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

}
相关推荐
方也_arkling1 天前
【Java-Day08】static / final / 枚举
java·开发语言
橙淮1 天前
Spring Bean作用域与生命周期全解析
java·spring
风吹夏回1 天前
Python 全局异常处理:从“满屏 try-except”到优雅兜底
开发语言·python
Chengbei111 天前
一站式源码安全检测工具、云安全 / APP / 小程序源码敏感信息递归多层目录扫描AK、JWT、手机号、身份证等敏感信息
java·开发语言·安全·web安全·网络安全·系统安全·安全架构
llz_1121 天前
web-第一次课后作业
java·开发语言·idea
小熊Coding1 天前
Python爬取当当网二手图书项目实战!
开发语言·爬虫·python·beautifulsoup·requests·二手图书
秋91 天前
Java项目运行5天左右自动宕机:系统性定位与解决方案
java·开发语言·python
小江的记录本1 天前
【JVM虚拟机】垃圾回收GC:垃圾收集器:CMS:核心原理、回收流程、优缺点、废弃原因(附《思维导图》+《面试高频考点清单》)
java·jvm·后端·python·spring·面试·maven
xiaoshuaishuai81 天前
C# 内存管理与资源泄漏
开发语言·c#
DIY源码阁1 天前
JavaSwing学生成绩管理系统 - MySQL版
java·数据库·mysql·eclipse