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

时间:2016-11-12 08:09:48

标签: java hibernate struts2

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

Student.java

<select id='select'>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3" selected="selected">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<p>text</p>

AddStudentAction.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;
    }

}

student.jsp

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();
    }
}

StudentDAO.java

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

struts.xml中

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();
        }
    }

}

hibernate.cfg.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>

在上面的代码中,在student.jsp上按下提交按钮之后调用execute方法,并且在调用了validate之后,因此即使我输入firstname它也会引发错误以输入firstname,因为验证已完成数据插入数据库后,我出错了?我需要先调用validate方法。

控制台:

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

1 个答案:

答案 0 :(得分:1)

正如您在调试中看到的那样,插件执行它自己的验证。它不是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"/>