Nupur Nupur - 22 days ago 6
Java Question

Validate method called after the execute method of struts 2


I am using struts 2 and hibernate framework and had developed a small
CRUD to enter data into mysql db , and validating the fields


Student.java

package com.struts2hibernatepagination.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "student")
public class Student {

@Id
@GeneratedValue
private int id;
@Column(name = "last_name")
private String lastName;
@Column(name = "first_name")
private String firstName;
private int marks;

public int getId() {
return id;
}

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

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public int getMarks() {
return marks;
}

public void setMarks(int marks) {
this.marks = marks;
}

}



AddStudentAction.java


package com.struts2hibernatepagination.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.struts2hibernatepagination.dao.StudentDAO;
import com.struts2hibernatepagination.hibernate.Student;

public class AddStudentAction extends ActionSupport implements
ModelDriven<Student> {

public AddStudentAction() {
// TODO Auto-generated constructor stub
}

private Student student = new Student();

private List<Student> students = new ArrayList<Student>();

public Student getStudent() {
return student;
}

public void setStudent(Student student) {
this.student = student;
}

public List<Student> getStudents() {
return students;
}

public void setStudents(List<Student> students) {
this.students = students;
}

StudentDAO dao = new StudentDAO();

@Override
public Student getModel() {
// TODO Auto-generated method stub
return student;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
dao.addStudent(student);
String f = student.getFirstName();
String l = student.getLastName();
int m = student.getMarks();
System.out.println(f + l + m + "Inside execute method");
return "success";
}

public String listStudents() {
students = dao.getStudents();
return "success";
}
@Override
public void validate() {
// TODO Auto-generated method stub
if (student.getFirstName() == null) {

String first = student.getFirstName();

System.out.println(first);//this statement is returning null
this.addActionError("Please Enter First Name !!!");
System.out.println("Inside validate method!!");
}
// super.validate();
}
}



student.jsp


<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Hello World</title>
<s:head />
</head>
<body>
<s:form action="addStudent">
<s:actionerror />
<s:textfield name="firstName" label="First Name" />
<s:textfield name="lastName" label="Last Name" />
<s:textfield name="marks" label="Marks" />
<s:submit />
<hr />
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Marks</th>
</tr>
<s:iterator value="students">
<tr>
<td><s:property value="firstName" /></td>
<td><s:property value="lastName" /></td>
<td><s:property value="marks" /></td>
</tr>
</s:iterator>
</table>

</s:form>
<s:form action="fetchStudentList">
<s:submit>See All Student List</s:submit>

</s:form>
</body>
</html>



StudentDAO.java


package com.struts2hibernatepagination.dao;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transaction;

import org.hibernate.Session;

import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.struts2hibernatepagination.hibernate.Student;

public class StudentDAO {

// The session object and transaction object will be injected using the
// @SessionTarget
// and @TransactionTarget annotation respectively.

@SessionTarget
Session session;

@TransactionTarget
Transaction transaction;

@SuppressWarnings("unchecked")
public List<Student> getStudents() {
List<Student> students = new ArrayList<Student>();
try {
students = session.createQuery("from Student").list();
} catch (Exception e) {
e.printStackTrace();
}
return students;
}

public void addStudent(Student student) {
try {
session.save(student);
} catch (Exception e) {
e.printStackTrace();
}
}

}



struts.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<constant name="struts.devMode" value="true" />

<package name="default" extends="hibernate-default">

<action name="addStudent" method="execute"
class="com.struts2hibernatepagination.action.AddStudentAction">



<result name="success" type="redirect">
listStudents
</result>

<result name="input">/student.jsp</result>




</action>

<action name="listStudents" method="listStudents"
class="com.struts2hibernatepagination.action.AddStudentAction">
<result name="success">/student.jsp</result>
<result name="input">/student.jsp</result>




</action>

<action name="fetchStudentList"
class="com.struts2hibernatepagination.action.AddStudentAction"
method="listStudents">

<result name="success">/displaytag.jsp</result>
<result name="input">/student.jsp</result>


</action>

</package>





hibernate.cfg.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">admin12345</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.1.3:3306/nupur</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.struts2hibernatepagination.hibernate.Student" />
</session-factory>
</hibernate-configuration>


In the above code, the execute method is called first after the submit button is pressed on student.jsp and after that validate is been called, hence even when I enter firstname it raises error to enter firstname, since the validation is done after the data is inserted in db, where I am getting wrong? I need to call validate method first.


Console :


17:36:12 - DEBUG: Preparing Injection Hibernate Session and Transaction process: /addStudent - Method: com.struts2hibernatepagination.action.AddStudentAction.execute()
17:36:12 - DEBUG: Full Hibernate Plugin's Session Factory: destroy factory required...
17:36:12 - DEBUG: Full Hibernate Plugin's Session Factory: C3P0 not found
17:36:12 - DEBUG: Full Hibernate Plugin's Session Factory: All SessionFactories Destroyed sucessful
17:36:12 - DEBUG: Hibernate Session Required (from current Thread) - SessionFactory required: (default)
17:36:12 - DEBUG: No Hibernate Session in current thread. New Hibernate Session will be created and returned (SessionFactory "(default)")
17:36:12 - DEBUG: New Hibernate Session required - SessionFactory required: (default)
17:36:12 - DEBUG: Full Hibernate Plugin's Session Factory build started...
17:36:12 - DEBUG: Full Hibernate Plugin's Session Factory using Hibernate Annotation Configuration
17:36:13 - DEBUG: Full Hibernate Plugin's Session Factory configuration file "/hibernate.cfg.xml" configured
17:36:14 - DEBUG: SessionFactory "" configured from "/hibernate.cfg.xml" file
17:36:14 - DEBUG: "" configured as the *default* SessionFactory of the Full Hibernate Plugin's Session Factory
17:36:14 - DEBUG: Full Hibernate Plugin's Session Factory built successful
17:36:14 - DEBUG: New Hibernate Session created and returned (SessionFactory "")
17:36:14 - DEBUG: Hibernate Session from Full Hibernate Plugin's Hibernate Session Factory
17:36:14 - DEBUG: Hibernate Session injected (by annotation) into Action. Field "session". Class "com.struts2hibernatepagination.dao.StudentDAO"
17:36:14 - DEBUG: Full Hibernate Plugin Validation in class com.struts2hibernatepagination.action.AddStudentAction
17:36:14 - DEBUG: Full Hibernate Plugin Validation found no erros.
Hibernate: insert into student (last_name, first_name, marks) values (?, ?, ?)
**TinaDutta44Inside execute method**
17:36:15 - DEBUG: Hibernate Transation org.hibernate.transaction.JDBCTransaction@1d4fbd1 rolledback by Full Hibernate Plugin
17:36:15 - DEBUG: Hibernate Session closed
17:36:15 - DEBUG: Hibernate Session closed by Full Hibernate Plugin's Hibernate Session Factory
17:36:15 - DEBUG: Hibernate Transaction Committed
17:36:15 - DEBUG: Injection Hibernate Session and Transaction process for /addStudent - Method: com.struts2hibernatepagination.action.AddStudentAction.execute() finished
17:36:15 - DEBUG: Preparing Injection Hibernate Session and Transaction process: /listStudents - Method: com.struts2hibernatepagination.action.AddStudentAction.listStudents()
17:36:15 - DEBUG: Hibernate Session Required (from current Thread) - SessionFactory required: (default)
17:36:15 - DEBUG: No Hibernate Session in current thread. New Hibernate Session will be created and returned (SessionFactory "(default)")
17:36:15 - DEBUG: New Hibernate Session required - SessionFactory required: (default)
17:36:15 - DEBUG: New Hibernate Session created and returned (SessionFactory "")
17:36:15 - DEBUG: Hibernate Session from Full Hibernate Plugin's Hibernate Session Factory
17:36:15 - DEBUG: Hibernate Session injected (by annotation) into Action. Field "session". Class "com.struts2hibernatepagination.dao.StudentDAO"
17:36:15 - DEBUG: Full Hibernate Plugin Validation in class com.struts2hibernatepagination.action.AddStudentAction
17:36:15 - DEBUG: Full Hibernate Plugin Validation found no erros.
**null
Inside validate method!!**
17:36:15 - DEBUG: Full Hibernate Plugin found custom validation errors: {} [Please Enter First Name !!!]
17:36:16 - DEBUG: Hibernate Transation org.hibernate.transaction.JDBCTransaction@6ee964 rolledback by Full Hibernate Plugin
17:36:16 - DEBUG: Hibernate Session closed
17:36:16 - DEBUG: Hibernate Session closed by Full Hibernate Plugin's Hibernate Session Factory
17:36:16 - DEBUG: Hibernate Transaction Committed
17:36:16 - DEBUG: Injection Hibernate Session and Transaction process for /listStudents - Method: com.struts2hibernatepagination.action.AddStudentAction.listStudents() finished

Answer

As you see in the debugs that the plugin performs it's own validation. It's not Struts validation, but a bean validation with Hibernate Validator.

You should choose the validation framework that better suits your needs. If you enable Struts validation with defaultStackHibernateStrutsValidation then you should exclude some action methods from validation and remove input result.

<action name="listStudents" method="listStudents"
        class="com.struts2hibernatepagination.action.AddStudentAction">
    <interceptor-ref name="defaultStackHibernateStrutsValidation">
       <param name="validation.excludeMethods">listStudents</param>
    </interceptor-ref>
    <result name="success">/student.jsp</result>
</action>

The other actions also need that stack defaultStackHibernateStrutsValidation, so you better use in the package

<default-interceptor-ref name="defaultStackHibernateStrutsValidation"/>