Spring中HttpRequest获取的几种方式

阅读更多
1.Controller中加参数
@Controller
public class TestController {
    @RequestMapping("/test")
    public void test(HttpServletRequest request) throws InterruptedException {

    }
}


2.自动注入
@Controller
public class TestController{
 
    @Autowired
    private HttpServletRequest request; //自动注入request
 
    @RequestMapping("/test")
    public void test() throws InterruptedException{

    }
}


3.父类中自动注入
public class BaseController {
    @Autowired
    protected HttpServletRequest request;     
}

@Controller
public class TestController extends BaseController {
 
    @RequestMapping("/test")
    public void test() throws InterruptedException {
      
    }
}
 

4.上下文中获取
@Controller
public class TestController {
    @RequestMapping("/test")
    public void test() throws InterruptedException {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
    
    }
}

5.@ModelAttribute(线程不安全)
@Controller
public class TestController {
    private HttpServletRequest request;
    @ModelAttribute
    public void bindRequest(HttpServletRequest request) {
        this.request = request;
    }
    @RequestMapping("/test")
    public void test() throws InterruptedException {
     
    }
}

你可能感兴趣的:(java)