在SpringMVC的控制器中如何使用HttpServletRequest对象呢?

复制代码
SpringMVC中使用HttpServletRequest对象的两种解决方法:
 1.完全解耦方式,完全不依赖HttpServletRequest
     - 该方式只能用于存取数据,不能做其他操作(获得session,获得其他请求数据)
     - 使用方法,向方法中注入Model对象,该对象时一个Map集合,底层是request中的属性对象
     - 如果要将Model对象中的某些属性添加到session作用域,则需要在类上使用@SessionAttributes({"属性名",...})
 2.非解耦方式,通过依赖注入的方式实现,由容器向控制器中注入HttpServletRequest等对象
     - 该方法需要在控制器方法中声明要注入的对象
     - 使用此方式就可以在控制器中直接使用HttpServlet对象

下面为demo演示

java 复制代码
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@SessionAttributes({"name","upwd"})
public class userController {

    @RequestMapping("/demo")
    public String demo(){
        return "index.jsp";
    }

    @RequestMapping("/demo1")
    public String demo1(){
        return "redirect:index.jsp";      //重定向前面加redirect:
    }
    /**
     * 在SpringMVC的控制器中如何使用HttpServletRequest对象呢?
     * SpringMVC中使用HttpServletRequest对象的两种解决方法:
     *  1.完全解耦方式,完全不依赖HttpServletRequest
     *      - 该方式只能用于存取数据,不能做其他操作(获得session,获得其他请求数据)
     *      - 使用方法,向方法中注入Model对象,该对象时一个Map集合,底层是request中的属性对象
     *      - 如果要将Model对象中的某些属性添加到session作用域,则需要在类上使用@SessionAttributes({"属性名",...})
     *  2.非解耦方式,通过依赖注入的方式实现,由容器向控制器中注入HttpServletRequest等对象
     *      - 该方法需要在控制器方法中声明要注入的对象
     *      - 使用此方式就可以在控制器中直接使用HttpServlet对象
     * @return
     */
    @RequestMapping("/demo2")
    public String demo2(Model model){
        model.addAttribute("name","root");
        model.addAttribute("upwd","123456");
        return "index.jsp";
    }

    @RequestMapping("/demo3")
    public ModelAndView demo2(ModelAndView modelAndView){
        modelAndView.getModelMap().addAttribute("name","admin1");
        modelAndView.getModelMap().addAttribute("upwd","1234561");
        modelAndView.setViewName("index.jsp");
        return modelAndView;
    }

    @RequestMapping("/reqDemo2")
    public String reqDemo(HttpServletRequest request){
        request.setAttribute("name","hello");
        request.setAttribute("upwd","000000");
        return "index.jsp";
    }

}
相关推荐
克拉克盖博14 分钟前
chapter03_Bean的实例化与策略模式
java·spring·策略模式
Franklin17 分钟前
Python界面设计【QT-creator基础编程 - 01】如何让不同分辨率图像自动匹配graphicsView的窗口大小
开发语言·python·qt
DashVector25 分钟前
如何通过Java SDK分组检索Doc
java·数据库·面试
郝学胜-神的一滴30 分钟前
深入理解QFlags:Qt中的位标志管理工具
开发语言·c++·qt·程序人生
程序员清风44 分钟前
跳表的原理和时间复杂度,为什么还需要字典结构配合?
java·后端·面试
渣哥1 小时前
Kafka消息丢失的3种场景,生产环境千万要注意
java
渣哥1 小时前
ElasticSearch深度分页的致命缺陷,千万数据查询秒变蜗牛
java
Olrookie1 小时前
XXL-JOB GLUE模式动态数据源实践:Spring AOP + MyBatis 解耦多库查询
java·数据库·spring boot
柯南二号1 小时前
【Java后端】MyBatis-Plus 原理解析
java·开发语言·mybatis
又是努力搬砖的一年1 小时前
SpringBoot中,接口加解密
java·spring boot·后端