在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";
    }

}
相关推荐
编程星空34 分钟前
css主题色修改后会多出一个css吗?css怎么定义变量?
开发语言·后端·rust
软件黑马王子42 分钟前
Unity游戏制作中的C#基础(6)方法和类的知识点深度剖析
开发语言·游戏·unity·c#
Logintern091 小时前
使用VS Code进行Python编程的一些快捷方式
开发语言·python
Multiple-ji1 小时前
想学python进来看看把
开发语言·python
极客先躯1 小时前
说说高级java每日一道面试题-2025年2月13日-数据库篇-请说说 MySQL 数据库的锁 ?
java·数据库·mysql·数据库的锁·模式分·粒度分·属性分
程序员侠客行1 小时前
Spring事务原理 二
java·后端·spring
一个小白11 小时前
C++——list模拟实现
开发语言·c++
bug总结1 小时前
新学一个JavaScript 的 classList API
开发语言·javascript·ecmascript
小猫猫猫◍˃ᵕ˂◍1 小时前
备忘录模式:快速恢复原始数据
android·java·备忘录模式
Nicole Potter2 小时前
请说明C#中的List是如何扩容的?
开发语言·面试·c#