在struts2中訪问servletAPI
生活随笔
收集整理的這篇文章主要介紹了
在struts2中訪问servletAPI
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在struts2中訪問servletAPI,通俗點也就是使用servlet中的兩個對象request對象和response對象。
前幾天看到一個CRM項目的源代碼,里面使用request對象和response對象方式和我曾經(jīng)使用的方式有點不同,于是便上網(wǎng)查詢一些相關(guān)資料。特此記錄于此,有興趣的也能夠參考參考。
- 以往使用struts2往網(wǎng)頁填充數(shù)據(jù)通常採用往值棧存放數(shù)據(jù)。也就是ActionContext.getContext().****();后面的方法類似與request對象和response對象的方法。
- 這幾天看到的是實現(xiàn)接口ServletRequestAware,ServletResponseAware。通過這兩個接口實現(xiàn)兩個方法setServletResponse(HttpServletResponse response)與setServletRequest(HttpServletRequest request)。然后訪問用戶請求的HttpServletRequest實例與server響應(yīng)的HttpServletResponse實例。
- 進過上網(wǎng)查找另一種ServletActionContext。這個類直接繼承了ActionContext。
- Object get(Object key):該方法類似于調(diào)用HttpServletRequest的getAttribute(String name)方法;
- Map getApplication():返回一個Map對象。該對象模擬了該應(yīng)用的ServletContext實例。
- static ActionContext getContext():靜態(tài)方法,獲取系統(tǒng)的ActionContext實例;
- Map getParameters():獲取全部的請求參數(shù)。
類似于調(diào)用HttpServletRequest對象的getParameterMap方法;
- Map getSession():返回一個Map對象,該Map對象模擬了HttpSession實例。
- void setApplication(Map application):直接傳入一個Map實例,將該Map實例里的key-value對轉(zhuǎn)換成application的屬性名。屬性值;
- void setSession(Map session):直接傳入一個Map實例。將該Map實例里的key-value對轉(zhuǎn)換成session的屬性名。屬性值
- static PageContext getPageContext():取得Web應(yīng)用的PageContext對象;
- static HttpServletRequest getRequest():取得web應(yīng)用的HttpServletRequest對象;
- static HttpServletResponse getResponse():取得web應(yīng)用的HttpServletResponse對象;
- static ServletContext getServletContext():取得web應(yīng)用的ServletContext對象;
我貼上代碼來看看吧。
ServletRequestAware,ServletResponseAware
package cn.crm.web.action;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware;import com.opensymphony.xwork2.ActionSupport;public class BaseAction extends ActionSupport implements ServletRequestAware,ServletResponseAware{protected HttpServletRequest request;protected HttpServletResponse response;@Overridepublic void setServletResponse(HttpServletResponse response) {// TODO Auto-generated method stubthis.response=response;}@Overridepublic void setServletRequest(HttpServletRequest request) {// TODO Auto-generated method stubthis.request=request;}} ActionContextActionContext context = ActionContext.getContext(); Map params = context.getParameters(); String username = (String) params.get("username");
HttpServletRequest request = ServletActionContext. getRequest(); HttpSession session = ServletActionContext. getRequest().getSession();
轉(zhuǎn)載于:https://www.cnblogs.com/bhlsheji/p/5076747.html
總結(jié)
以上是生活随笔為你收集整理的在struts2中訪问servletAPI的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端模块化杂谈
- 下一篇: 1-5-20:球弹跳高度的计算