SSH框架之Struts的常用技術——數據回顯、防止表單重複提交

Struts2的常用三大技術:
1、數據回顯
2、模型驅動
3、防止表單重複提交

一、數據回顯:
1、數據回顯,必須要用struts標籤!

2、代碼講解:
1)Action:

// 進入修改頁面
    public String viewUpdate() {
        // 模擬一個對象(先獲取一個id,再根據id調用service查詢,把查到的結果保存到域)
        User userInfo = new User();
        userInfo.setUserName("Endeavor");
        userInfo.setEmail("[email protected]");

        ActionContext ac = ActionContext.getContext();
//      Map<String,Object> request = (Map<String, Object>) ac.get("request");
//      request.put("userInfo", userInfo);

        /************* 數據回顯***************/
        // 獲取值棧
        ValueStack vs = ac.getValueStack();
        vs.pop();// 移除棧頂元素
        vs.push(userInfo);  // 入棧


        // 進入修改頁面
        return "viewUpdate";
    }

2)jsp頁面:

<body>
    <%@taglib uri="/struts-tags" prefix="s" %>


    <br/>
    <!-- 在頁面文本框內,顯示要修改記錄的數據 -->

    <!-- 手動通過value設置顯示的值 
    <s:form action="#">

        用戶名: <s:textfield name="user.userName" value="%{#request.userInfo.userName}"></s:textfield>   <br/>

        郵箱: <s:textfield name="user.email" value="%{#request.userInfo.email}"></s:textfield>     <br/>
    </s:form>
    -->

    <!-- 數據回顯技術:s:textfield會自動查找根元素數據(Ognl表達式語言取值)  -->
    <s:form action="#">

        用戶名: <s:textfield name="userName"></s:textfield>   <br/>

        郵箱: <s:textfield name="email"></s:textfield>     <br/>
    </s:form>

    <s:debug></s:debug>
  </body>

二、防止表單重複提交
核心:Struts提供了防止表單重複提交攔截器:

<interceptor name="token" 
class="org.apache.struts2.interceptor.TokenInterceptor"/>

通過案例進行說明:
1、update.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Add</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
  </head>

  <body>
    <s:form action="/emp_update" method="post">
        <!-- 隱藏域,保存主鍵 -->
        <s:hidden name="id"></s:hidden>

        <table>
            <tr>
                <td>員工名:</td>
                <td><s:textfield name="empName" /></td>
            </tr>
            <tr>
                <td>日期:</td>
                <!-- 
                <td><s:date name="workDate" format="yyyy-MM-dd"/>
                    <s:hidden name="workDate"></s:hidden>
                </td>
                 -->
                 <td>
                    <s:textfield name="workDate" />
                 </td>
            </tr>
            <tr>
                <td colspan="2">
                    <s:submit value="修改員工"></s:submit>
                </td>
            </tr>
        </table>
    </s:form>
  </body>
</html>

2、list.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>list</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
  </head>

  <body>
     <table border="1" align="center">
        <tr>
            <th>序號</th>
            <th>編號</th>
            <th>員工名稱</th>
            <th>日誌日期</th>
            <th>操作</th>
        </tr>
        <!-- 1. 先判斷;2.  再迭代 -->
        <s:if test="#request.listEmp != null">
            <s:iterator var="emp" value="#request.listEmp" status="st">
                <tr>
                    <td><s:property value="#st.count"/></td>
                    <td><s:property value="#emp.id"/></td>
                    <td><s:property value="#emp.empName"/></td>
                    <td><s:property value="#emp.workDate"/></td>
                    <td>
                        <s:a href="emp_viewUpdate?id=%{#emp.id}">修改</s:a>
                    </td>
                </tr>
            </s:iterator>
        </s:if>
        <s:else>
            <tr>
                <td colspan="5">對不起,沒有你要顯示的數據</td>
            </tr>
        </s:else>
     </table>
  </body>
</html>

3、add.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Add</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
  </head>

  <body>
    <s:form action="/emp_save" method="post">
        <!-- 防止表單重複提交,第一步:生成id(客戶端、服務器) -->
        <s:token></s:token>

        <table>
            <tr>
                <td>員工名:</td>
                <td><s:textfield name="empName" /></td>
            </tr>
            <tr>
                <td>日期:</td>
                <td><s:textfield name="workDate" /></td>
            </tr>
            <tr>
                <td colspan="2">
                    <s:submit value="保存員工"></s:submit>
                </td>
            </tr>
        </table>
    </s:form>
  </body>
</html>

4、EmployeeAction.java

public class EmployeeAction extends ActionSupport implements ModelDriven<Employee>{

    /****封裝數據****/
    private Employee employee = new Employee();
    public Employee getEmployee() {
        return employee;
    }
    public void setEmployee(Employee employee) {
        this.employee = employee;
    }
    // 重寫模型驅動方法
    @Override
    public Employee getModel() {
        return employee;
    }

    /****調用的Service****/
    private IEmployeeService employeeService = new EmployeeService();

    /**
     * 1. 添加員工
     */
    public String save() {
        try {
            // 調用service保存
            employeeService.save(employee);
            // 添加成功,去到列表頁面
            return list();
            //return "addsuccess";
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
    }

    /**
     * 2. 列表顯示
     */
    public String list() {
        try {
            // 查詢全部
            List<Employee> listEmp = employeeService.getAll();
            // 保存到request域
            ActionContext.getContext().getContextMap().put("listEmp", listEmp);
            return "list";
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
    }

    /**
     * 3. 進入修改頁面
     */
    public String viewUpdate() {
        try {
            // 3.1 獲取當前修改的記錄的主鍵值
            int id = employee.getId();
            // 3.2 service查詢
            Employee emp = employeeService.findById(id);
            // 3.3 數據回顯
            // a. 先得到值棧
            ValueStack vs = ActionContext.getContext().getValueStack();
            vs.pop();   //移除棧頂元素
            vs.push(emp);   // emp對象放入棧頂

            return "update";
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
    }

    /**
     * 4. 修改員工
     */
    public String update() {
        try {
            // 調用service修改
            employeeService.update(employee);
            return list();
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
    }
}

5、struts.xml

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

<struts>
    <!-- 更改主題 -->
    <constant name="struts.ui.theme" value="simple"></constant>

    <package name="emp" extends="struts-default">

        <!-- 全局視圖 -->
        <global-results>
            <result name="error">/error/error.jsp</result>
        </global-results>

        <action name="emp_*" class="cn.itcast.action.EmployeeAction" method="{1}">

            <!-- 防止表單重複提交,第二步: 配置" 防止表單重複提交攔截器" -->
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <interceptor-ref name="token">
                <!-- 指定攔截哪些方法需要防止表單重複提交(save) -->
                <param name="includeMethods">save</param>
            </interceptor-ref>

            <!-- 防止表單重複提交,第三步: 如果用戶重複提交了跳轉到指定的錯誤頁面  -->
            <result name="invalid.token" type="redirectAction">emp_list</result>

            <!-- 首頁顯示 -->
            <result name="list">/WEB-INF/list.jsp</result>

            <!-- 進入修改頁面 -->
            <result name="update">/WEB-INF/update.jsp</result>

            <!-- 
            <result name="addsuccess" type="redirectAction">emp_list</result>
             -->
        </action>

    </package>
</struts>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章