Creating Java Web Application from Scratch- Java,Servlet, JSP, MySQL

This post for the developer who already gone through Basic Core Java concepts and ready to push themselves to next level.We recommend you to read Servlet Basics Tutorial before looking into this application,  In this post, we are going to create a Java web application from scratch.We will try our level best to keep it very simple so that it will be really helpful to new learners.We are not using any framework in this application only advanced Java (J2EE) concepts are used.

Note:You can bookmark this page as we will proceed step by and update it accordingly.

Software we are going to use:

  • Eclipse-jee-mars-2-win32-x86_64
  • apache-tomcat-8.0.33
  • apache-maven-3.3.9
  • mysql-5.1.73-winx64.msi
  • JDK 1.8


Software Installation:

Before we start our application development we have to do our environment set up.
Keep all the software mentioned above in your machine.

Scope:
In this application, we are going to develop a small application with multiple modules.Once application started home page will be visible.

Login Module-User can  Login into application and Logout.After login user can see home page with his username at the top,

Add Employee-User can add the employee.If the  user is already logged in he will get Add Employee page else, Login Page.After logging in he will get Add Employee.

Search Employee-To search the employee.

Application Development:
Create Maven Web Application and import in Eclipse. 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javainstance</groupId>
  <artifactId>JavaWebApp</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>JavaWebApp Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
    
  </dependencies>
  <build>
    <finalName>JavaWebApp</finalName>
     <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            </plugins>
            
  </build>

</project>


Below is the code for Login Module.

String encodeRedirectURL(String URL) - This method encodes the URL passed as parameter and then we send it to the sendRedirect method.If encoding is not required it passes the URL unchanged.

void sendRedirect(String path) - It redirects the response to the client using  specified path.

getRequestDispatcher(String path).include(request, response)- Include the content of the resource in the response.In this application, we are using it in LoginServlet and LogoutServlet where we are sending the message by setting on PrintWriter object and redirecting to the new page.

You can go through  doGet and doPost once.

To Handle Login Request

LoginServlet.java

package com.javainstance.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author javainstance
 *
 */
public class LoginServlet extends HttpServlet {


public LoginServlet() {
super();

}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String encodedURL = response.encodeRedirectURL("login.jsp");
response.sendRedirect(encodedURL);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();

String user = request.getParameter("username");
String password = request.getParameter("password");

if (user.equalsIgnoreCase("admin") && password.equals("admin")) {

session.setAttribute("user", user);
if (session.getAttribute("requestfrom") != null) {
String encodedURL = response.encodeRedirectURL("addemployee.jsp");
response.sendRedirect(encodedURL);
} else {

String encodedURL = response.encodeRedirectURL("home.jsp");
response.sendRedirect(encodedURL);
}
} else {
PrintWriter out = response.getWriter();
request.getRequestDispatcher("login.jsp").include(request, response);
out.print("Wrong Credentials!");

out.close();

}

}


}

To handle Logout Request

LogoutServlet.java

package com.javainstance.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author javainstance
 *
 */
public class LogoutServlet extends HttpServlet {

public LogoutServlet() {
super();

}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
PrintWriter out = response.getWriter();
if (session != null) {
session.invalidate();
response.setContentType("text/html");
request.getRequestDispatcher("login.jsp").include(request, response);
out.print("Logout Successful!");

out.close();
}
}


}

To handle add employee request.

AddEmployeeServlet.java

package com.javainstance.servlet;

import java.io.IOException;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author javainstance
 *
 */
public class AddEmployeeServlet extends HttpServlet {

public AddEmployeeServlet() {
super();

}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
if (session.getAttribute("user") != null) {
String encodedURL = response.encodeRedirectURL("addemployee.jsp");
response.sendRedirect(encodedURL);
} else {
session.setAttribute("requestfrom", "addemp");

String encodedURL = response.encodeRedirectURL("login.jsp");
response.sendRedirect(encodedURL);
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}


}

JSP Pages

addemployee.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ include file="header.jsp" %>
<!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>Insert title here</title>
</head>
<body>
<table border="2px" style="color: green">
<tr>
<td>Employee Number</td>
<td><input type="text" name="enumber"/></td>
</tr>
<tr>
<td>Employee Name</td>
<td><input type="text" name="ename"/></td>
</tr>
<tr>
<td>Employee Department</td>
<td><input type="text" name="edept"/></td>
</tr>
<tr>
<td><input type="submit" value="Add Employee"></td>
</tr>
</table>
</body>
</html>



header.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Insert title here</title>
</head>
<body>

<table>
<tr>
<td> <h1>Employee Management System</h1></td>
<c:choose>
<c:when test="${sessionScope.user!=null}">
<td>Welcome</td>
<td style="color: blue;"> ${sessionScope.user}</td>
<td><a href="LogoutServlet">Logout</a></td>
<br />
</c:when>
<c:otherwise>
<td><a href="LoginServlet">Login</a></td>
<br />
</c:otherwise>
</c:choose>
<td><a href="home.jsp">Home</a></td>
</tr>
</table>
</body>

</html>


home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ include file="header.jsp"%>
<!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>Insert title here</title>
</head>
<body>
<table border="2px">
<tr>
<td><a href="EmployeeServlet">Add Employee</a></td></tr>
<tr><td><a href="">Search Employee</a></td></tr>
</table>
</body>

</html>







login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Insert title here</title>
</head>
<body>
<h1>Login Page</h1>

<form action="LoginServlet" method="post">
<table>
<tr>
<td>UserName</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td><input type="submit" value="Login" /></td>
</tr>
</table>
</form>
</body>

</html>




web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>
    <welcome-file>home.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.javainstance.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
   <servlet>
    <description></description>
    <display-name>LogoutServlet</display-name>
    <servlet-name>LogoutServlet</servlet-name>
    <servlet-class>com.javainstance.servlet.LogoutServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LogoutServlet</servlet-name>
    <url-pattern>/LogoutServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>EmployeeServlet</display-name>
    <servlet-name>EmployeeServlet</servlet-name>
    <servlet-class>com.javainstance.servlet.AddEmployeeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>EmployeeServlet</servlet-name>
    <url-pattern>/EmployeeServlet</url-pattern>
  </servlet-mapping>

</web-app>


In next part, we will work on database connectivity.

You may be interested in Deploying Maven Application on Tomcat.

Give your suggestion in comments.
If you like the post Share with your friends on social network.

6 Different ways to iterate through HashMap



.







Creating Java Web Application from Scratch- Java,Servlet, JSP, MySQL Creating Java Web Application from Scratch- Java,Servlet, JSP, MySQL Reviewed by JavaInstance on 4:41:00 AM Rating: 5

1 comment:

Powered by Blogger.