标签:index 查看 file cut 不一致 jar包 出错 nbsp run
package cn.itcast.action;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
// 获取请求参数 属性驱动 第一种,直接将action作为model
public class Login1Action extends ActionSupport {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
// 2.判断用户名与密码是否正确
if ("tom".equals(username) && "123".equals(password)) {
request.getSession().setAttribute("username", username);
return SUCCESS;
} else {
request.setAttribute("login.message", "用户名或密码错误");
return "failer";
}
}
}
login1.jsp<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
${requestScope["login.message"]}
<br>
<form action="${pageContext.request.contextPath}/login1" method="POST">
username:<input type="text" name="username"><br>
password:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
2.将model对象作为Action类成员(属性驱动模式二)package cn.itcast.domain;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
}
}
package cn.itcast.action;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import cn.itcast.domain.User;
import com.opensymphony.xwork2.ActionSupport;
// 获取请求参数 属性驱动 第二种,直接在action上声明一个model
public class Login2Action extends ActionSupport {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
// 2.判断用户名与密码是否正确
if ("tom".equals(user.getUsername())
&& "123".equals(user.getPassword())) {
request.getSession().setAttribute("username", user.getUsername());
return SUCCESS;
} else {
request.setAttribute("login.message", "用户名或密码错误");
return "failer";
}
}
}
login2.jsp<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
${requestScope["login.message"]}
<br>
<form action="${pageContext.request.contextPath}/login2" method="POST">
username:<input type="text" name="user.username"><br>
password:<input type="password" name="user.password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
3.模型驱动(action类实现ModelDrivern接口)package cn.itcast.action;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import cn.itcast.domain.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
// 获取请求参数 模型驱动
public class Login3Action extends ActionSupport implements ModelDriven<User> {
private User user=new User();
@Override
public User getModel() {
return user;
}
@Override
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
// 2.判断用户名与密码是否正确
if ("tom".equals(user.getUsername())
&& "123".equals(user.getPassword())) {
request.getSession().setAttribute("username", user.getUsername());
return SUCCESS;
} else {
request.setAttribute("login.message", "用户名或密码错误");
return "failer";
}
}
}
login3.jsp<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
${requestScope["login.message"]}
<br>
<form action="${pageContext.request.contextPath}/login3" method="POST">
username:<input type="text" name="username"><br>
password:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
${username }
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/list" method="POST">
username:<input type="text" name="users[0].username"><br>
password:<input type="password" name="users[0].password"><br>
username:<input type="text" name="users[1].username"><br>
password:<input type="password" name="users[1].password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
ListActionpackage cn.itcast.action;
import java.util.List;
import cn.itcast.domain.User;
import com.opensymphony.xwork2.ActionSupport;
public class ListAction extends ActionSupport {
private List<User> users;
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
@Override
public String execute() throws Exception {
System.out.println(users);
return null;
}
}
5.将数据封装到Map集合<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/map" method="POST">
username:<input type="text" name="map[‘aaa‘].username"><br>
password:<input type="password" name="map[‘aaa‘].password"><br>
username:<input type="text" name="map[‘bbb‘].username"><br>
password:<input type="password" name="map[‘bbb‘].password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
MapActionpackage cn.itcast.action;
import java.util.Map;
import cn.itcast.domain.User;
import com.opensymphony.xwork2.ActionSupport;
public class MapAction extends ActionSupport {
private Map<String, User> map;
public Map<String, User> getMap() {
return map;
}
public void setMap(Map<String, User> map) {
this.map = map;
}
@Override
public String execute() throws Exception {
System.out.println(map);
return null;
}
}
配置struts.xml<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="login1" class="cn.itcast.action.Login1Action">
<result name="failer">/login1.jsp</result>
<result type="redirect">/success.jsp</result>
</action>
<action name="login2" class="cn.itcast.action.Login2Action">
<result name="failer">/login2.jsp</result>
<result type="redirect">/success.jsp</result>
</action>
<action name="login3" class="cn.itcast.action.Login3Action">
<result name="failer">/login3.jsp</result>
<result type="redirect">/success.jsp</result>
</action>
<action name="list" class="cn.itcast.action.ListAction"></action>
<action name="map" class="cn.itcast.action.MapAction"></action>
</package>
</struts>
package cn.itcast;
public interface MyModelDriven<T> {
public T getModel();
}
创建User类(和上面的一样)package cn.itcast.action;
import cn.itcast.MyModelDriven;
import cn.itcast.User;
public class HelloAction implements MyModelDriven<User> {
// 剖析模型驱动
private User user = new User();
public User getModel() {
return user;
}
/* 属性驱动模式一
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
*/
public String say() {
System.out.println(user.getUsername() + " " + user.getPassword());
return "good";
}
}
自定义拦截器(模仿Struts中的params拦截器)package cn.itcast.filter;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import cn.itcast.MyModelDriven;
public class StrutsFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// 1.强转
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
// 2.操作
// 2.1 得到请求资源路径
String uri = request.getRequestURI();
String contextPath = request.getContextPath();
String path = uri.substring(contextPath.length() + 1);
// System.out.println(path); // hello
// 2.2 使用path去struts.xml文件中查找某一个<action name=path>这个标签
SAXReader reader = new SAXReader();
try {
// 得到struts.xml文件的document对象。
Document document = reader.read(new File(this.getClass()
.getResource("/struts.xml").getPath()));
Element actionElement = (Element) document
.selectSingleNode("//action[@name=‘" + path + "‘]"); // 查找<action
// name=‘hello‘>这样的标签
if (actionElement != null) {
// 得到<action>标签上的class属性以及method属性
String className = actionElement.attributeValue("class"); // 得到了action类的名称
String methodName = actionElement.attributeValue("method");// 得到action类中的方法名称。
// 2.3通过反射,得到Class对象,得到Method对象
Class actionClass = Class.forName(className);
Method method = actionClass.getDeclaredMethod(methodName);
// 处理请求参数封装:
Object actionObj = actionClass.newInstance();
// 2.模型驱动
if (actionObj instanceof MyModelDriven) {
MyModelDriven mmd = (MyModelDriven) actionObj;
BeanUtils.populate(mmd.getModel(),
request.getParameterMap());
} else {
// 1.属性驱动
BeanUtils.populate(actionObj, request.getParameterMap());//
}
// 2.4 让method执行.
String returnValue = (String) method.invoke(actionObj); // 是让action类中的方法执行,并获取方法的返回值。
// 2.5
// 使用returnValue去action下查找其子元素result的name属性值,与returnValue做对比。
Element resultElement = actionElement.element("result");
String nameValue = resultElement.attributeValue("name");
if (returnValue.equals(nameValue)) {
// 2.6得到了要跳转的路径。
String skipPath = resultElement.getText();
// System.out.println(skipPath);
request.getRequestDispatcher(skipPath).forward(request,
response);
return;
}
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 3.放行
chain.doFilter(request, response);
}
public void destroy() {
}
}
编辑自定义的struts.xml<?xml version="1.0" encoding="UTF-8" ?>
<struts>
<action name="hello" class="cn.itcast.action.HelloAction"
method="say">
<result name="good">/hello.jsp</result>
</action>
</struts>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP ‘index.jsp‘ starting page</title>
</head>
<body>
<h1>hello Struts2</h1>
</body>
</html>
index.jsp<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP ‘index.jsp‘ starting page</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/hello?username=tome&password=123">第一次使用struts2</a>
</body>
</html>
DefaultTypeConverter类实现了TypeConverter接口:
package cn.itcast.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import ognl.DefaultTypeConverter;
public class MyDateConverter extends DefaultTypeConverter {
@Override
public Object convertValue(Map context, Object value, Class toType) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
try {
if (toType == Date.class) {// 当字符串向Date类型转换时
String[] params = (String[]) value;
return dateFormat.parse(params[0]);
} else if (toType == String.class) {// 当Date转换成字符串时
Date date = (Date) value;
return dateFormat.format(date);
}
} catch (ParseException e) {
throw new RuntimeException("日期转换错误");
}
return null;
}
}
再新建一个日期转换类(使用另外一种方式继承自StrutsTypeConverter)package cn.itcast.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;
public class MyDateConverter2 extends StrutsTypeConverter {
// 接收页面传递的数据封装到JavaBean
@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
String value = values[0];
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date date = null;
try {
date = sdf.parse(value);
} catch (ParseException e) {
// e.printStackTrace();
throw new RuntimeException();
}
return date;
}
@Override
public String convertToString(Map context, Object o) {
return null;
}
}
具体代码如下:package cn.itcast.action1;
import cn.itcast.domain.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class RegistAction extends ActionSupport implements ModelDriven<User> {
private User user = new User();
@Override
public User getModel() {
return user;
}
@Override
public String execute() throws Exception {
System.out.println(user);
return null;
}
}
package cn.itcast.action2;
import java.util.Arrays;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
public class Regist2Action extends ActionSupport {
private String username;
private String password;
private int age;
private Date birthday;
private String[] hobby;
@Override
public String toString() {
return "Regist2Action [username=" + username + ", password=" + password
+ ", age=" + age + ", birthday=" + birthday + ", hobby="
+ Arrays.toString(hobby) + "]";
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
@Override
public String execute() throws Exception {
System.out.println(this);
return null;
}
}
birthday=cn.itcast.utils.MyDateConverter2
Userpackage cn.itcast.domain;
import java.util.Arrays;
import java.util.Date;
public class User {
private String username;
private String password;
private int age;
private Date birthday;
private String[] hobby;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password
+ ", age=" + age + ", birthday=" + birthday + ", hobby="
+ Arrays.toString(hobby) + "]";
}
}
User-conversion.propertiesbirthday=cn.itcast.utils.MyDateConverter
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="regist" class="cn.itcast.action1.RegistAction">
<result name="input">/success.jsp</result>
</action>
<action name="regist2" class="cn.itcast.action2.Regist2Action">
<result name="input">/success.jsp</result>
</action>
</package>
</struts>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/regist" method="POST">
username:<input type="text" name="username"><br>
password:<input type="password" name="password"><br>
hobby:<input type="checkbox" name="hobby" value="eat">吃
<input type="checkbox" name="hobby" value="drink">喝
<input type="checkbox" name="hobby" value="play">玩<br>
age:<input type="text" name="age"><br>
birthday:<input type="text" name="birthday"><br>
<input type="submit" value="注册">
</form>
</body>
</html>
regist2.jsp<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/regist2" method="POST">
username:<input type="text" name="username"><br>
password:<input type="password" name="password"><br>
hobby:<input type="checkbox" name="hobby" value="eat">吃
<input type="checkbox" name="hobby" value="drink">喝
<input type="checkbox" name="hobby" value="play">玩<br>
age:<input type="text" name="age"><br>
birthday:<input type="text" name="birthday"><br>
<input type="submit" value="注册">
</form>
</body>
</html>
success.jsp<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<s:fielderror/>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP ‘index.jsp‘ starting page</title>
</head>
<body>
<s:fielderror/>
<form action="${pageContext.request.contextPath}/login" method="post">
username:<input type="text" name="username"><s:fielderror fieldName="username.message"/><br>
password:<input type="password" name="password"><s:fielderror fieldName="password.message"/><br>
repassword:<input type="password" name="repassword"><br>
hobby:<input type="checkbox" name="hobby" value="eat">吃<input
type="checkbox" name="hobby" value="drink">喝<input
type="checkbox" name="hobby" value="play">玩<br> age:<input
type="text" name="age"><br> birthday:<input type="text"
name="birthday"><br>
email:<input type="text" name="email"><br>
url:<input type="text" name="url"><br>
telphone:<input type="text" name="telphone"><br>
<input type="submit" value="注册">
</form>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP ‘index.jsp‘ starting page</title>
</head>
<body>
<s:fielderror/>
<form action="${pageContext.request.contextPath}/regist" method="post">
username:<input type="text" name="username"><s:fielderror fieldName="username.message"/><br>
password:<input type="password" name="password"><s:fielderror fieldName="password.message"/><br>
repassword:<input type="password" name="repassword"><br>
hobby:<input type="checkbox" name="hobby" value="eat">吃<input
type="checkbox" name="hobby" value="drink">喝<input
type="checkbox" name="hobby" value="play">玩<br> age:<input
type="text" name="age"><br> birthday:<input type="text"
name="birthday"><br>
email:<input type="text" name="email"><br>
url:<input type="text" name="url"><br>
telphone:<input type="text" name="telphone"><br>
<input type="submit" value="注册">
</form>
</body>
</html>
新建model类Userpackage cn.itcast.domain;
import java.util.Arrays;
import java.util.Date;
public class User {
private String username;
private String password;
private int age;
private Date birthday;
private String[] hobby;
private String url;
private String email;
private String telphone;
private String repassword;
public String getRepassword() {
return repassword;
}
public void setRepassword(String repassword) {
this.repassword = repassword;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelphone() {
return telphone;
}
public void setTelphone(String telphone) {
this.telphone = telphone;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password
+ ", age=" + age + ", birthday=" + birthday + ", hobby="
+ Arrays.toString(hobby) + "]";
}
}
package cn.itcast.action;
import cn.itcast.domain.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
// 采用手动的方式
public class UserAction extends ActionSupport implements ModelDriven<User> {
private User user = new User();
@Override
public User getModel() {
return user;
}
@Override
public String execute() throws Exception {
System.out.println(user);
return null;
}
public String login() throws Exception {
System.out.println("login method ......");
return null;
}
public String regist() throws Exception {
System.out.println("regist method ......");
return null;
}
@Override
public void validate() {
System.out.println("validate method ......");
}
public void validateRegist() {
if (user.getUsername() == null
|| user.getUsername().trim().length() == 0) {
// 说明用户名为空
this.addFieldError("username.message", "用户名不能为空");
}
if (user.getPassword() == null
|| user.getPassword().trim().length() == 0) {
this.addFieldError("password.message", "密码不能为空");
}
if (!(user.getAge() >= 10 && user.getAge() <= 40)) {
this.addFieldError("age.message", "年龄必须在10-40之间");
}
System.out.println("validateRegist......");
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="regist" class="cn.itcast.action.UserAction"
method="regist">
<result name="input">/regist.jsp</result>
</action>
<action name="login" class="cn.itcast.action.UserAction"
method="login">
<result name="input">/login.jsp</result>
</action>
</package>
</struts>
输入http://localhost/mystruts2_day02_3/login.jsp 直接提交<validator name="required" class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/>
<validator name="requiredstring" class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/>
<validator name="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/>
<validator name="long" class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/>
<validator name="short" class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/>
<validator name="double" class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/>
<validator name="date" class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/>
<validator name="expression" class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/>
<validator name="fieldexpression" class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/>
<validator name="email" class="com.opensymphony.xwork2.validator.validators.EmailValidator"/>
<validator name="url" class="com.opensymphony.xwork2.validator.validators.URLValidator"/>
<validator name="visitor" class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/>
<validator name="conversion" class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/>
<validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/>
<validator name="regex" class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/>
<validator name="conditionalvisitor" class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<!-- 对username属性进行校验 -->
<field name="username">
<!-- 指定username不能为空 -->
<field-validator type="requiredstring">
<!-- 错误信息 -->
<message>用户名不能为空---</message>
</field-validator>
<!-- 长度校验,规定用户名必须在6-10位之间 -->
<field-validator type="stringlength">
<param name="maxLength">10</param>
<param name="minLength">6</param>
<message>用户名必须在${minLength}-${maxLength}位之间</message>
</field-validator>
</field>
<!-- 对age进行校验,规定年龄必须在10-40之间 -->
<field name="age">
<field-validator type="int">
<param name="min">10</param>
<param name="max">40</param>
<message>年龄必须在${min}--${max}之间</message>
</field-validator>
</field>
<!-- 对birthday进行校验 -->
<field name="birthday">
<field-validator type="date">
<param name="min">1974-01-01</param>
<param name="max">2004-12-31</param>
<message>生日必须在${min}--${max}年之间</message>
</field-validator>
</field>
<!-- 校验邮箱 -->
<field name="email">
<field-validator type="email">
<message>邮箱格式不正确</message>
</field-validator>
</field>
<!-- url校验 -->
<field name="url">
<field-validator type="url">
<message>url不合法,应类似于http://www.baidu.com</message>
</field-validator>
</field>
<!-- 使用正则 -->
<field name="telphone">
<field-validator type="regex">
<param name="regexExpression"><![CDATA[^135[0-9]{8}$]]></param>
<message>电话号码必须是135xxxxxxxx</message>
</field-validator>
</field>
<field name="repassword">
<field-validator type="fieldexpression">
<param name="expression"><![CDATA[(password==repassword)]]></param>
<message>两次密码输入不一致</message>
</field-validator>
</field>
</validators>
调试结果如下:JAVAWEB开发之Struts2详解(二)——Action接受请求参数、类型转换器、使用Struts2的输入校验、以及遵守约定规则实现Struts2的零配置
标签:index 查看 file cut 不一致 jar包 出错 nbsp run
原文地址:http://blog.csdn.net/u013087513/article/details/60867351