Learn Servlet-JSP By Building A Social Network Website — Part V

Sera Ng.
Tech Training Space
9 min readOct 25, 2020

Learn the forwarding and redirecting techniques to apply in implement the account registration feature

Task 7: Reading: Redirect — Forward

Before we implement any features in our web application, we need to discuss the two fundamental and very important techniques in web development: redirect and forward.

These two techniques are used to transfer a request from one web element (servlet, JSP, etc) to another. But they are fundamentally different.

Let’s discuss the Forward technique

1: Web browser sends a request to the RegisterController, the RegisterController forwards to the register.jsp with all data in the request object

2: The register.jsp receives a request from the RegisterController and performs its own business logic

3: The register.jsp generates HTML page and sends back to the web browser

Now let’s take a look at the flow of a Redirect action

1: Web browser sends a request to the RegisterController, the RegisterController redirects to the register.jsp.

2: Since the RegisterController recognizes that is a redirecting request, it sends back the response to the web browser with the redirected URL. And because the response has been sent back to the web browser, the request object has no longer existed which leads to data in the request object also is removed.

3: The web browser performs a new request with the redirected URL received from the RegisterController (register.jsp)

4: The register.jsp receives the request, performs its own business logic, generates HTML page, and sends back to the web browser

As you have observed the two techniques, the biggest difference is that in the Redirect, the web browser needs to conduct a new request to the redirected target. And that causes data in the previous request has no longer existed.

Which technique to use really depends on particular situations and whether we want to keep previous data in the request object or not. In the log-out feature for instance, once users sign out, it should be redirected to the home page so that all previous data will be completely removed.

Task 8: Implement Account Registration

By the end of this task, users will be able to create a new account in our system.

The main flow is as follows:

Users navigate to register.jsp page and input their account information and click the “Create an account” button

User’s inputs will be validated

  • If one of the inputs is invalid, users will be forwarded to the register.jsp page again with an error message
  • If all the provided information is correct, a new account is created in the database and the user will be redirected to the login.jsp page

Step 1: in the package net.learnbyproject.helper, create a new Java class called Validator with the following members:

I have used some regular expressions to perform some basic validations:

  • The name should contain a — z, A — Z, and whitespace character with a minimum of 3 characters and a maximum of 50
  • Since we allow users to use either email or phone number to create an account, we need to check either one being the correct format.
  • Email must be in either format: email@domain.abc or email@domain.abc.xyz
  • Phone number must be digits with a minimum of 9 digits and a maximum of 11 digits

To help users to increase security, we enforce the password:

  • at least 4 chars, max 8 chars
  • contains at least one digit
  • contains at least one upper alpha char

If you are not familiar with regular expression, check out the Regular Expression Tutorials here

Also, in the same package, create another class called Keys:

The Keys class stores constants which will be used for attributes in session and request objects. Attributes are the way we pass data among servlets and JSPs.

Step 2: in the package net.learnbyproject.model, create User class:

The User class is corresponding to the tbl_user table in the database. When fetching a record from the tbl_user in the data, we store necessary details in an instance of the User class. This is very convenient for transferring user details among servlets as well as JSPs.

Step 3: in the package net.learnbyproject.service, create UserService class. This class will contain user-related business logic code:

Before adding a new account to the database, we need to invoke the method isDuplicateEmailOrPhone() to make sure that there is no duplicate email address or phone number.

Once all the inputs are valid, the addNewUser() will be called to insert a new row in the database.

Note in the insert query statement:

String insert = “Insert into tbl_user Values(null,?,?,?,?,?,?,null)”;

The first parameter is null because that is the auto-increased primary key.

The last parameter is also null because that is the avatar column which we don’t ask users at the time they register a new account. Rather, we will allow users to upload their avatar later on on the profile page.

Step 4: in the package net.learnbyproject.controller, create a servlet called RegisterController. This is the controller that will handle account registering requests.

In Netbeans, you can quickly create a new servlet as follows:

Right click on the package net.learnbyproject.controller, select New -> select Servlet… item

Creating a new servlet

Input your servlet name, which is RegisterController in this case

Click the Next button.

Don’t check the option “Add information to deployment descriptor (web.xml)” because we are not going to configure servlet mapping in the web.xml. Rather, we will achieve this task using annotation. This will helps to reduce the complexity of the web.xml file.

By default, the servlet name “RegisterController” will be used as URL pattern, the one that users will be used to send requests to our servlet. We don’t want to keep that default name since the semantic is not so clear.

To change that default name to something more semantic, in the URL Pattern(s) text field, change to /register, or any name that you wish.

Click the Finish button when you are done.

By default, Netbeans generates quite a lot of comments, methods, and other HTML tags, remove those so that your servlet looks like this:

Note I have also removed the name = “RegisterController” attribute in the @WebServlet() annotation.

The attribute urlPatterns = {“/register”} is used to inform the web browser that this is the way to send requests to the RegisterController servlet.

In the servlet, Netbeans generates three methods: processRequest(), doGet(), and doPost().

The one that is actually invoked when the servlet receives requests from the web browser is either doGet() or doPost() depending on the form method as we have mentioned in the previous session. So, basically, we just need one of those three methods.

However, since we might be using both Get and Post methods in the form or at least, we don’t want to care about whether Get or Post is sent from the web browser, the neutral processRequest() method is created and invoked in both doGet() and doPost() methods. This way, either Get or Post is in the form request, the processRequest() is always executed.

Let’s leave the RegisterController servlet for now, we’ll get back to it later.

Step 5: update register.jsp file

Open the register.jsp file, add the following 2 lines of code at the top of the page:

<%@page import=”net.learnbyproject.helper.Keys”%>
<%@page import=”java.util.Objects”%>

This is the way we import classes to be used in a JSP file.

Then, scroll down and find the <form> tag similar to:

<form … class=”register-form”>

Right above that <form> tag, add the following code:

<div class=”alert-danger”>
<%= Objects.toString(request.getAttribute(Keys.ERROR), “”)%>
</div>

The above code is used to display an error message in case one of the inputs is invalid. The tag <%= … %> in JSP is called an expression tag which is used to display a certain value received from the Java back-end code.

We use request.getAttribute(Keys.ERROR) to get the attribute value from the RegisterController servlet with the key Keys.ERROR that we have defined in the Keys class previously.

Also, the piece of code needs to place in the Objects.toString() method because this method will return and empty string (specified in the second parameter) if request.getAttribute(Keys.ERROR) is null; otherwise, request.getAttribute(Keys.ERROR) will be returned.

If we just put the code like:

<%= request.getAttribute(Keys.ERROR) %>

Then a null string will be displayed in the web browser in case there is no attribute key of the Keys.ERROR defined yet such as when the register.jsp page is first loaded.

Now, let’s update the <form> tag as follows:

In the <form> tag, I have specified:

  • the method as Post because the form contains sensitive information to be sent to the server
  • the action as “register” which has been defined in @WebServlet(urlPatterns = {“/register”}) in RegisterController servlet. That means when the form is submitted, the form data will be sent to the RegisterController to be processed further.

You can also observe the value attribute in the <input> tags, for instance:

<input type=”text” name=”first-name” value=”<%= Objects.toString(request.getParameter(“first-name”), “”)%>” placeholder=”First name”>

The purpose of having

value=”<%= Objects.toString(request.getParameter(“first-name”), “”)%>”

is that we want to keep the value a user had inputted previously in case the form had been submitted and returned back to the register.jsp page. Otherwise, the user has to input all the information again.

That is the way we keep the inputted values in <input> tag with the type of text.

But in our form, we have other kinds of inputs as well:

If we want to keep the selected item in the dropdown list and in the radio input type, we need to write some jQuery code.

Scroll down to the <script> tag at the bottom of the register.jsp file, and update your <script> as with the following:

Step 6: Update RegisterController servlet

Locate the processRequest() method in the RegisterController servlet.

First, we need to get inputs from the users:

Data in <form> tag is sent in form of parameters in the request object. So, we invoke the request.getParameter() method and supply the input name to extract the inputted value.

Make sure you use the correct names defined in the <input> tags in the register.jsp. For instance,

<input type=”text” name=”first-name” …>

Next, we need to perform validations on the inputted information:

If one of the inputs is invalid, we set an error message to the request attribute and forward it to the register.jsp

If all the information is correct, we create a new account and redirect to the login page

To achieve a forwarding action, we use the RequestDispatcher class:

RequestDispatcher dis = request.getRequestDispatcher(“register.jsp”);
dis.forward(request, response);

Note in this case we have to perform a forward to the register.jsp, not a redirect, because we have attached an attribute with an error message to the request object, and that message needs to be extracted and displayed in the register.jsp page.

Once a new account has been added, we need to redirect to the login page so that all previous inputs in the form will be clear:

response.sendRedirect(“login.jsp”);

Here is the complete code in the processRequest() method:

Let’s run your web page. But you should clean and build your project first.

In Netbeans, you can right-click on the register.jsp and select Run:

If you just leave everything blank and click the “Create an account” button, you will see the error message:

So, let give yourself some time to test the page.

If all inputs are correct, you will be redirected to the login page. Check your database, you will see a new row inserted in the tbl_user table.

If you get stuck, check out the complete source code for this task:

https://github.com/stackera/learn-servlet-jsp/blob/main/Task8_Impl_RegisterAccount.zip

--

--