在 struts 2 的执行方法之后调用的验证方法

Validate method called after the execute method of struts 2

我正在使用 struts 2 和休眠框架,并开发了一个小型 CRUD 来将数据输入 mysql 数据库,并验证字段

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>

在上面的代码中,在 student.jsp 上按下提交按钮后首先调用执行方法,然后调用验证,因此即使我输入名字,它也会引发输入名字的错误,因为验证是在数据插入数据库后完成的,我哪里出错了?我需要先调用验证方法。

控制台:

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 

正如您在调试中看到的那样,插件执行它自己的验证。这不是 Struts 验证,而是使用 Hibernate Validator 的 bean 验证。

您应该选择更适合您需求的验证框架。如果您使用 defaultStackHibernateStrutsValidation 启用 Struts 验证,那么您应该从验证中排除一些操作方法并删除 input 结果。

<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>

其他动作也需要那个堆栈defaultStackHibernateStrutsValidation,所以你最好在包中使用

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