zoukankan      html  css  js  c++  java
  • 【Java】Struts2中使用ServletAPI

    • ActionContext的方式

    登录的表单:

        <form action="login.action" method="post">
            name:<input type="text" name="username"><br>
            password:<input type="password" name="password"><br>
            <input type="submit" value="Submit">
        </form>

    登录的控制器:

    package com.action;
    
    import com.opensymphony.xwork2.ActionContext;
    import com.opensymphony.xwork2.ActionSupport;
    import com.opensymphony.xwork2.ModelDriven;
    import com.pojo.User;
    
    public class Login extends ActionSupport implements ModelDriven<User>{
        private User user = new User();
        @Override
        public String execute() throws Exception {    
    //        通过Struts2提供的ActionContext类,访问ServletAPI
    //        Object get(Object key):此方法类似调用HttpServletRequest的getAttrbute(String name)
    //        Map getApplication():返回一个Map对象,该对象模拟了该应用的ServletContext实例
    //        static ActionContext getContext():静态方法,返回系统的actionContext实例
    //        Map getParameters():获取所有的请求参数。类似于调用HttpServletRequest对象的getParameterMap()方法
    //        Map getSession():返回一个Map对象,该Map对象模拟了HttpSession实例
    //        void setApplication(Map application):直接传入一个Maori实例,将该Map实例里面的Key-value转化为application中的键值对
    //        void setSession(Map Seesion):直接传入一个Map实例,将该Map实例的键值对转化为Session的键值对
            
            ActionContext ctx = ActionContext.getContext(); //静态方法获取实例
    //        通过ActionContext访问application范围的属性值
            Integer counter = (Integer) ctx.getApplication().get("counter");
            if (counter == null){
                counter = 1;
            }else{
                counter += 1;
            }
    //        通过ActionContext设置application范围的属性
            ctx.getApplication().put("counter", counter);
            
    //        通过ActionContext设置application范围的属性
            ctx.getSession().put("username", user.getUsername()); // session范围
            ctx.put("password", user.getPassword()); // requset范围
            return SUCCESS;
        }
        
        @Override
        public User getModel() {
            // TODO Auto-generated method stub
            return user;
        }
        
    }

    显示的JSP:

          <h1>这是第${applicationScope.counter } 次访问</h1>
        Username:<strong>${sessionScope.username }</strong>
        Password:<strong>${requestScope.password }</strong>
    • Action直接访问ServletAPI

    虽然Struts2提供了ActionContext来访问ServletAPI,但这种方式不是直接获得ServletAPI的实例。为了在Action中直接访问ServletAPI,Struts2还提供了如下几个接口:

    1. ServletRequestAware:实现该接口的Action可以直接访问用户请求的HttpServletRequest实例
    2. ServletResponseAware:实现该接口的Action可以直接访问服务器响应的HttpServletResponse实例。
    3. ServletContextAware:实现该接口的Action可以直接访问Web应用的ServletContext实例。

     这里在刚刚的代码的基础上,通过response添加一个Cookie。

    package com.action;
    
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.struts2.interceptor.ServletResponseAware;
    
    import com.opensymphony.xwork2.ActionContext;
    import com.opensymphony.xwork2.ActionSupport;
    import com.opensymphony.xwork2.ModelDriven;
    import com.pojo.User;
    
    public class Login extends ActionSupport implements ModelDriven<User>,ServletResponseAware{
        private User user = new User();
        private HttpServletResponse response;
        @Override
        public String execute() throws Exception {
    //        通过Struts2提供的ActionContext类,访问ServletAPI
    //        Object get(Object key):此方法类似调用HttpServletRequest的getAttrbute(String name)
    //        Map getApplication():返回一个Map对象,该对象模拟了该应用的ServletContext实例
    //        static ActionContext getContext():静态方法,返回系统的actionContext实例
    //        Map getParameters():获取所有的请求参数。类似于调用HttpServletRequest对象的getParameterMap()方法
    //        Map getSession():返回一个Map对象,该Map对象模拟了HttpSession实例
    //        void setApplication(Map application):直接传入一个Maori实例,将该Map实例里面的Key-value转化为application中的键值对
    //        void setSession(Map Seesion):直接传入一个Map实例,将该Map实例的键值对转化为Session的键值对
            
            ActionContext ctx = ActionContext.getContext(); //静态方法获取实例
    //        通过ActionContext访问application范围的属性值
            Integer counter = (Integer) ctx.getApplication().get("counter");
            if (counter == null){
                counter = 1;
            }else{
                counter += 1;
            }
    //        通过ActionContext设置application范围的属性
            ctx.getApplication().put("counter", counter);
            
    //        通过ActionContext设置application范围的属性
            ctx.getSession().put("username", user.getUsername()); // session范围
            ctx.put("password", user.getPassword()); // requset范围
         Cookie c = new Cookie("user",user.getUsername());
            c.setMaxAge(60*60);
            response.addCookie(c);  // 用ServletAPI 添加一个Cookie
    return SUCCESS; } @Override public User getModel() { // TODO Auto-generated method stub return user; } @Override

       public void setServletResponse(HttpServletResponse response) {
            // TODO Auto-generated method stub
            this.response = response;
     } }
    • 使用ServletActionContext访问ServletAPI

    Struts2 提供了一个工具类,包含了几个静态的方法。

    1. static PageContext getPageContext() 取得Web应用的PageContext对象。
    2. static HttpServletRequest getRequest():取得Web应用的HttpServletRequest对象
    3. static HttpServletResponse getResponse():取得Web应用的HttpServletResponse对象
    4. static HttpServletContext getServletContext():取得Web应用的ServletContext对象

    借助ServletActionContext工具类的帮助,我们也能在Action中访问ServletAPI,并且可以避免Action类实现xxAware接口--虽然如此,但Action依然和ServletAPI直接耦合,不利于高层次的解耦。

    // 使用 ServletActionContext 增加一个Cookie
    ServletActionContext.getResponse().addCookie(c);
  • 相关阅读:
    【Hibernate框架】对象的三种持久化状态
    【Mybatis架构】Mapper映射文件中的#{}与${}
    【Mybatis架构】 延迟加载
    IDEA快捷键+使用小技巧
    Aop_AspectJ实现
    Aop_实践篇之过滤器
    Aop_思想篇
    超简单的Springboot中的日志管理配置
    SpringMVC+MYBatis企业应用实战笔记
    Spring学习
  • 原文地址:https://www.cnblogs.com/to-red/p/11152405.html
Copyright © 2011-2022 走看看