首页 > 编程语言 > 详细

java学习笔记 (10) —— ActionContext、ServletActionContext、ServletRequestAware用法

时间:2016-03-13 14:10:02      阅读:239      评论:0      收藏:0      [点我收藏+]

核心思想

1、ActionContext

HttpServletRequest getAttribute setAttribute

ActionContext get put

//ActionContext.getContext() 获取入口
ActionContext.getContext().put("key", "value");

 2、ServletRequestAware

package com.test.action;

public class LoginAction extends ActionSupport implements ServletRequestAware
{
    private static final long serialVersionUID = -74906200993380354L;
    private HttpServletRequest request;
   
    
    @SuppressWarnings("unchecked")
    public String execute() throws Exception
    {
        if("james".equals(this.getUsername()) && "james".equals(this.getPassword())){
            Map map = ActionContext.getContext().getSession();
            //ActionContext.getContext() 获取入口
            //ActionContext.getContext().put("james", "get from AcionContext");
            request.setAttribute("chenkai", "from ServletRequestAware");
            map.put("user", "james");
            return "success"; 
        }else {
            this.addFieldError("username", "username or password is wrong");
            return "failer";
        }
    }
    
    /*
     * 实现 ServletRequestAware 接口 方法
     * struts2 自动加载,【ioc 依赖注入的方式】 将与容器相关的request参数set到应用里
     */
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }
    
}

 3、ServletResponseAware 与 Cookie 的使用

public class LoginAction extends ActionSupport implements ServletResponseAware
{
    private HttpServletResponse response;
  public String execute() throws Exception
    {
        
            Cookie cookie = new Cookie("name", "james");
            cookie.setMaxAge(100);
            response.addCookie(cookie);
            return SUCCESS; 
    }
}
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
  </head>  
  <body>
    username:${requestScope.username }<br>
    password:${requestScope.password }<br>
    Cookie:${cookie.name }
  </body>
</html>

 4、ServletActionContext

    public String execute() throws Exception
    {
            HttpServletResponse response = ServletActionContext.getResponse();
            Cookie cookie = new Cookie("name", "james");
            cookie.setMaxAge(100);
            response.addCookie(cookie);
            return SUCCESS; 
    }

建议使用顺序   

a) ActionContext 【首选】

    b) ServletActionContext [如果需要使用reponse]

    c) ServletRequestAware [必须实现接口]

java学习笔记 (10) —— ActionContext、ServletActionContext、ServletRequestAware用法

原文:http://www.cnblogs.com/cklovefan/p/5270124.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!