0

I have a form for registration on my website. When submitting the form, a Java Servlet is called. Within the Servlet I check my database if the username or email is already used. I want the Servlet to respond if the registration was completed or not and I want my client to receive this response and act accordingly. A simple result could be a text above the registration form saying "Registration successful" or "Email/username already in use". How can I let my client receive the response from the Servlet?

My form

<form id="registerForm" autocomplete="on">
  <h1>Registrera</h1>
  <p>
    <label for="usernamesignup" class="uname" data-icon="u">Användarnamn</label> 
    <input id="usernamesignup" name="usernamesignup" required="required" type="text"
    placeholder="användarnamn" />
  </p>
  <p>
    <label for="emailsignup" class="youmail" data-icon="e">E-mail</label> 
    <input id="emailsignup" name="emailsignup" required="required" type="email"
    placeholder="namn@mail.com" />
  </p>
  <p>
    <label for="passwordsignup" class="youpasswd" data-icon="p">Lösenord</label> 
    <input id="passwordsignup" name="passwordsignup" required="required" type="password"
    placeholder="lösenord" />
  </p>
  <p>
    <label for="passwordsignup_confirm" class="youpasswd" data-icon="p">Upprepa lösenord</label> 
    <input id="passwordsignup_confirm" name="passwordsignup_confirm" required="required" type="password"
    placeholder="lösenord" />
  </p>
  <p class="signin button">
    <input type="submit" value="Registrera"/>
  </p>
  <p class="change_link">
    Redan medlem? <a href="#tologin" class="to_register">Logga in</a>
  </p>
</form>

My Servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String username = request.getParameter("usernamesignup");
    String email = request.getParameter("emailsignup");
    String password = request.getParameter("passwordsignup");

    try {
        MysqlDataSource dataSource = new MysqlDataSource();
        ...

        Connection conn = dataSource.getConnection();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM Users WHERE username = '" + username + "' OR email = '" + email + "'");

        if (!rs.next()) {
            stmt.executeUpdate("INSERT INTO Users VALUES('" + username + "', '" + password + "', '" + email + "')");
            //Notify the client that the registration was successful!
        } else {
            //Notify the client that the registration failed!
        }
        ...
    }
}

My solution

I went for a solution where I send redirects from my Servlet and append a status parameter. Core JSTL then retrieves this parameter and display a message accordingly. I do the following in my Servlet:

ResultSet rs = stmt.executeQuery("SELECT * FROM Users WHERE username = '" + username + "' OR email = '" + email + "'");

if (!rs.next()) {
    stmt.executeUpdate("INSERT INTO Users VALUES('" + username + "', '" + password + "', '" + email + "')");
    //Registration was successful!
    response.sendRedirect ("pages/index.jsp?status=1");
} else {
    //Registration failed
    response.sendRedirect ("pages/index.jsp?status=2#toregister");
}

and in my JSP I do:

<div id="registerMessage">
    <c:set var="status" value="${param.status}" />
    <c:if test="${status == '1'}">
        <p class="success">Du är nu registrerad och kan logga in!</p>
    </c:if>
    <c:if test="${status == '2'}">
        <p class="fail">Användarnamnet eller email adressen finns redan!</p>
    </c:if>
</div>

3 Answers3

1

A simple way to do this is to send a response back to the client in the form of html:

response.setContentType("text/html");
PrintWriter out = response.getWriter();  //Returns a PrintWriter object that can send character text to the client
out.println("<h1>Registered successfully</h1>");

For more information, go through these Tutorials

If you dont want the page to reload then you should:

  • send Ajax request to your servlet via Javascript
  • check the values sent to your Servlet as you are doing right now and send the response as I mentioned in code above (you can send a boolean value for success or failure to later check in Javascript)
  • you you will receive response data in Javascript as Ajax response
  • now you can set the result of response accordingly in your specific div.

    See this answer for more information on how to use Ajax with Servlets.

Community
  • 1
  • 1
Iffat Fatima
  • 1,610
  • 2
  • 16
  • 27
  • Thanks for the answer. I know this is one solution. The problem is that I want the message to appear on the URL that I submitted the form from and I want it to appear at a certain position on the page (say inside a div placed above the register form). – Richard Silvertass Mar 05 '16 at 19:54
  • @RichardSilvertass I have edited the answer, have a look. I hope it helps – Iffat Fatima Mar 05 '16 at 20:08
  • Can you give me an example how to submit the form in javascript by using Ajax and catch the responses (both a successful registration and a non successful one)? – Richard Silvertass Mar 05 '16 at 20:21
  • @RichardSilvertass see here http://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax or google it. Its fairly simple. – Iffat Fatima Mar 05 '16 at 20:23
  • I checked out the link and changed my form to this: `
    ...
    ` And my javascript has this: `$(document).on("submit", "#registerForm", function(event) { alert("Registering"); $.get("registrationServlet", function(responseText) { alert(responseText); }); });` But my function isn't called. Can you see why?
    – Richard Silvertass Mar 05 '16 at 20:46
  • @RichardSilvertass I need to see the complete code to help you. How are you submitting the form? on a button click ? – Iffat Fatima Mar 05 '16 at 20:51
  • My whole form can be found in my original post. – Richard Silvertass Mar 05 '16 at 20:59
  • @RichardSilvertass have you downloaded JQuery and included it in your html file ? If not add this in your head tag It should work. – Iffat Fatima Mar 05 '16 at 21:07
  • I added jQuery to my page (embarrassing that I had forgotten) and now my javascript function is called. The Servlet is also called BUT not my callback function. In my Servlet I tried to create a simple response: `String text = "some text"; response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(text);` Any idea why my callback function isn't called? – Richard Silvertass Mar 05 '16 at 21:32
  • @RichardSilvertass Check if the syntax of ajax is correct or not. Try using console.log(data) or alert statements in your JS to debug as to why the call back function is not called. – Iffat Fatima Mar 05 '16 at 21:38
  • It seems like my callback function is called and my alert is shown when I don't do my database operations in the Servlet. But once I start doing them, the alert isn't shown anymore. Any ideas? – Richard Silvertass Mar 05 '16 at 22:08
0

I assume that you used jsp for the registration form..

Case in which username already in use:

From servlet send a variable " status=1" via url..

   response.sendRedirect ("registration.jsp?status=1);

If the registration is successfull from servlet send a variable "status=2 " via url

   response.sendRedirect ("registration.jsp?status=2);

Now in jsp under user id text box code or in any specific div above the form use this code..

    <% String s=request.getParameter("status");
         If (s==null)
          {  }
         else if (s.equals ("1"))
         {
    %>
   <br/><h3>  user id already exist </h3>
    <%} 
         else if (s.equals ("2"))
         {
    %>
   <br/><h3> registration successfull</h3>
    <%}
         else { }%>

It should work fine.

0

Simplest way i can think of, You can hide the variable say msg in some div like {msg} on registration Page under the submit say , and fill this variable with value in servlet doget or dopost (which ever you are using)

doGet(...){
//code for deal with db
if(succesfullRegistration)
request.setAttribute("msg", "Registration Succesfull! Please Login and Proceed..or what ever you want to show...");
else
request.setAttribute("msg", "User already Exists");
}
// forward the request to same registration page.
} 

for Asnyc , do it with ajax.

umesh
  • 231
  • 1
  • 14