Home StrutsMVCDemo3 - Struts2后台验证(2.2.3)
Post
Cancel

StrutsMVCDemo3 - Struts2后台验证(2.2.3)

Struts2提供的后台效验流程

  1. 拦截器调用指定的方法validate()方法;
  2. 判断保存错误的Map集合是否为空,为null,才执行action的execute()方法;
  3. 如果不为null, 说明验证有错误,不放行。

数据效验原理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public synchronized void addFieldError(String fieldName, String errorMessage) {
    // 保存所有的错误信息的map集合
    // 同一个key,可以对应多个值
    final Map> errors = internalGetFieldErrors();
    // 先根据当前错误的key,去错误的map集合中查找,看是否已经存在!
    List thisFieldErrors = errors.get(fieldName);

    // 当前错误的key,在map集合不存在
    if (thisFieldErrors == null) {
        thisFieldErrors = new ArrayList();
        errors.put(fieldName, thisFieldErrors);
    }
    // 设置错误信息!
    thisFieldErrors.add(errorMessage);
}

错误处理

配置错误视图标记input对应的JSP页面,出现错误跳转到index.jsp,合理显示错误信息。

1
2
3
4
5
6
7
<package name="animal" namespace="" extends="person">
    <action name="a1" class="com.bbs.action.AnimalAction">
        <result name="success">/WEB-INF/success.jsp</result>
        <result name="error">/WEB-INF/error.jsp</result>
        <result name="input">/index.jsp</result>
    </action>
</package>

目录结构

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns="http://java.sun.com/xml/ns/javaee" 
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
         id="WebApp_ID" version="2.5">
    <display-name>Struts2MVCDemo</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

struts.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    "http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
    <!-- 不需要默认Spring容器管理struts -->
    <constant name="struts.objectFactory" 
              value="com.opensymphony.xwork2.ObjectFactory"></constant>

    <!-- 开发阶段,struts配置修改,重新加载 -->
    <constant name="struts.configuration.xml.reload" value="true"></constant>
    
    <package name="person" namespace="/person" extends="struts-default">
        <action name="hello1" class="com.bbs.action.PersonAction">
            <result name="success">/WEB-INF/success.jsp</result>
        </action>
        
        <action name="hello2" class="com.bbs.action.PersonAction" method="zhangxueyou">
            <result name="success">/WEB-INF/success.jsp</result>
            <result name="error">/WEB-INF/error.jsp</result>
        </action>
        
        <action name="hello3" class="com.bbs.action.PersonAction" method="liming">
            <result name="success">/WEB-INF/success.jsp</result>
            <result name="error">/WEB-INF/error.jsp</result>
        </action>
    </package>

    <include file="struts*.xml"></include>
</struts>

struts1.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    "http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
    <package name="animal" namespace="" extends="person">
        <action name="a1" class="com.bbs.action.AnimalAction">
            <result name="success">/WEB-INF/success.jsp</result>
            <result name="error">/WEB-INF/error.jsp</result>
            <result name="input">/index.jsp</result>
        </action>
    </package>
</struts>

PersonAction.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.bbs.action;

// struts2 Action层
public class PersonAction {

    private String name;
    
    // 视图从值栈中获取name
    public String getName() {
        System.out.println("调用getName方法");
        return name;
    }
    
    public void setName(String name) {
        System.out.println("调用setName方法,在actionContext中记录值栈信息");
        this.name = name;
    }
    
    // 默认执行
    public String execute() {
        // 返回result结果,视图名字
        return "success";
    }
    
    public String zhangxueyou() {
        if (true) {
            return "success";
        } else {
            return "error";
        }
    }
    
    public String liming() {
        System.out.println("获取页面参数:" + name);
        if (name == null || name.equals("")) {
            return "error";
        }
        return "success";
    }
    
}

AnimalAction.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.bbs.action;
import com.opensymphony.xwork2.ActionSupport;

/**
 * action 模型,处理animal方法
 * ActionSupport类不仅实现了action接口。还实现了:
 * validateable      提供校验功能
 * validationAware   提供校验功能
 * textprovider      提供国际化支持
 * localprovider     提供国际化支持
 * serializable      序列化接口
 * 所以,更多情况下,我们需要继承ActionSupport类
 * @author Administrator
 */
public class AnimalAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    private String name;
    private String pwd;
    
    public String getName() {
        return name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String login() {
        if (name.trim().equals("mayi") && pwd.trim().equals("123")) {
            return "success";
        } else {
            return "error";
        }
    }
    
    public void validate() {
        // 验证
        if (name == null || pwd == null) {
            addFieldError(name, "不能为空!");
        }
    }
    
}

success.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@  taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Success页面</title>
</head>
<body>
    success获取值栈属性值:${name }
    <s:debug></s:debug>
</body>
</html>

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index页面</title>
</head>
<body>
index
    <a href="http://localhost:8080/Struts2MVCDemo/person/hello1">
        请求链接-------PersonAction中的方法
    </a>
</body>
</html>

error.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Error页面</title>
    </head>
    <body>
        success
    </body>
</html>
This post is licensed under CC BY 4.0 by the author.