我是靠谱客的博主 无情人生,最近开发中收集的这篇文章主要介绍Struts2获取request,session,application的几种方式,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

request,session,application在正常使用时,在会话中传递数据的方式都是通过key-value的形式传递,因此,我们可以将它们看做Map,Struts2为我们提供了多种获取它们的方法;

  1. 通过ActionContext获取得到

public class TestAction1 extends ActionSupport {
//初始化三个同名map
private Map request;
private Map session;
private Map application;
//在构造器内对获取到web元素之后赋值给到之前的map
public LoginAction1(){
request = (Map) ActionContext.getContext().get("request");
session = (Map) ActionContext.getContext().getSession();
application = (Map) ActionContext.getContext().getApplication();
}
//此时map已经具有web元素的作用,可以在web作用域里面传递数据啦
public String execute(){
request.put("1", "1");
session.put("2", "2");
application.put("3", 3");
return SUCCESS;
}

2.通过实现RequestAware,SessionAware,ApplicationAware接口达到IOC控制反转来实现获取web元素;(此方法建议重点掌握)

public class TestAction2 extends ActionSupport implements RequestAware,SessionAware,ApplicationAware {
//初始化三个同名指定数据类型的同名map(接口中的方法有规定了)
private Map<String, Object> request;
private Map<String, Object> session;
private Map<String, Object> application;
//实现三个接口中的方法
public void setRequest(Map<String, Object> request) {
this.request = request;
}
public void setSession(Map<String, Object> session) {
this.session = session;
}
public void setApplication(Map<String, Object> application) {
this.application = application;
}
//放入Key与value
public String execute(){
request.put("1", "1");
session.put("2", "2");
application.put("3", 3");
return SUCCESS;
}
}

3.通过普通的HttpServlet方法获取;

public class TestAction3 extends ActionSupport {
//先初始化三个web元素
private HttpServletRequest request;
private HttpSession session;
private ServletContext application;
//获取web元素
public TestAction3(){
request = ServletActionContext.getRequest();
session = request.getSession();
application = session.getServletContext();
}
//放入Key与value
public String execute(){
request.setAttribute("1", "1");
session.setAttribute("2", "2");
application.setAttribute("3", "3");
return SUCCESS;
}

4.通过实现ServletRequestAware接口获取;

public class TestAction3 extends ActionSupport implements SevletRequestAware {
//先初始化三个web元素
private HttpServletRequest request;
private HttpSession session;
private ServletContext application;
//实现ServletRequestAware中的setServletRequest
public void setServletRequest(HttpServletRequest request){
this.request = request;
this.seesion = request.getSession();
this.application = session.getServletContext;
}
//获取web元素
public TestAction4(){
request = ServletActionContext.getRequest();
session = request.getSession();
application = session.getServletContext();
}
//放入Key与value
public String execute(){
request.setAttribute("1", "1");
session.setAttribute("2", "2");
application.setAttribute("3", "3");
return SUCCESS;
}

最后

以上就是无情人生为你收集整理的Struts2获取request,session,application的几种方式的全部内容,希望文章能够帮你解决Struts2获取request,session,application的几种方式所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(43)

评论列表共有 0 条评论

立即
投稿
返回
顶部