一 写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;}@Overridepublic void validate() {// TODO Auto-generated method stubsuper.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";}}
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN""http://struts.apache.org/dtds/struts-2.1.7.dtd"><struts><package name="struts2-demo1" extends="struts-default"><action name="login" class="he.action.Login"><result name='success' type='dispatcher'>/ok.jsp</result><result name='fail' type='dispatcher'>/index.jsp</result><result name="input">/index.jsp</result></action></package> </struts>
<%@ 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>