//submit page
<%@ 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:form action="login.action" method="post">
<s:textfield label="User Name:" name="user.userName"></s:textfield> <!--set方法-->
<s:textfield label="User Name:" name="user.userPwd"></s:textfield>
<s:submit label="submit"></s:submit>
</s:form>
</body>
</html>
//po
public class User implements Serializable {
private String userName;
private String userPwd;
public User() { //必须有这个空的构造方法
}
public User(String userName, String userPwd) {
this.userName = userName;
this.userPwd = userPwd;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
}
//action
public class UserAction extends ActionSupport {
private User user;
public User getUser() { //必须set get 方法
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String execute() throws Exception {
if(user.getUserName() != null && !"".equals(user.getUserName().trim())){
System.out.println(SUCCESS);//output : success
return SUCCESS;
}else{
System.out.println(ERROR);
addFieldError("userName","userName is abc");
return ERROR;//output : error
}
}
}
//struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="strust2" extends="struts-default">
<action name="login" class="com.struts2.action.UserAction">
<result name="success">/index.jsp</result>
<result name="error">/MyJsp.jsp</result>
</action>
</package>
</struts>
//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>