Java Servlet

We will now see how to implement a login application using Java Servlet. Create a new Dynamic Web Application in Eclipse as described in the previous section. We will call this LoginServletApp:

  1. Right-click on the src folder under Java Resources for the project in Project Explorer. Select the New | Servlet menu option.
  2. In the Create Servlet wizard, enter package name as packt.book.jee_eclipse.book.servlet and class name as LoginServlet. Then, click Finish.
Figure 2.22: Create Servlet wizard
  1. The servlet wizard creates the class for you. Notice the @WebServlet("/LoginServlet") annotation just above the class declaration. Before JEE 5, you had to declare servlets in web.xml in the WEB-INF folder. You can still do that, but you can skip this declaration if you use proper annotations. Using WebServlet, we are telling the servlet container that LoginServlet is a servlet, and we are mapping it to the /LoginServlet URL path. Thus, we are avoiding the following two entries in web.xml by using this annotation: <servlet> and <servlet-mapping>.

We will now change the mapping from /LoginServlet to just /login. Therefore, we will modify the annotation as follows:

@WebServlet("/login") 
public class LoginServlet extends HttpServlet {...} 
  1. The wizard also created the doGet and doPost methods. These methods are overridden from the following base class: HttpServlet. The doGet method is called to create response for the Get request and doPost is called to create a response for the Post request.

We will create a login form in the doGet method and process the form data (Post) in the doPost method. However, because doPost may need to display the form, in case user credentials are invalid, we will write a createForm method, which could be called from both doGet and doPost.

  1. Add a createForm method as follows:
protected String createForm(String errMsg) { 
 StringBuilder sb = new StringBuilder("<h2>Login</h2>"); 
//check whether error message is to be displayed 
  if (errMsg != null) { 
    sb.append("<span style='color: red;'>") 
      .append(errMsg) 
      .append("</span>"); 
  } 
  //create form 
  sb.append("<form method='post'>n") 
    .append("User Name: <input type='text' 
name='userName'><br>n") .append("Password: <input type='password'
name='password'><br>n") .append("<button type='submit'
name='submit'>Submit</button>n") .append("<button type='reset'>Reset</button>n") .append("</form>"); return sb.toString(); }
  1. We will now modify a doGet method to call a createForm method and return the response:
protected void doGet(HttpServletRequest request, 
HttpServletResponse response) throws ServletException, IOException { response.getWriter().write(createForm(null)); }

We call the getWrite method on the response object and write the form content to it by calling the createForm function. Note that when we display the form, initially, there is no error message, so we pass a null argument to createForm.

  1. We will modify doPost to process the form content when the user posts the form by clicking the Submit button:
protected void doPost(HttpServletRequest request, 
HttpServletResponse response) 
  throws ServletException, IOException { 
    String userName = request.getParameter("userName"); 
    String password = request.getParameter("password"); 
 
  //create StringBuilder to hold response string 
  StringBuilder responseStr = new StringBuilder(); 
  if ("admin".equals(userName) && "admin".equals(password)) { 
    responseStr.append("<h2>Welcome admin !</h2>") 
    .append("You are successfully logged in"); 
  } 
  else { 
    //invalid user credentials 
    responseStr.append(createForm("Invalid user id or password. 
Please try again")); } response.getWriter().write(responseStr.toString()); }

We first get username and password from the request object by calling the request.getParameter method. If the credentials are valid, we add a welcome message to the response string; or else, we call createForm with an error message and add a return value (markup for the form) to the response string.

Finally, we get the Writer object from the response string and write the response.

  1.  Right-click on the LoginServlet.java file in Project Explorer and select the Run As | Run on Server option. We have not added this project to the Tomcat server. Therefore, Eclipse will ask if you want to use the configured server to run this servlet. Click the Finish button of the wizard.
  2. Tomcat needs to restart because a new web application is deployed in the server. Eclipse will prompt you to restart the server. Click OK.

When the servlet is run in the internal browser of Eclipse, notice the URL; it ends with /login, which is the mapping that we specified in the servlet annotation. However, you will observe that instead of rendering the HTML form, the page displays the markup text. This is because we missed an important setting on the response object. We did not tell the browser the type of content we are returning, so the browser assumed it to be text and rendered it as plain text. We need to tell the browser that it is HTML content. We do this by calling response.setContentType("text/html") in both the doGet and the doPost methods. Here is the complete source code:

package packt.book.jee_eclipse.book.servlet; 

// skipping imports to save space /** * Servlet implementation class LoginServlet */ @WebServlet("/login") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; public LoginServlet() { super(); } //Handles HTTP Get requests protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.getWriter().write(createForm(null)); } //Handles HTTP POST requests protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter("userName"); String password = request.getParameter("password"); //create StringBuilder to hold response string StringBuilder responseStr = new StringBuilder(); if ("admin".equals(userName) && "admin".equals(password)) { responseStr.append("<h2>Welcome admin !</h2>") .append("You're are successfully logged in"); } else { //invalid user credentials responseStr.append(createForm("Invalid user id or password.
Please try again")); } response.setContentType("text/html"); response.getWriter().write(responseStr.toString()); }

//Creates HTML Login form protected String createForm(String errMsg) { StringBuilder sb = new StringBuilder("<h2>Login</h2>"); //check if error message to be displayed if (errMsg != null) { sb.append("<span style='color: red;'>") .append(errMsg) .append("</span>"); } //create form sb.append("<form method='post'>n") .append("User Name: <input type='text'
name='userName'><br>n") .append("Password: <input type='password'
name='password'><br>n") .append("<button type='submit'
name='submit'>Submit</button>n") .append("<button type='reset'>Reset</button>n") .append("</form>"); return sb.toString(); } }

As you can see, it is not very convenient to write HTML markup in servlet. Therefore, if you are creating a page with a lot of HTML markup, then it is better to use JSP or plain HTML. Servlets are good to process requests that do not need to generate too much markup, for example, controllers in Model-View-Controller (MVC) frameworks, for processing requests that generate a non-text response, or for creating a web service or WebSocket endpoints.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.62.122