Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Create an application for access JPA Entity class into Servlet
Previous Home Next

In this Servlet application, an Entity class which is part of Java Persistence API is accessed for inserting and fetching data through servlet.Consider following steps for create this application

Step-1 Create a new web project and name it as EntityServlet. Go to source package and name it as r4r.Entity.Servlet, now right click over package and go to New -> other ->New File, window open (as show into below picture). Now choose Persistence from the Categories list and and Entity Class from File Types list, then click on Next button.

Step-2 Now New Entity Class window open, Specify the values as shown in below picture, and don't forget to tick on check box for create Persistence Unit for application. After fill all the entry click on Next button.

Step-3 After Create Persistence Unit, now provide database connection to Persistence Unit as describe below image. It is not necessary to connect with EclipseLink(JPA 2.0), many other option are also available.

RememberTable Generation Strategy

Create- is use for create a table and use same table every time program is run.

Drop and Create- is used for create a table but it drop the old table and generate new one on same place every time program is run.

Application directory structure

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
  xmlns="http://java.sun.com/xml/ns/persistence" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
   http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
 <persistence-unit name="EntityServletPU"
			transaction-type="RESOURCE_LOCAL">
  <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
  <class>r4r.Entity.Servlet.ServletEntity</class>
  <exclude-unlisted-classes>false</exclude-unlisted-classes>
  <properties>
<property name="javax.persistence.jdbc.url"
	value="jdbc:mysql://localhost:3306/r4r"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" 
		value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
  </properties>
 </persistence-unit>
</persistence>

Entity Class

/*
 * Save as a ServletEntity.java
 */
package r4r.Entity.Servlet;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author R4R
 */
@Entity
@Table(name = "SERVLETENTITY")
@XmlRootElement
@NamedQueries({
 @NamedQuery(name = "ServletEntity.findAll", query = 
	      "SELECT s FROM ServletEntity s")
})
public class ServletEntity implements Serializable {

 private static final long serialVersionUID = 1L;
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Basic(optional = false)
 @Column(name = "ID")
 private Integer id;
 @Column(name = "FIRSTNAME")
 private String fname;
 @Column(name = "LASTNAME")
 private String lname;
 @Column(name = "CITY")
 private String city;
 @Column(name = "COUNTRY")
 private String country;

 //-------------------------- Constructor
 public ServletEntity() {
 }

 public ServletEntity(Integer id) {
  this.id = id;
 }

 public ServletEntity(Integer id, String fname,
	  String lname, String city, String country) {
  this.id = id;
  this.fname = fname;
  this.lname = lname;
  this.city = city;
  this.country = country;
 }

 @Override
 public int hashCode() {
  int hash = 0;
  hash += (id != null ? id.hashCode() : 0);
  return hash;
 }

 @Override
 public boolean equals(Object object) {
//TODO:Warning -this method won't work in the case the id fields are not set
  if (!(object instanceof ServletEntity)) {
return false;
  }
  ServletEntity other = (ServletEntity) object;
  if ((this.id == null && other.id != null) || 
	    (this.id != null && !this.id.equals(other.id))) {
return false;
  }
  return true;
 }

 @Override
 public String toString() {
  return "r4r.Entity.Servlet.ServletEntity[ id=" + id + " ]";
 }

 //------------------------------ Getter/Setter
 public Integer getId() {
  return id;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 public String getFname() {
  return fname;
 }

 public void setFname(String fname) {
  this.fname = fname;
 }

 public String getLname() {
  return lname;
 }

 public void setLname(String lname) {
  this.lname = lname;
 }
}			

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <servlet>
   <servlet-name>EntityServlet</servlet-name>
   <servlet-class>r4r.Entity.Servlet.EntityServlet</servlet-class>
  </servlet>
  <servlet-mapping>
        <servlet-name>EntityServlet</servlet-name>
        <url-pattern>/EntityServlet</url-pattern>
  </servlet-mapping>
  <session-config>
        <session-timeout>
            30
        </session-timeout>
  </session-config>
</web-app>

Index.jsp

<%-- 
 Document: index.jsp
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>r4r.co.in-index</title>
 </head>
 <body>
  <h1>Insert and Fetch data through Entity class!</h1>
  <form action="EntityServlet" method="POST">
   Firstname: <input type="text" name="fname"
    value="" size="30" maxlength="10" />(not null)<br/>
   Lastname: <input type="text" name="lname"
    value="" size="30" maxlength="10"/>(not null)<br/>
   City: <input type="text" name="city" 
    value="" size="30" maxlength="10" />(not null)<br/>
   Country: <input type="text" name="country"
    value="" size="30" maxlength="10"/>(not null)<br/>
   <input type="submit" value="Insert Data" name="insert" />
   <input type="submit" value="Fetch Data" name="fetch" />
  </form>
 </body>
</html>

Servlet Program

/*
 * Save as a EntityServlet.java
 */
package r4r.Entity.Servlet;
import java.io.*;
import java.util.List;
import javax.persistence.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
/**
 *
 * @author R4R
 */
public class EntityServlet extends HttpServlet {

 private static EntityManagerFactory emf;
 private static EntityManager em;

 @Override
 public void init() throws ServletException {
  emf = Persistence.createEntityManagerFactory("EntityServletPU");
  em = emf.createEntityManager();
 }

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

 @Override
 protected void doPost(HttpServletRequest request,
  HttpServletResponse response)throws ServletException,IOException
 {
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();

  //Get value from TextField in index.jsp
  String fname = request.getParameter("fname");
  String lname = request.getParameter("lname");
  String city = request.getParameter("city");
  String country = request.getParameter("country");

  try {
if (request.getParameter("insert") != null) {
 if (!fname.equals("") || !lname.equals("") || 
	        !city.equals("") || !country.equals("")) 
{

  //create ServletEntity Object and store value into it
  ServletEntity servletEntity = new ServletEntity();
  em.getTransaction().begin();
  servletEntity.setFname(fname);
  servletEntity.setLname(lname);
  servletEntity.setCity(city);
  servletEntity.setCountry(country);
  em.getTransaction().commit();

  out.println("Data successfully store into Entity table");
  out.println("<BR><a href=\"index.jsp\">Return to index page</a>");
 } else {
  out.println("Please don't leave any testField empty");
  out.println("<BR><a href=\"index.jsp\">Return to index page</a>");
 }
} else {
 //invoke method
 prcessHeader(out);
 processRequest(out);
 processFooter(out);
}
  } finally {
//free all resource
em.close();
emf.close();
out.flush();
out.close();
  }
 }

 @Override
 public String getServletInfo() {
  return "r4r.co.in-EntityServlet";
 }

 //prcessHeader method is used to handle output form Head
 private void prcessHeader(PrintWriter out) {
  out.println("<html>");
  out.println("<head>");
  out.println("<title>" + getServletInfo() + "</title>");
  out.println("</head>");
  out.println("<body>");
  out.println("<h1>Fetch Data from Database</h1>");
  out.println("<table border=\"1\" cellspacing=\
                           "2\"cellpadding=\"2\">");
  out.println("<thead><tr>");
  out.println("<td> Id </td>");
  out.println("<td> FirstName </td>");
  out.println("<td> Lastname </td>");
  out.println("<td> City </td>");
  out.println("<td> Country </td>");
  out.println("</thead></tr>");
 }

 //prcessRequest method is used to handle output form Body
 private void processRequest(PrintWriter out) {
  em.getTransaction().begin();
  //fetch total record from Entity class and store into List
  Query q = em.createQuery
	            ("select object(o) from ServletEntity as o");
  List<ServletEntity> list = q.getResultList();
  out.println("Total result found :<b>" 
	                   + list.size() + "</b><BR>");
  for (int i = 0; i < list.size(); i++) {
ServletEntity servletEntity = list.get(i);
//display record on browser
out.println("<tbody><tr>");
out.println("<td> " + "<I><b>"
                  + servletEntity.getId() + "</I></b>" + "</td>");
out.println("<td> " + "<I><b>" 
	              + servletEntity.getFname() + "</I></b>" + "</td>");
out.println("<td> " + "<I><b>"
                  + servletEntity.getLname() + "</I></b>" + "</td>");
out.println("<td> " + "<I><b>" 
	              + servletEntity.getCity() + "</I></b>" + "</td>");
out.println("<td> " + "<I><b>"
                  + servletEntity.getCountry() + "</I></b>" + "</td>");
out.println("</tr></tbody>");
  }
 }

 //prcessFooter method is used to handle output form Footer
 private void processFooter(PrintWriter out) {
  out.println("</body>");
  out.println("</html>");
  out.println("<BR><a href=\"index.jsp\">Return to index page</a>");
 }
}

Test Program

/*
 * Save as a EntityServletMain.java
 * This class is only for test purpose
 (fetch data from database and display over server console)
*/
package r4r.Entity.Servlet;
import java.util.List;
import javax.persistence.*;
/**
 *
 * @author R4R
 */
public class EntityServletMain {

 private static final EntityManagerFactory emf =
	  Persistence.createEntityManagerFactory("EntityServletPU");
 private static EntityManager em = emf.createEntityManager();
 public static void main(String[] args) {
 try
 {
	
 }
 catch ()
 {
 }{
 em.getTransaction().begin();
 //fetch total record from Entity class and store into List
 Query q = em.createQuery
	  ("select object(o) from ServletEntity as o");
List<ServletEntity> list = q.getResultList();
System.out.printf
	   ("Total (%d) result found into table", list.size());

for (int i = 0; i < list.size(); i++) {
 ServletEntity entity = list.get(i);
 //display record over server console
 System.out.println(entity.getId() + "|" 
	          + entity.getFname() + "|" + entity.getLname()
+ "|" + entity.getCity() + "|" + entity.getCountry());
}
  } finally {
//free all resource
em.getTransaction().commit();
em.close();
emf.close();
  }
 }
}
Output of Program
Previous Home Next