Struts2系列之三:注解式Action
以登录为例:
1. 页面文件
在webapp下新建login.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> <title>Welcome to the Struts world</title> </head> <body> <form action="${pageContext.request.getContextPath()}/user/login.action" method="post"> <label for="username">Username:</label> <input type="text" name="username" /><br /> <label for="password">Password:</label> <input type="password" name="password" /><br /> <input type="submit" value="Submit" /> <input type="reset" value="Clear" /> </form> </body> </html>
其中上下文可以写成:<%=request.getContextPath()%>
在WEB-INF下新建main.jsp:
<html> <body> <h2>Welcome, ${username}</h2> </body> </html>
2. Action类
LoginAction.java:
public class LoginAction extends ActionSupport { private static final long serialVersionUID = -1514466166933201351L; private String username; private String password; // getters and setters are omitted public String login() { return "success"; }
Struts2会将请求表单中的属性值自动填充到Action的对应属性中,可以为结果页面使用。
3. 配置文件:
在struts.xml中加入:
<package name="user" namespace="/user" extends="struts-default"> <action name="login" class="com.john.struts2.action.LoginAction" method="login"> <result name="success">/WEB-INF/main.jsp</result> </action> </package>
4. 测试
启动web工程,在浏览器输入:http://localhost:8080/mystruts2/login.jsp,输入用户名(John)和密码,提交后显示输入的用户名:
Welcome, John