【问题标题】:How to get HttpServletRequest object inside a controller [duplicate]如何在控制器中获取 HttpServletRequest 对象[重复]
【发布时间】:2014-09-11 15:53:56
【问题描述】:
我写了一个控制器类和一个动作方法,比如
@Controller
public class Controller
{
@RequestParam("/test.htm")
public String action(Model model)
{
//Something
}
}
如何在action的方法体中获取HttpServletRequest对象?
【问题讨论】:
标签:
java
class
spring-mvc
【解决方案1】:
您可以通过在您的操作方法中传递引用来获取HttpServletRequest 的实例:
@Controller
public class Controller
{
@RequestParam("/test.htm")
public String action(Model model, HttpServletRequest request)
{
//Something
try {
request.getParameter("user_name"); //write in try-catch block
} catch(ServletException ex) {
}
}
}
【解决方案2】:
Spring MVC 很容易利用 HttpServletRequest 、 HttpServletResponse 和许多其他类进行处理:
直接在方法参数中添加 HttpServletRequest 如下:
@RequestParam("/test.htm")
public String action(Model model , HttpServletRequest request)
{
//Something
}