Struts2支持直接使用领域对象接收用户输入的数据。
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>My JSP 'login.jsp' starting page</title>
</head>
<body>
<form action="/learnstructslogin/way2/login.action" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="user.username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="user.password"></td>
</tr>
<tr>
<td><input type="reset" value="重置"></td>
<td><input type="submit" value="提交"></td>
</tr>
</table>
</form>
</body>
</html>
领域对象User类:User.java
package com.pei.learnstruts.login.way2;
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;
}
}
LoginAction.java
package com.pei.learnstruts.login.way1;
import com.opensymphony.xwork2.Action;
public class LoginAction implements Action{
private User user;
public String execute() throws Exception{
System.out.println("123");
if(user.getUsername().equals("xupei")&&user.getPassword().equals("123456")){
return SUCCESS;
}else{
return ERROR;
}
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
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>
<package name="way1" namespace="/way1" extends="struts-default">
<action name="login" class="com.pei.learnstruts.login.way1.LoginAction">
<result name="success">/way1/success.jsp</result>
<result name="error">/way1/error.jsp</result>
</action>
</package>
</struts>
success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'success.jsp' starting page</title>
</head>
<body>
SUSSESS. <br>
<h3><s:property value="user.username"/></h3>
</body>
</html>
error.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>My JSP 'error.jsp' starting page</title>
</head>
<body>
ERROR. <br>
</body>
</html>