首页 > 代码库 > ActionContext和Session

ActionContext和Session

1、在执行action后,如果要在所跳转的目标页面中显示信息,则要用到Action和Session。

2、在Struts2中,Action已经与Servlet API分离,这使得Action具有更加灵活和低耦合的特性。

3、Struts2提供了ActionContext类;ActionContext是一个Action的上下文对象,Action运行期间所用到的数据都保存在ActionContext中。

4、通过ActionContext.getContext()方法获取ActionContext的实例对象。

5、ActionContext的其中一个方法:    Map getSession()   返回一个Map类型的HttpSession对象。

6、代码事例

  (1)Aciton中产生Session对象的代码

 1 package com.action;
 2 
 3 import com.factory.StudentDAOFactory;
 4 import com.opensymphony.xwork2.ActionContext;
 5 import com.vo.Student;
 6 
 7 public class Login {
 8     private String Type;
 9     private String Username;
10     private String Password;
11     private String Msg;
12     public String getType() {
13         return Type;
14     }
15     public void setType(String type) {
16         Type = type;
17     }
18     public String getUsername() {
19         return Username;
20     }
21     public void setUsername(String username) {
22         Username = username;
23     }
24     public String getPassword() {
25         return Password;
26     }
27     public void setPassword(String password) {
28         Password = password;
29     }
30     public String getMsg() {
31         return Msg;
32     }
33     public void setMsg(String msg) {
34         Msg = msg;
35     }
36     public String execute()throws Exception{
37         if(Type.equals("学生")){
38             Student student = new Student();
39             student.setStudent_Number(getUsername());
40             student.setStudent_Password(getPassword());
41             if(StudentDAOFactory.getIStudentDAOInstance().studentLogin(student)){
42                 ActionContext.getContext().getSession().put("student_number", student.getStudent_Number());
43                 ActionContext.getContext().getSession().put("student_name", student.getStudent_Name());
44                 ActionContext.getContext().getSession().put("student_sex", student.getStudent_Sex());
45                 ActionContext.getContext().getSession().put("student_domitory", student.getStudent_Domitory());
46                 ActionContext.getContext().getSession().put("student_password", student.getStudent_Password());
47                 ActionContext.getContext().getSession().put("student_absenceDate", student.getStudent_AbsenceDate());
48                 return "success";
49             }else{
50                 Msg = "用户名或者密码错误";
51                 return "error";
52             }
53         }else{
54             Msg = "身份选择错误!";
55             return "error";
56         }
57     }
58 }

(2)跳转的目标页面中显示Action处理后的信息

 1 <html>
 2   <head>
 3     
 4     <title>My JSP ‘welcome.jsp‘ starting page</title>
 5 
 6   </head>
 7   
 8   <body>
 9     successfully!!!
10     ${student_number }
11     ${student_name } 
12     ${student_sex }
13     ${student_domitory }
14     ${student_password }
15     ${student_absenceDate }
16   </body>
17 </html>

 

ActionContext和Session