在struts2中,我们可以实现对action的所有方法进行校验或者对action的指定方法进行校验。
对于输入校验struts2提供了两种实现方法:
1. 采用手工编写代码实现。
2. 基于XML配置方式实现。
方法一实例:
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!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>输入校验</title>
</head>
<body>
<!-- 用于显示错误信息 -->
<s:fielderror/>
<form action="${pageContext.request.contextPath }/test/helloword.do
" method="post">
用户名:<input type="text" name="username"/><br/>
手机号:<input type="text" name="mobile"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
struts.xml文件
<action name="helloword" class="cn.itcast.action.HelloWordAction" method="save">
<result name="input">/index.jsp</result>
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
HelloWord.java
定义两个属性
private String username;
private String mobile;
在此省略以上两个属性的set和get方法
public String update(){
ActionContext.getContext().put("message", "更新成功");
return "success";
}
public String save(){
ActionContext.getContext().put("message", "保存成功");
return "success";
}
@Override
public void validate() {//会对action中的所有方法校验
if(this.username==null || "".equals(username.trim())){
//添加错误信息
this.addFieldError("username", "用户名不能为空");
}
if(this.mobile==null || "".equals(mobile.trim())){
this.addFieldError("mobile", "手机号不能为空");
}else{
if(!Pattern.compile("^1[358]\\d{9}$").matcher(mobile).matches()){
this.addFieldError("mobile", "手机号格式不正确");
}
}
}
message.jsp
${message}
复习struts2之对action中所有方法进行输入校验
最新推荐文章于 2019-11-02 15:21:49 发布