行业知识
在SpringMVC的控制器中如何使用HttpServletRequest对象呢?
2026-11-14 04:13:00
来源:互联网转载
SpringMVC中使用HttpServletRequest对象的两种解决方法: 1.完全解耦方式,完全不依赖HttpServletRequest - 该方式只能用于存取数据,不能做其他操作(获得session,获得其他请求数据) - 使用方法,向方法中注入Model对象,该对象时一个Map集合,底层是request中的属性对象 - 如果要将Model对象中的某些属性添加到session作用域,则需要在类上使用@SessionAttributes({"属性名",...}) 2.非解耦方式,通过依赖注入的方式实现,由容器向控制器中注入HttpServletRequest等对象 - 该方法需要在控制器方法中声明要注入的对象 - 使用此方式就可以在控制器中直接使用HttpServlet对象 �index.php/tags-41973.html" >�下面为demo演示
()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"; }} ()