Servlet Example in Java with Database Connection

We are going to develop a web application in which User can register and then login to the application.We are going to maintain user information in DB.We are using mysql database, so we need to create a table first as given below.We use Eclipse IDE for Java EE Developers which includes tools for creating Java EE and Web applications.


CREATE TABLE  USERDETAILS   
   ( NAME VARCHAR(100),   
    PASSWORD VARCHAR(50),   
    EMAIL VARCHAR(50),   
    LANGUAGE VARCHAR(50)  
   ); 

We are going to develop a web application in which User can register and then login to the application.We are going to maintain user information in DB.We are using mysql database, so we need to create a table first as given below.We use Eclipse IDE for Java EE Developers which includes tools for creating Java EE and Web applications.


CREATE TABLE  USERDETAILS   
   ( NAME VARCHAR(100),   
    PASSWORD VARCHAR(50),   
    EMAIL VARCHAR(50),   
    LANGUAGE VARCHAR(50)  
   ); 


Directory Structure Of Project

Servlet Database Example

Steps to create Registration form in servlet

Create a dynamic Web Project in Eclipse and assign the name of project as ServletDBExample as shown below.

Servlet Database Example

Now create a jsp file inside WebContent directory of your project and provide the name of jsp file as register.jsp and add following code into this file.

register.jsp

In this page,user will provide inputs using text fields and combobox. The information entered by the user is forwarded to RegisterServlet, which is responsible to store the data into the database.

<%@ 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>
<body>
	<form action="register" method="post">

		Name:<input type="text" name="userName"/><br/>
		Password:<input type="password" name="password"/><br/>
	    Email Id:<input type="text" name="email" /><br/>
		Language: <select name="language">
			<option>Hindi</option>
			<option>English</option>
			<option>French</option>
		</select> <br/>
		<input type="submit" value="Submit"/>

	</form>
</body>
</html>

RegisterServlet.java

Now create a package com.jwt.servlet and in that package create a class RegisterServlet and add following code into this. This servlet class receives all the data entered by user and stores it into the database. Here, we are performing the database logic.

package com.jwt.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

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

public class RegisterServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		String n = request.getParameter("userName");
		String p = request.getParameter("password");
		String e = request.getParameter("email");
		String c = request.getParameter("language");

		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/servlet", "root", "mukesh");

			PreparedStatement ps = con
					.prepareStatement("insert into USERDETAILS values(?,?,?,?)");

			ps.setString(1, n);
			ps.setString(2, p);
			ps.setString(3, e);
			ps.setString(4, c);

			int i = ps.executeUpdate();
			if (i > 0)
				out.print("You are successfully registered...");

		} catch (Exception e2) {
			System.out.println(e2);
		}

		out.close();
	}

}

web.xml

Map the servlet in 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_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<servlet>
		<servlet-name>Register</servlet-name>
		<servlet-class>com.jwt.servlet.RegisterServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>Register</servlet-name>
		<url-pattern>/register</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>register.jsp</welcome-file>
	</welcome-file-list>

</web-app>  


Note:-We need to add mysql connector jar in the lib folder of the project for getting the MYSQL DB connection using java.

Run the Application

Right Click on the project and select Run as -> Run on Server and select the Tomcat Server and add your project in the server and click Finish.

Output in Browser

Servlet Database Example

After providing the value when user clicks on Submit button user will be redirected to success page as shown below.

Servlet Database Example



comments powered by Disqus