Skip to main content

Creation of simple login application using Servlet, Testing the application using JUnit, and Deloying the application into Apache server.

Here I am using Eclipse for developing this application. In this application i hard coded user name and password. In real application these values are fetched from database.

1. Create a new dynamic web project and name it as ServletStudy.

2. Inside the WebContent folder ,create a index.jsp file and include the following code.

      <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
          pageEncoding="ISO-8859-1"%>
          <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org 
          /TR/html4/   loose.dtd">
         <html>
              <head>
                  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
                  <title>Login</title>
              </head>
             <body>
                <form method="post" action="loginController">
                     User Name: <input type="text" name="userName" /> <br/>
                     Password: <input type="password" name="password" /><br/>
                    <input type="submit" name="submit" value="Login" /><br/>   
                </form>
             </body>
         </html>

3. Inside the WebContent folder, create a new success.jsp file and include the following code.

        <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
         pageEncoding="ISO-8859-1"%>
        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org
          /TR/html4/loose.dtd">
        <html>
           <head>
               <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
               <title>Login Success</title>
           </head>
            <body>
              <h3>Successfully logged into your home page </h3>
           </body>
      </html>

4. Inside the WebContent folder, create a new loginfailure.jsp file and include the following code.
        <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
              pageEncoding="ISO-8859-1"%>
        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org
        /TR/html4/loose.dtd">
       <html>
           <head>
                <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
                <title>Login Failure</title>
          </head>
          <body>
                <h3>Your username or password incorrect... </h3>
         </body>
      </html>


5. Inside the src folder create a com.util package. Create a new LoginCheck class into inside a com.util package. Add one new checkUserNameAndpassword function  into LoginCheck class and include the following code.


package com.utils;

public class LoginCheck {
      public boolean checkUserNameAndPassword(String userName,String password){
            boolean loginStatus = false;
            if((userName.equals("admin") && password.equals("admin"))){
                  loginStatus = true;
            }
            return loginStatus;
      }
}

6. Inside the src folder create a com.test package. Inside the com.test package, create a one new LoginControllerTest class, the class extends the Junit TestCase. Include the following code into LoginControllerTest class.


package com.test;

import com.utils.LoginCheck;

import junit.framework.TestCase;

public class LoginControllerTest extends TestCase{
      private LoginCheck loginCheck = null;
      public void setUp(){
            try {
                  loginCheck = new LoginCheck();
                  super.setUp();
            } catch (Exception e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
      }
      public void tearDown(){
            try {
                  loginCheck = null;
                  super.tearDown();
            } catch (Exception e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
      }

      public void testCheckUserNameAndPassword(){
            assertTrue(loginCheck.checkUserNameAndPassword("admin", "admin"));
            assertFalse(loginCheck.checkUserNameAndPassword("admin", "password"));
      }
}




7. Inside the LoginControllerTest class Right click --> Run as --> Junit test . Check whether the test are passed or not.

8. Create a new servlet and name it as LoginController as show here.


package com.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginController")
public class LoginController extends HttpServlet {
      private static final long serialVersionUID = 1L;

      public LoginController() {
        super();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String userName = request.getParameter("userName");
            String password = request.getParameter("password");
            if((userName.equals("admin") && password.equals("admin"))){
                  //Redirect to success page.
                  response.sendRedirect("success.jsp");
            }
            else{
                  //Redirect error page.
                  response.sendRedirect("loginfailure.jsp");
            }
      }
}

9. Configuration of web.xml file and servlet mapping. Include the following code into web.xml file.


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ServletStudy</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
      <servlet-name>LoginController</servlet-name>
      <servlet-class>com.controller.LoginController</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>LoginController</servlet-name>
      <url-pattern>/loginController</url-pattern>
  </servlet-mapping>
</web-app>
  
The final file structure look likes

 
10. Creating war file and deploying into tomcat server.

         Right click a ServletStudy root folder --> Export -->Choose WAR --> Give application name and select your file path for where you want to store a WAR file. Refer the below screen shots.



11. After creating war go to your tomcat installed path. Here I am installed tomcat in following location. "D:\Apache Tomcat 7.0.11".
             Go to tomcat bin directory and run the tomcat server ie run the startup.bat present in "D:\Apache Tomcat 7.0.11\bin".

      If you have any problem in server start up check your java environment variable setups in windows.




12. Copied your war file and paste into webapps folder.
      Now your application was successfuly deployed into apache server.
      Trying to access the application through following url.
       http://localhost:8080/ServletStudy/
         The port number was based on your tomcat server setup. If you want to know your port number then go to your config folder and open the server.xml file and check the Connector port value.


Comments

Popular posts from this blog

Ext JS 4 – Creating web page using Ext.container.Viewport class and region propery

The Ext.container.Viewport is used for creating general web page and region property is used for splitting web page into different parts. Ext.container.Viewport is a specialized container represents the viewable area of the application (the browser area). It render itself to the document body, there is no need for providing renderTo property and it automatically sizes itself to size of the browser viewport. The viewport also re-size the child elements based on view area(based on browser width and height). The default layout of the viewport is border layout and we can customize this property according to our requirements. The viewport does not provide any scrolling. If necessary, the child elements(generally panels) within viewport needs to provide a scroll feature by using autoScroll property. See the below example for better understanding. This is Home.js file placed into app/view folder. Ext.define('MyApp.view.Home', { extend : 'Ext.container.Viewport&#

Getting servlet init parameter that is defined in web.xml

1. Create a new dynamic web project using eclipse. 2. Create a one new servlet and include the following code. package com.controller ; import java.io.IOException; import javax.servlet .ServletConfig; import javax.servlet .ServletException; import javax.servlet .annotation.WebServlet; import javax.servlet .http.HttpServlet; import javax.servlet .http.HttpServletRequest; import javax.servlet .http.HttpServletResponse; @ WebServlet ( "/LoginController" ) public class LoginController extends HttpServlet {                 private static final long serialVersionUID = 1L;                 public LoginController() {         super ();     }     protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {                                 ServletConfig config = getServletConfig ();                                 System.out.println( "Init parameter user nam

Simple Login Application Using Spring MVC and Hibernate – Part 1

 I hope developers working in web application development might hear about MVC architecture. Almost all technologies provide support for MVC based web application development, but the success is based on many factors like reusable of the code, maintenance of the code, future adaption of the code, etc..,  The success of the Spring MVC is “ Open for extension and closed for modification ” principle. Using Spring MVC the developers can easily develop MVC based web application. We don’t need any steep learning curve at the same time we need to know the basics of spring framework and MVC architecture. The Spring MVC consists of following important components. 1. Dispatcher servlet 2. Controller 3. View Resolver 4. Model Spring MVC - Overview  The overall architecture of Spring MVC is shown here.  1. When “Dispatcher Servlet” gets any request from client, it finds the corresponding mapped controller for the request and just dispatches the request to the corresponding contro