Create Entity Class in JPA
The entity class for our application “Employee.java” is created in the package “com.model.entities”.PFB the code of
“Employee.java”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | package com.model.entities;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class Employee {
@Id
private String empid;
private String password;
private String password1;
private String empname;
private int age;
private String city;
private String email;
//getters & setters for all the attributes
} |
Service Layer
The service layer exposes an interface “EmployeeService” and an implementation class “EmployeeServiceImpl” to the users. These classes are defined in the package “com.service”
EmployeeService.java
1 2 3 4 5 6 | package com.service;
import com.model.entities.Employee;
import java.util.List;
public interface EmployeeService {
public void save(Employee user);
} |
EmployeeServiceImpl.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | package com.service;
import com.model.entities.Employee;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
@PersistenceContext(name = "persistence/myStrutsJPA", unitName = "StrutsJPAPersistenceUnit", type = PersistenceContextType.EXTENDED)
@javax.ejb.TransactionManagement(javax.ejb.TransactionManagementType.BEAN)
public class EmployeeServiceImpl implements EmployeeService {
private EntityManager em;
@Resource
private UserTransaction utx;
private EntityManagerFactory emf = null;
public UserTransaction getUtx() {
return utx;
}
public void setUtx(UserTransaction utx) {
this.utx = utx;
}
public EmployeeServiceImpl() {
try {
Context envCtx = (Context) new InitialContext().lookup("java:comp/env");
em = (EntityManager) envCtx.lookup("persistence/myStrutsJPA");
utx = (UserTransaction) envCtx.lookup("UserTransaction");
} catch (NamingException ex) {
System.out.println("PU Not found");
ex.printStackTrace();
}
}
public void setEntityManager(EntityManager em) {
this.em = emf.createEntityManager();
System.out.println(em);
}
public void save(Employee Employee) {
try {
System.out.println("Tx Status in save:=" + utx.getStatus());
if (utx.getStatus() == 6) { // Incase there's no active Transaction, we'll start one
Context envCtx = (Context) new InitialContext().lookup("java:comp/env");
utx = (UserTransaction) envCtx.lookup("UserTransaction");
utx.begin();
}
em.persist(Employee);
utx.commit();
} catch (NotSupportedException ex) {
ex.printStackTrace();
} catch (SystemException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void setEm(EntityManager em) {
this.em = em;
}
public void setEmf(EntityManagerFactory emf) {
this.emf = emf;
}
public EntityManager getEm() {
return em;
}
public EntityManagerFactory getEmf() {
return emf;
}
private EntityManager getEntityManager() {
return em;
}
} |
Action Class
Struts does the request processing with the help of Action classes. Here’s the code for the EmployeeAction.java which handles the request to create a new Employee. This class is created in the package
“com.actions”.
EmployeeAction.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | package com.actions;
import com.model.entities.Employee;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.service.EmployeeServiceImpl;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
public class EmployeeAction extends ActionSupport implements ModelDriven, Preparable, ServletRequestAware {
private Employee emp;
private HttpServletRequest req;
private EmployeeServiceImpl empService;
public EmployeeAction() {
this.empService=new EmployeeServiceImpl();
}
public Employee getEmp() {
return emp;
}
public void setEmp(Employee emp) {
this.emp = emp;
}
public EmployeeServiceImpl getEmpService() {
return empService;
}
public void setEmpService(EmployeeServiceImpl empService) {
this.empService = empService;
}
public String execute() throws Exception {
empService.save(emp);
return SUCCESS;
}
public Object getModel() {
return emp;
}
public void prepare() throws Exception {
emp=new Employee();
}
public void setServletRequest(HttpServletRequest hsr) {
this.req=hsr;
}
} |
Please note that there’s no validation logic in the action class. We have put the validation logic in the
“EmployeeAction-validation.xml” file kept in the “com.actions” package. Please note that the validation.xml file should always be kept in the same package where your action class is present.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="empid">
<field-validator type="requiredstring">
<message>Employee Id is a mandatory field</message>
</field-validator>
<field-validator type="regex">
<param name="expression">
<![CDATA[([E][m][p][0-9][0-9][0-9])]]>
</param>
<message>Valid Employee Id required e.g. Emp001</message>
</field-validator>
</field>
<field name="age">
<field-validator type="int">
<param name="min">20</param>
<param name="max">80</param>
<message>Age needs to between ${min} and ${max}</message>
</field-validator>
</field>
<field name="empname">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>User Name is required</message>
</field-validator>
</field>
<field name="password">
<field-validator type="requiredstring">
<message>Password is required</message>
</field-validator>
<field-validator type="stringlength">
<param name="maxLength">10</param>
<param name="minLength">5</param>
<param name="trim">true</param>
<message>
Enter password between 5 and 10 characters
</message>
</field-validator>
</field>
<field name="password1">
<field-validator type="fieldexpression">
<param name="expression">(password==password1)</param>
<message>
Password and Re-enter password must be same
</message>
</field-validator>
</field>
<field name="city">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>You can not leave city as blank</message>
</field-validator>
</field>
<field name="email">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>You can not leave email as blank</message>
</field-validator>
<field-validator type="email">
<message>
The email address you entered is not valid.
</message>
</field-validator>
</field>
</validators> |
Let us understand the request processing in the action class. The Action class has implemented the following interfaces:
- ServletRequestAware:This simplifies access to the HttpServletRequest object representing the request.
- ModelDriven:This enables the use of a POJO class to contain the data (similar to ActionForm of Struts1, with an exception that the class here is a POJO and doesn’t extend from any framework specific classes/interfaces). In our case, the entity class “Employee.java” created inside the “com.entities” package acts
as the model. - PreparableThis prepares the action class for use.
The data validation is performed with the help of “EmployeeAction-validation.xml” file. Different validation routines
are configured for the different entity attributes.
The User Interface Tier
The user interface part of the application is created in JSP. The home page of the application is “RegisterEmp.jsp”, where a form is displayed to the users asking for few details for the registration
purpose. PFB the code of “RegisterEmp.jsp”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Add Employee Details Using Field Validators</title>
</head>
<body>
<h1>Struts2 and JPA Integration Demo</h1>
Enter the Employee Details Here
<s:form action="addEmployee">
<s:textfield name="empid" key="app.empid" />
<br>
<s:textfield name="empname" key="app.empname" />
<br>
<s:password key="app.password" name="password" />
<br>
<s:password key="app.password1" name="password1" />
<br>
<s:textfield name="city" key="app.city" />
<br>
<s:textfield name="age" key="app.age" />
<br>
<s:textfield name="email" key="app.email" />
<br>
<br>
<s:submit value="Add Employee" />
</s:form>
<s:actionerror/>
</body>
</html> |
Once the user fills in the required details and clicks on the “Submit” button, the request is submitted to the action class. Upon successful validation, a new employee record is inserted in the database and user is navigated to
“RegisterEmp_Success.jsp”page. Here’s the code of “RegisterEmp_Success.jsp”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Employee Registration Success Page</title> </head> <body> <h1>Employee Details saved Successfully</h1> Employee Name: <s:property value="empname" /> <br> <br> Password: <s:property value="password" /> <br> <br> Employee Id: <s:property value="empid" /> <br> <br> Age: <s:property value="age" /> <br> <br> City: <s:property value="city" /> <br> <br> E-Mail: <s:property value="email" /> <br> <br> </body> </html> |






February 28, 2011
JPA, Struts 2.0