您的位置:首页 > 编程语言 > Java开发

表单校验---struts2

2015-12-28 20:25 507 查看
一 写validate方伐

    1 让你的Action继承ActionSupport类,

      重写validate方法,(或validateXxxx)

      判断,写入错误信息

      jsp中用标签显示,struts。xml中配置转向的页面

package he.action;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class Login extends ActionSupport{
String name;
String pwd;

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;
}

@Override
public void validate() {
// TODO Auto-generated method stub
super.validate();
if("".equals(name)||name==null){
this.addFieldError("name", "name can not be null");
}
if("".equals(pwd)||pwd==null){
this.addFieldError("pwd", "pwd can not be null");
}
}

public String execute(){
System.out.print(name+"  \n"+pwd);
if("scott".equals(name)&&"1234".equals(pwd)){
Map<String, Object> session = ActionContext.getContext().getSession();
session.put("user", name);
return "success";
}
this.addActionError("name do not match pwd");
return "fail";
}

}


<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/struts-tags"  prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.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>
<s:actionerror/>
<s:form action="login" >
<s:textfield  name="name" label="name" labelposition="left"></s:textfield>
<s:fielderror fieldName="name"></s:fielderror><br>
<s:textfield  name="pwd" label="pwd" labelposition="left"></s:textfield>
<s:fielderror fieldName="pwd"></s:fielderror><br>
<s:submit  value="OK"></s:submit>
</s:form>
</body>
</html>


index.jsp
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: