struts2中手动完成输入校验

手动校验是通过重写validate()方法来实现的

以登录为例:

1.Login.jsp代码

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Login</title>
</head>
<body>
<s:form action="Login.action">
<s:textfield name="name" label="Name"/>
<s:fielderror>
<s:param>name.xml</s:param>
</s:fielderror>
<s:password name="password" label="Password"/>
<s:fielderror>
<s:param>password.xml</s:param>
</s:fielderror>
<s:submit value="Login"/>
</s:form>
</body>
</html>

2.Login.java代码

import com.opensymphony.xwork2.ActionSupport;

public class Login extends ActionSupport {
private String name;
private String password;
private String message;

public String execute(){
message = "Welcome, xml!";
return SUCCESS;
}

public void validate(){ //这里必须为validate()方法
if(!name.equalsIgnoreCase("xml")){
this.addFieldError("name.xml", "用户名必须为xml");
this.addActionError("用户名错误,登录失败");
}
if(!password.equalsIgnoreCase("xml")){
this.addFieldError("password.xml", "密码必须为xml");
this.addActionError("密码错误,登录失败");
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}


public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

3.struts.xml文件中进行关联

<action name="Login" class="com.koubei.Login">
<result name="success">/Welcome.jsp</result>
<result name="input">/Login.jsp</result>
</action>

4.登录成功页面

<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!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=GB18030">
<title>welcome</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>

这里验证validate()方法是自动调用的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值