package wusihanWeb;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
publicclassUserActionextendsActionSupportimplementsModelDriven<User>{//此处与上面不同,必须人为new User因为这种方式不会调用setUser方法,会直接调用getModel方法来获取User对象,如果不在 此时new User那么此时user为空,调用该对象的setName或setAge时会空指针异常private User user = new User();
@Override
public User getModel() {
System.out.println("getModel");
return user;
}
public String execute(){
return"success";
}
}
package wusihanWeb;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
publicclassUserActionextendsActionSupportimplementsModelDriven<User>{private User user = new User();
@Override
public User getModel() {
System.out.println("getModel");
return user;
}
public String execute(){
//根据不同的姓名内容返回不同的页面,从而达到验证的目的 if(user.getName()==null||!user.getName().equals("admin")){
this.addFieldError("name", "name is error");
return"error";
}
return"success";
}
}
jsp中代码如下
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%><%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!--使用/struts-tags标签 --><%@taglib uri="/struts-tags" prefix="s" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><basehref="<%=basePath%>"><title>HelloStruts2</title><metahttp-equiv="pragma"content="no-cache"><metahttp-equiv="cache-control"content="no-cache"><metahttp-equiv="expires"content="0"><metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"><metahttp-equiv="description"content="This is my page"><!--
<link rel="stylesheet" type="text/css" href="styles.css">
--></head><body>
Hello Struts2 <br><!--s对应上面的prefix,fielderror对应action类中使用的方法addFieldError,fieldName对应addFieldError方法的第一个参数,theme为主题,simple为默认主题,下面这句话可以用简单的样式显示出addFieldError第二个参数的内容 --><s:fielderrorfieldName="name"theme="simple"/></body></html>