1.目录结构及导入的jar包
2.web.xml 配置
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
6 <welcome-file-list>
7 <welcome-file>index.jsp</welcome-file>
8 </welcome-file-list>
9
10 <filter>
11 <filter-name>StrutsPrepareAndExecuteFilter</filter-name>
12 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
13 </filter>
14
15 <filter-mapping>
16 <filter-name>StrutsPrepareAndExecuteFilter</filter-name>
17 <url-pattern>/*</url-pattern>
18 </filter-mapping>
19
20 </web-app>
2.Action类编写
User JavaBean定义
1 package cn.test.entity;
2
3 public class User {
4
5 private String name;
6 private String age;
7 private String password;
8
9 public String getAge() {
10 return age;
11 }
12
13 public void setAge(String age) {
14 this.age = age;
15 }
16
17 public String getName() {
18 return name;
19 }
20
21 public void setName(String name) {
22 this.name = name;
23 }
24
25
26 public String getPassword() {
27 return password;
28 }
29
30 public void setPassword(String password) {
31 this.password = password;
32 }
33
34 @Override
35 public String toString() {
36 return "User [age=" + age + ", name=" + name + ", password=" + password
37 + "]";
38 }
39
40 }
通过继承ActionSupport类创建 Action控制器:
(1)不管是通过Javabean 还是直接通过属性字段获取请求数据,都需要在Action类设置setter getter方法
(2)ActionSupport类实现了Action接口,所以此处可以选择重写execute() 方法,处理请求
(3)此处通过ActionContext类访问Servlet API,获取session对象
1 package cn.test.action;
2
3 import cn.test.entity.User;
4
5 import com.opensymphony.xwork2.Action;
6 import com.opensymphony.xwork2.ActionContext;
7 import com.opensymphony.xwork2.ActionSupport;
8
9 /**
10 * Action处理请求参数-属性驱动 strtus2中页面的请求数据和Action有两种基本的对应方式,分别是字段驱动和模型驱动方式。字段驱动也叫属性驱动
11 * 属性驱动是指通字段进行数据传递,包括:与基本数据类型的属性对应,直接使用域对象(也就是javaBean)
12 *
13 * @author Administrator
14 *
15 */
16 public class UserLoginAction extends ActionSupport {
17
18 private static final long serialVersionUID = 1L;
19 private User user;// 通过javaBean获取前端传递的数据;必须设置getter setter方法
20
21 public User getUser() {
22 return user;
23 }
24
25 public void setUser(User user) {
26 this.user = user;
27 }
28
29 @Override
30 public String execute() throws Exception { //继承ActionSupport接口的Action类中,必须要有重写的execute方法
31 //获取Context对象: 通过ActionContext类访问Servlet API
32 ActionContext context = ActionContext.getContext();
33 if("admin".equals(user.getName()) && "123".equals(user.getPassword())){
34 //把用户名和密码放到session中
35 context.getSession().put("username", user.getName());
36 context.getSession().put("password", user.getPassword());
37 return Action.SUCCESS;
38 } else {
39 context.getSession().put("error", "用户登陆失败");
40 return ERROR;//Action接口中定义的常量
41 }
42
43 }
44
45
46
47 }
3. struts.xml中 action的配置
当Action类返回“success”逻辑视图名,请求转发到loginSuccess.jsp 页面,当返回error 逻辑视图名,请求转发到 loginError.jsp 页面。
红色部分是配置了一个默认的action,当请求一个不存在的action时,一般页面会报404 not found,当我们配置默认的action,如果请求一个不存在的aciton时,页面就会跳转到
我们指定的错误页面,而不是提示404, 此处跳转到error.jsp 页面
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE struts PUBLIC
3 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
4 "http://struts.apache.org/dtds/struts-2.3.dtd">
5 <struts>
6 <!-- 开启动态调用,并且设置启用开发者模式 -->
7 <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
8 <constant name="struts.devMode" value="true"></constant>
9
10 <!-- 配置默认的action,当请求一个不存在的Action,将跳转到error.jsp页面-->
11 <package name="default" namespace="/user" extends="struts-default">
12 <default-action-ref name="defaultAction"></default-action-ref>
13 <action name="defaultAction">
14 <result>/error.jsp</result>
15 </action>
16 </package>
17
18 <package name="user" namespace="/user" extends="struts-default">
19 <action name="userLogin" class="cn.test.action.UserLoginAction">
20 <result name="success">/loginSuccess.jsp</result>
21 <result name="error">/loginError.jsp</result>
22 </action>
23 </package>
24 </struts>
4. JSP页面编写
登录页面userLogin.jsp(浏览器直接请求该页面,进入到登陆页面):
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2
3 <%
4 String path = request.getContextPath();
5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
6 %>
7
8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
9 <html>
10 <head>
11 <base href="<%=basePath%>">
12 <title>userLogin page</title>
13 </head>
14 <body>
15 <div style="margin:10px;padding:10px">
16 <form name="fomr1" action="<%=basePath%>user/userLogin.action" method="post">
17 用户名:<input type="text" name="user.name" /><br/>
18 密码: <input type="password" name="user.password" /><br/>
19 <input type="submit" value="登陆" />
20 </form>
21 </div>
22 </body>
23 </html>
登陆成功页面
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2 <%@ taglib uri="/struts-tags" prefix="s"%>
3 <%
4 String path = request.getContextPath();
5 String basePath = request.getScheme() + "://"
6 + request.getServerName() + ":" + request.getServerPort()
7 + path + "/";
8 %>
9
10 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
11 <html>
12 <head>
13 <base href="<%=basePath%>">
14 <title>My JSP 'success.jsp' starting page</title>
15 </head>
16
17 <body>
18 登陆成功,session中的登陆用户名是:<%=request.getAttribute("user.name") %><br>
19 <!--<s:property value="name"/> value里面写上Action类中定义的属性,就能在jsp页面显示请求中所带的参数了 -->
20 采用OGNL与Struts2标签输出Action类的属性值(Action类获取到的请求参数值) <br/>
21 name=<s:property value="user.name" /> password=<s:property value="user.password" /> <br>
22 采用EL表达式 输出Action类的属性值(${对象名.属性名 }):<br>
23 name=${user.name }
24 </body>
25 </html>
登陆失败页面
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2 <%@ taglib uri="/struts-tags" prefix="s"%>
3 <%
4 String path = request.getContextPath();
5 String basePath = request.getScheme() + "://"
6 + request.getServerName() + ":" + request.getServerPort()
7 + path + "/";
8 %>
9
10 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
11 <html>
12 <head>
13 <base href="<%=basePath%>">
14 <title>登陆失败页面</title>
15 </head>
16
17 <body>
18 控制器返回的错误信息为:${error };<br>
19 <a href="userLogin.jsp">单击链接返回登陆页面</a>
20 </body>
21 </html>
默认Action指定的跳转页面
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2 <%
3 String path = request.getContextPath();
4 String basePath = request.getScheme() + "://"
5 + request.getServerName() + ":" + request.getServerPort()
6 + path + "/";
7 %>
8
9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
10 <html>
11 <head>
12 <base href="<%=basePath%>">
13 <title>My JSP 'success.jsp' starting page</title>
14 </head>
15 <body>
16 真不巧,您访问的页面走丢了<br>
17 <a href="userLogin.jsp">单击链接返回登陆页面</a>
18 </body>
19 </html>
部署测试:
(1)输入一个访问不到的请求:http://localhost:8080/strutsstu3/user/userLogi ,此时处理请求的是默认Action
(2) 单击上一步的链接, 转到 http://localhost:8080/strutsstu3/userLogin.jsp
输入admin 和一个错误的密码,结果如下:
单击链接返回登陆页,输入admin 和123 提交,结果如下
注:
(1)在使用Javabean属性方式传值时,如果JSP页面时负责取值的,那么取值的格式必须为“对象.属性名”;如果JSP页面时负责传值的,那么传值的格式可以为“对象.属性名”,也可以直接是“属性名”;
(2)Struts2的Action没有与ServletAPI发生耦合,但是web开发中经常会用到ServletAPI中的对象,如用户登陆成功,则应该将用户信息保存到HttpSession中,而最常用的ServletAPI就是HttpSession, HttpServletRequest、ServletContext这三个接口,Strtus2访问ServletAPI,可以分为2类:与Servlet API 解耦的访问方式和与servlet API耦合的访问方式。
与Servlet API 解耦的访问方式:
(a)使用ActionContext类获取Servlet 对象对用的Map对象
例如:
ActionContext context = ActionContext.getContext();
Map request = (Map) context.get("request");//ActionContext类没有提供getRequest()这样的方法来获取HttpServletRequest对应的map对象,要想得到HttpServletRequest对象对应的map对象,需要为get()方法传递request参数
context.put("username", "admin"); //放到request作用域,相当于ServletAPI中国年的HttpServletRequest的setAttribute()方法
context.getSession().put("username", "admin"); // 把信息放到session作用域
context.getApplication().put("username", "admin"); // 把信息放到Application 作用域
(b) 实现特定接口获取Servlet API对象
与Servlet API 耦合的访问方式:
示例代码下载地址 https://github.com/liuch0228/Struts2SSH.git