struts2 表單處理


在這篇教程里我們將探究如何處理表單提交。本文例子介紹:

  • javabean存儲表單數據
  • 在action中重寫validate方法進行簡單的校驗
  • 創建一個struts2表單並和javabean匹配

javabean存儲表單數據

為了封裝數據,我們將使用一個簡單的Java類,它遵循基本的Java Bean規范,即為每個屬性設置public get/set 方法。

Person.java

package model;

public class Person {
    private String firstName;
    private String lastName;
    private String email;
    private int age;
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName + ", email="
                + email + ", age=" + age + "]";
    }
}

注意上面的javabean:

  • 年齡為int類型(action在講表單參數填充到javabean中,會進行適當的類型轉換)
  • 復寫了toString方法(<s:property>會調用toString方法)

action處理表單數據

action類需要繼承ActionSupport,在Register類中我們申明一個屬性personBean,並且提供相應的get/set方法。同時,在Register類中復寫execute方法和validate方法。

  • execute方法:

默認實現不執行任何操作的返回"success"。子類應重寫此方法以提供業務邏輯,並由此返回Action的預定義的返回值:SUCCESS、NONE 、ERROR、INPUT、LOGIN。

我們在Struts.xml中添加action元素時,需要定義這些返回值對應的頁面(注:返回哪些寫哪些)。

  • validate方法:

在Validatable接口中定義了一個validate()方法,重寫該方法,如果建議表單輸入域出現錯誤,則將錯誤添加到Actionsupport類的fieldErrors域中,然后通過OGNL表達式負責輸出。

Register.java

package test.action;

import model.Person;
import com.opensymphony.xwork2.ActionSupport;

public class Register extends ActionSupport {
    private static final long serialVersionUID = 1L;
    private Person personBean;
    
    public String execute() throws Exception {

        // call Service class to store personBean's state in database

        return SUCCESS;
    }
    
    public void validate() {
        if (personBean.getFirstName().length() == 0) {
            addFieldError("personBean.firstName", "firstName is required");
        }
        if (personBean.getEmail().length() == 0) {
            addFieldError("personBean.email", "firstName is required");
        }
        if(personBean.getAge()<18){
            addFieldError("personBean.age", "Age is required and must be 18 or older");
        }
    }

    public Person getPersonBean() {
        return personBean;
    }

    public void setPersonBean(Person person) {
        personBean = person;
    }
}


jsp頁面的struts2表單

表單維持和錯誤輸出

用struts標簽<s:form>進行表單維持和錯誤輸出比較方便,但也因此生成了<table>的大量HTML代碼。往往我們並不需要這些格式和代碼,並且對這些標簽的格式控制可能會增加我們的工作量。因此我們更改struts默認的主題,輸出我們想要的效果。

struts2的主題和模板

struts2默認主題為XHTML,我們可以在struts.properties文件中修改struts2的默認主題。

struts.properties

struts.ui.theme=simple

表單書寫格式

因為用了simple模板,就需要自己定義fielderror的顯示。

格式為:<s:fielderror fieldName="XXX">並將此標簽放在表單XXX字段之后。

fielderror默認主題是ul li的格式,我們需要可以將默認文檔進行更改。參考:

http://bbs.csdn.net/topics/300107242

register.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'register.jsp' starting page</title>
</head>
<s:head />
<body>
    <h1>register</h1>
    <s:form action="register">
        firstName:<s:textfield name="personBean.firstName"></s:textfield>
                  <s:fielderror fieldName="personBean.firstName" /><br>
        lastName:<s:textfield name="personBean.lastName"></s:textfield>
                      <s:fielderror fieldName="personBean.lastName" /><br>
        email:<s:textfield name="personBean.email"></s:textfield>
              <s:fielderror fieldName="personBean.email" /><br>
        age:<s:textfield name="personBean.age"></s:textfield>
            <s:fielderror fieldName="personBean.age" /><br>
        <s:submit />
    </s:form>
</body>
</html>

顯示結果的thankyou.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>   
    <title>My JSP 'thankyou.jsp' starting page</title>
  </head> 
  <body>
    <p>Your registration information: <s:property value="personBean" /> </p>    
    <h3><s:text name="thankyou" /></h3>
  </body>
</html>

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="basicstruts2" extends="struts-default">
        <action name="register" class="test.action.Register" method="execute">
            <result name="success">/thankyou.jsp</result>
            <result name="input">/register.jsp</result>
        </action>
    </package>
</struts>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM