zoukankan      html  css  js  c++  java
  • Struts2数据校验

      一.为什么要进行数据校验 

          对于一个web应用而言,所有的应用数据都是通过浏览器收集的,用户的输入信息是非常复杂的,对于一些用户操作不熟练,输入出错,等网络传输不稳定,这些都有可能导致异常输入。

        异常的输入,轻则导致系统非正常中断,重则导致系统崩溃,应用程序必须能正常处理表现层接收的异常数据,通常的做法是遇到非法数据,应用程序将相应的给出用户提示,提示用户必须输入要求的数据,也就是将那些异常输入过滤掉,我们说对异常数据的过滤就是数据校验。

        二.如何实现数据校验

        我们可以让一个自定义类去继承自一个ActionSupport类,这个类是一个默认的的Action实现类,他的完全限定名com.opensymphony.xwork2.ActionSupport.这个类中提供了很多的默认方法,包括获取国际化信息的方法,数据校验的方法,以及默认处理用户请求的方法等,由于ActionSupport类是Struts2默认的实现类,所以如果在struts.xml中的Action配置中省略了class属性,则代表访问ActionSupport类,其execute()方法直接返回SUCCESS,同时ActionSupport类还增加了对验证,本地化的支持。

         三.数据校验案例

       我们在这里就一个登录案例来演示

       1.登录界面login.jsp:  

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8" %>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <%@taglib uri="/struts-tags"  prefix="s"%>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'login.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
      </head>
      <body>
        <div>
        <!-- 输出错误信息 -->
        <s:fielderror fieldName="errorname"/>
         <s:fielderror fieldName="errorpwd"/>
        </div>  
       <form action="Login.action" method="post" >
             用户名:<input type="text" name="username"/>
             密码:<input type="text" name="userpwd"/>
             <input type="submit" value="登录">
       </form>
      </body>
    </html>
    View Code

        2.LoginAction类:

    package cn.action;
    
    import java.util.Map;
    
    import cn.entity.User;
    
    import com.opensymphony.xwork2.ActionContext;
    import com.opensymphony.xwork2.ActionSupport;
    
    public class LoginAction extends ActionSupport{
         private String username;
         private String userpwd;
         
        
            @Override
            public void validate() {
                if(username.length()==0){
                    addFieldError("errorname", "用户名不能为空");
                } 
                if(userpwd.length()==0)
                {
                    addFieldError("errorpwd","密码不能为空");
                }
            }
    
              @Override
            public String execute() throws Exception {
                if(username.equals("123")&&userpwd.equals("123")){
                    //通过解耦合的方式获取到一个Map
                    Map<String,Object> map=ActionContext.getContext().getSession();
                    //如果用户用户名和密码输入正确,把值保存到集合中,也就是把值放到session中
                    map.put("name", username);
                    return SUCCESS;    
                }else{
                    return INPUT;    
                }
                
            }
    
            public String getUsername() {
                return username;
            }
    
            public void setUsername(String username) {
                this.username = username;
            }
    
            public String getUserpwd() {
                return userpwd;
            }
    
            public void setUserpwd(String userpwd) {
                this.userpwd = userpwd;
            }
        
        
    }
    View Code

        3.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>
        <!-- 配置文件中只要添加以下配置,那么以后修改配置文件不用重启tomcat -->
        <constant name="struts.devMode" value="true"/>
       
        <package name="default" namespace="/" extends="struts-default">
            <action name="Login" class="cn.action.LoginAction">
               <result name="success">
               Login/scuess.jsp
               </result>
               <result name="input">
               Login/login.jsp
               </result>
            </action>  
        </package>
    </struts>
    View Code

    用户名和密码正确 情况:

    用户名和密码为空情况:

      可以看到数据校验起到效果了,我们在自定义Action类中LoginAction做了对用户名和密码的限定,长度不能为0,然后把错误信息通过addFieldError保存了起来,开发人员想要自前端获取到定义的错误信息,我们可以通过Struts2标签来输出:

    <s:fielderror fieldName="errorname"/>  
    <s:fielderror fieldName="errorpwd"/>

    如果想输出所有错误信息:
    <s:fielderror/>

        四.关于Struts2标签输出的错误自定义标签

       我们可以发现如果我们在用struts2标签输出的错误信息的时候,Struts2框架自动帮我们在错误信息外生成了标签

        

             如何避免这种让Struts2框架自动生成的标签

    我们可以在struts.xml中配置这个节点:

    <!--设置用户界面主题,默认值为XHTML风格-->
    <constant name="struts.ui.theme" value="simple"></constant>

    通过配置struts.xml的方式,来改变一些常量值,来控制struts2框架的行为。

       那么还有一种方式是通过值栈的方式来取出数据:

      你在login.jsp页面中加入<s:debug></s:debug>查看值栈的一些信息。

        我们可以看出值栈保存信息的方式,我们可以理解它是以一种Map集合的方式来保存值栈信息,那么我们可以看出Property Nam就是Key值,Property Value就是Value,我们如何在界面中去取出值栈中的值,这里我们可以以值栈中的错误信息显示在页面上。

     

       而且我们可以看出取出值栈中的值,他在值的外围不会再加上额外的标签。

      

  • 相关阅读:
    PAT (Advanced Level) Practice 1100 Mars Numbers (20分)
    PAT (Advanced Level) Practice 1107 Social Clusters (30分) (并查集)
    PAT (Advanced Level) Practice 1105 Spiral Matrix (25分)
    PAT (Advanced Level) Practice 1104 Sum of Number Segments (20分)
    PAT (Advanced Level) Practice 1111 Online Map (30分) (两次迪杰斯特拉混合)
    PAT (Advanced Level) Practice 1110 Complete Binary Tree (25分) (完全二叉树的判断+分享致命婴幼儿错误)
    PAT (Advanced Level) Practice 1109 Group Photo (25分)
    PAT (Advanced Level) Practice 1108 Finding Average (20分)
    P6225 [eJOI2019]异或橙子 树状数组 异或 位运算
    P4124 [CQOI2016]手机号码 数位DP
  • 原文地址:https://www.cnblogs.com/hyjj/p/5830918.html
Copyright © 2011-2022 走看看