访问Servlet API,访问web资源

来源:互联网 发布:2017年正能量网络热词 编辑:程序博客网 时间:2024/06/03 17:18

1.什么是WEB资源
> HttpServletRequest HttpSession ServletContext等原生的Servlet API

2.为什么访问WEB资源
> B/S 的应用的Controller中 必然需要访问web资源 向域对象中读写属性,读写Cookie 获取 realPath ....

3.如何访问 ?

I. 和 Servlet API 解耦的方式: 只能访问有限的 Servlet API 对象, 且只能访问其有限的方法(读取请求参数, 读写域对象的属性, 使 session 失效...).

> 使用 ActionContext

//0.获取ActionContext对象,是Action的上下文对象,可以从中获取ActionContext actionContext = ActionContext.getContext();//1.获取application对应的Map,并向其中添加一个属性Map<String,Object> applicationMap = actionContext.getApplication();//设置属性applicationMap.put("applicationKey","applicationValue");//获取属性 JSP文件中定义的dateObject date  = applicationMap.get("date");System.out.println("date:" + date);//2.sessionMap<String,Object> sessionMap = actionContext.getSession();sessionMap.put("SessionKey", "SessionValue");//3.request//actionContext中并没有提供getRequest方法来获取request对应的Map//需要手工调用get(),传入request字符串获取Map<String,Object> requestMap = (Map<String, Object>) actionContext.get("request");requestMap.put("requestKey","requestValue");//4.获取请求参数对应的Map,//键: 请求参数的名字, 值: 请求参数的值对应的字符串数组//注意: 1. getParameters 的返回值为 Map<String, Object>, 而不是 Map<String, String[]>//     2. parameters 这个 Map 只能读, 不能写入数据, 如果写入, 不出错, 但也不起作用!Map<String,Object> parameters = actionContext.getParameters();System.out.println(((String[])parameters.get("name"))[0]);parameters.put("age", 100);



> 实现 XxxAware 接口

public class TestAwareAction implements ApplicationAware,SessionAware,RequestAware,ParameterAware {private Map<String, Object> application;private Map<String, String[]> parameters;private Map<String, Object> session;private Map<String, Object> request;public String execute(){//1.向application中加入一个属性:applicationKey2 - applicationValue2application.put("applicationKey2", "applicationValue2");//2.从 application 中读取一个属性 date, 并打印. System.out.println(application.get("date"));return "success";}public void setApplication(Map<String, Object> application) {this.application = application;}public void setParameters(Map<String, String[]> parameters) {this.parameters = parameters;}public void setSession(Map<String, Object> session) {this.session = session;}public void setRequest(Map<String, Object> request) {this.request = request;}}


> 选用的建议: 若一个 Action 类中有多个 action 方法, 且多个方法都需要使用域对象的 Map 或 parameters, 则建议使用
Aware 接口的方式

> session 对应的 Map 实际上是 SessionMap 类型的! 强转后若调用其 invalidate() 方法, 可以使其 session 失效!

II. 和 Servlet API 耦合的方式: 可以访问更多的 Servlet API 对象, 且可以调用其原生的方法.

> 使用 ServletActionContext
1)使用HttpServletRequest

ServletActionContext.getRequest().setAttribute(key,value);
2)使用HttpSession

ServletActionContext().getRequest().getSession().setAttribute(key,value);
3)使用ServletContext

ServletActionContext.getServletContext().setAttribute(key,value);

> 实现 ServletXxxAware 接口.



0 0
原创粉丝点击