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

}
相关推荐
starzy19906 小时前
深入理解Scala隐式类:扩展方法机制
开发语言·人工智能·scala
Pniubi6 小时前
怎么排查慢SQL,怎么解决?
java·数据库·sql
M--Y6 小时前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
薛之谦_7 小时前
Java 全栈知识体系:从 IDEA 高效开发到 JVM、并发与 Stream 实战
java·jvm·intellij-idea
吴可可1237 小时前
WScript Shell操作注册表详解
开发语言
纪念 2298 小时前
C++ 算法基础 (差分)
开发语言·c++·算法
文丑颜不良啊11 小时前
LeetCode2761~2780题目解析
java·leetcode
IT枫斗者枫哥11 小时前
子线程断言失败,JUnit 为什么还显示通过?
java·后端
码农小河6612 小时前
基于PHP的电商后台蜜罐系统
开发语言·php
starzy199013 小时前
深入理解Scala柯里化函数:函数链式变换
开发语言·scala