获取HttpServletRequest / HttpSession / ServletContext / HttpServletResponse对象

阅读更多
获得这些stuctsHttpServletRequest / HttpSession / ServletContext /
HttpServletResponse对象方法有两种:

第一种:直接得到对象方式

<1、编写Action

public class ServletObject {

public String rsa()
{

HttpServletRequest request=ServletActionContext.getRequest();

request.setAttribute("request", "Request");

ServletContext servletContext = ServletActionContext.getServletContext();

servletContext.setAttribute("application", "Application");

request.getSession().setAttribute("request", "Request");

HttpServletResponse response = ServletActionContext.getResponse();

return "scope";
}
}
<2、配置struts.xml文件

/WEB-INF/page/scope.jsp

       

<3、编写scope.jsp得到写入的值
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


 
    My JSP 'hello.jsp' starting page
   


   



 

    Application:${applicationScope.application}

Session:${sessionScope.session}

Request:${requestScope.request}

 

<4、部署

第二种:implements ServletRequestAware, ServletResponseAware, ServletContextAware这些接口在实现方法中得到对象

<1、编写Action
public class HelloWorldAction implements ServletRequestAware,
ServletResponseAware, ServletContextAware {

private HttpServletRequest request;
private ServletContext servletContext;
private HttpServletResponse response;

public void setServletRequest(HttpServletRequest request) {
this.request=request;
}

public void setServletResponse(HttpServletResponse response) {
this.response=response;
}

public void setServletContext(ServletContext servletContext) {
this.servletContext=servletContext;
}
public String rsa()
{

//HttpServletRequest request=ServletActionContext.getRequest();

request.setAttribute("request", "Request");

//ServletContext servletContext = ServletActionContext.getServletContext();

servletContext.setAttribute("application", "Application");

request.getSession().setAttribute("request", "Request");

//HttpServletResponse response = ServletActionContext.getResponse();

return "scope";
}
}
<2、配置strus.xml文件


/WEB-INF/page/scope.jsp

       


<3、编写scope.jsp文件得到写入的值
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


 
    My JSP 'hello.jsp' starting page
   


   



 

    Application:${applicationScope.application}

Session:${sessionScope.session}

Request:${requestScope.request}

 

<4、部署

.......

你可能感兴趣的:(HttpSession,ServletContext)