SSH框架之Struts的常用技术——数据回显、防止表单重复提交

来源:互联网 发布:linux,vi怎么用 编辑:程序博客网 时间:2024/05/18 00:27

Struts2的常用三大技术:
1、数据回显
2、模型驱动
3、防止表单重复提交

一、数据回显:
1、数据回显,必须要用struts标签!

2、代码讲解:
1)Action:

// 进入修改页面    public String viewUpdate() {        // 模拟一个对象(先获取一个id,再根据id调用service查询,把查到的结果保存到域)        User userInfo = new User();        userInfo.setUserName("Endeavor");        userInfo.setEmail("Endeavor@163.com");        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>
0 0
原创粉丝点击