现在是科技的时代,大多数人都在网上购物了, 我们都碰到过相同的问题,各大网站弄的那些各种各样的注册页面,相信大家都深有体会。
有了这验证就很好的保证了我们的信息的准确性和安全性。
接下来我给大家讲解一下用struts2怎么实现页面上简单的拦截。
方法一:
用execute()方法来实现
1.0创建一个UserInfo类
package cn.struts.entity;public class UserInfo {//用户名private String name;//密码private String pwd;//电话private String phone;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;} }
2.0创建一个ExecuteAction继承ActionSupport
package cn.struts.action;import cn.struts.entity.UserInfo; import com.opensymphony.xwork2.ActionSupport;public class ExecuteAction extends ActionSupport {//用户对象private UserInfo user;//确认密码private String okpwd;@Overridepublic String execute() throws Exception {//判断用户名是否为空if (user.getName().length() == 0) {addFieldError("name", "用户名不能为空");}//判断密码是否为空if (user.getPwd().length() == 0) {addFieldError("pwd", "密码不能为空");}//判断电号码是否为空if (user.getPhone().length() == 0) {addFieldError("phone", "电话不能为空");}//判断两次输入的密码是否一致if(!user.getPwd().equals(okpwd)){addFieldError("userpwd", "两次密码不一致");}//这是最重要的判断//判断上面是否还存在没有通过的验证if (this.hasFieldErrors()) {return "input";}return "success";}public UserInfo getUser() {return user;}public void setUser(UserInfo user) {this.user = user;}public String getOkpwd() {return okpwd;}public void setOkpwd(String okpwd) {this.okpwd = okpwd;} }
3.0编写struts.xml
<action name="executeAction" class="cn.struts.action.ExecuteAction"><result>/success.jsp</result><result name="input">/index.jsp</result></action>
4.0编写页面
index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="s" uri="/struts-tags" %> <html> <title>登陆页面</title> <body> <s:fielderror></s:fielderror> <form action="execute" method="post">用户名:<input name="user.name"><br/>电话:<input name="user.phone"><br/>密码:<input name="user.pwd"><br/>确认密码:<input name="okpwd"><br/><input type="submit" value="提交"> </form> </body> </html>
success.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="s" uri="/struts-tags" %> <html> <head><title>成功页面</title> </head> <body> 欢迎你:<s:property value="user.name"></s:property></body> </html>
效果如下:
这些就是我们注册时常常碰到的提示!!!!
et=UTF-8" language="java" %> <%@taglib prefix="s" uri="/struts-tags" %> <html> <title>登陆页面</title> <body> <s:fielderror></s:fielderror> <form action="regist" method="post">用户名:<input name="user.name"><br/>电话:<input name="user.phone"><br/>密码:<input name="user.pwd"><br/>确认密码:<input name="okpwd"><br/><input type="submit" value="提交"> </form></body> </html>
效果图: