一.为什么要进行数据校验 对于一个web应用而言,所有的应用数据都是通过浏览器收集的,用户的输入信息是非常复杂的,对于一些用户操作不熟练,输入出错,等网络传输不稳定,这些都有可能导致异常输入。 异常的输入,轻则导致系统非正常中断,重则导致系统崩溃,应用程序必须能正常处理表现层接收的异常数据,通常的做法是遇到非法数据,应用程序将相应的给出用户提示,提示用户必须输入要求的数据,也就是将那些异常输入过滤掉,我们说对异常数据的过滤就是数据校验。 二.如何实现数据校验 我们可以让一个自定义类去继承自一个ActionSupport类,这个类是一个默认的的Action实现类,他的完全限定名com.opensymphony.xwork2.ActionSupport.这个类中提供了很多的默认方法,包括获取国际化信息的方法,数据校验的方法,以及默认处理用户请求的方法等,由于ActionSupport类是Struts2默认的实现类,所以如果在struts.xml中的Action配置中省略了class属性,则代表访问ActionSupport类,其execute()方法直接返回SUCCESS,同时ActionSupport类还增加了对验证,本地化的支持。login.jsp<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>LoginAction类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;
}
}struts.xml<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>如何避免这种让Struts2框架自动生成的标签我们可以在struts.xml中配置这个节点:<!--设置用户界面主题,默认值为XHTML风格-->
<constant name="struts.ui.theme" value="simple"></constant>通过配置struts.xml的方式,来改变一些常量值,来控制struts2框架的行为。推荐阅读:Struts2之动态方法调用改变表单action属性 http://www.linuxidc.com/Linux/2016-09/134982.htmStruts中异步传送XML和JSON类型的数据 http://www.linuxidc.com/Linux/2013-08/88247.htmStruts2的入门实例 http://www.linuxidc.com/Linux/2013-05/84618.htmStruts2学习笔记-Value Stack(值栈)和OGNL表达式 http://www.linuxidc.com/Linux/2015-07/120529.htm struts2文件上传(保存为BLOB格式) http://www.linuxidc.com/Linux/2014-06/102905.htmStruts2的入门实例 http://www.linuxidc.com/Linux/2013-05/84618.htmStruts2实现ModelDriven接口 http://www.linuxidc.com/Linux/2014-04/99466.htm遇到的Struts2文件下载乱码问题 http://www.linuxidc.com/Linux/2014-03/98990.htmStruts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htmStruts2 注解模式的几个知识点 http://www.linuxidc.com/Linux/2013-06/85830.htmStruts 的详细介绍:请点这里
Struts 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-10/135994.htm