ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
HttpServletResponse response = attributes.getResponse();
try {
response.getWriter().write("hello");
} catch (IOException e) {
e.printStackTrace();
}
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String value = request.getHeader(name);
System.out.println(name + "===========" + value);
}

使用springMVC的时候,有些时候会需要获取请求或者响应对象,例如在身份验证的时候,需要获取请求头中的token,在做登录系统的时候需要使用response对象向客户端添加cookie,一个有效的做法是在controller的方法中添加对应参数如下所示:

@RestController
public class Test2Contrller {
@RequestMapping("/test")
public void test(HttpServletRequest req, HttpServletResponse res) {
    // todo
   }
}

这样做有一个问题,就是如果这个系统是作为接口并希望被远程调用的,那么额外的参数的存在便会破坏原本的接口定义,造成麻烦,下面介绍两种不需要在方法中增加额外参数就能获取request和response的方式

第一种方式:通过RequestContextHolder类的方法获取requestAttributes,再从中获取请求和响应对象;

@RestController
public class Test2Contrller {
@RequestMapping("/testreq")
public void test() {
// 获得request对象,response对象
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
HttpServletResponse response = attributes.getResponse();
try {
response.getWriter().write("hello");
} catch (IOException e) {
e.printStackTrace();
}
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String value = request.getHeader(name);
System.out.println(name + "===========" + value);
} }
}

  

第二种方式:可以将请求和响应对象抽取出来放在一个超类中,需要使用这两个对象的controller继承这个类,直接使用即可,代码如下:

超类:

public class BaseController {
  // 这些对象何以直接被子类使用
protected HttpServletRequest request;
protected HttpServletResponse response;
protected HttpSession session; @ModelAttribute
public void setReqAndRes(HttpServletRequest req, HttpServletResponse res) {
this.request = req;
this.response = res;
this.session = req.getSession();
}
}

  

子类:

@RestController
public class Test3Contrller extends BaseController{
@RequestMapping("/testreq2")
public void test() {
try {
response.getWriter().write("hello");
} catch (IOException e) {
e.printStackTrace();
}
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String value = request.getHeader(name);
System.out.println(name + "===========" + value);
} }
}

  

可以看到第二种方式代码简洁很多,如果对请求或者响应对象有大量的使用需求,例如需要从传过来的请求头中的token获取用户信息,动态的返回结果时,建议使用第二种方式;

在springMVC的controller中获取request,response对象的一个方法的更多相关文章

  1. spring mvc controller中获取request head内容

    spring mvc controller中获取request head内容: @RequestMapping("/{mlid}/{ptn}/{name}") public Str ...

  2. SpringMVC Controller中注入Request成员域和在方法中定义中HttpServletRequest有啥区别

    先说结论,在Controller中注入Request是线程安全的. 以下是解释: 我们先来看看这两者有什么不同 在controller注入成员变量request 可以看到注入的是一个代理对象 写在方法 ...

  3. 在Struts2的Action中获得request response session几种方法

    转载自~ 在Struts2中,从Action中取得request,session的对象进行应用是开发中的必需步骤,那么如何从Action中取得这些对象呢?Struts2为我们提供了四种方式.分别为se ...

  4. Action类中获取request等对象的方法

    struts2中的action类中,SevletActionContext可以获取

  5. js中获取当前url参数值的一个方法

    var $_GET = (function(){             var url = window.document.location.href.toString();//获得当前url地址并 ...

  6. springMVC中获取request和response对象的几种方式(RequestContextHolder)

    springMVC中获取request和response对象的几种方式 1.最简单方式:参数 2.加入监听器,然后在代码里面获取 原文链接:https://blog.csdn.net/weixin_4 ...

  7. SpringMvc中获取Request

    Controller中加参数 @Controller public class TestController { @RequestMapping("/test") public v ...

  8. java中获取request与response对象的方法

    Java 获取Request,Response对象方法   第一种.参数 @RequestMapping("/test") @ResponseBody public void sa ...

  9. Spring中获取request的几种方法,及其线程安全性分析

    前言 本文将介绍在Spring MVC开发的web系统中,获取request对象的几种方法,并讨论其线程安全性. 原创不易,如果觉得文章对你有帮助,欢迎点赞.评论.文章有疏漏之处,欢迎批评指正. 欢迎 ...

随机推荐

  1. mysql帐号,权限管理

    -> use mysql; //选择数据库 -> select host,user,password from user; //查询已有用户 -> insert into user ...

  2. spring boot读取Excel

    首先引入相关依赖 <!--解析office相关文件--> <dependency> <groupId>org.apache.poi</groupId> ...

  3. 什么是Java内存模型

    转载 : https://www.jianshu.com/p/bf158fbb2432 在知识星球中,有个小伙伴提了一个问题: 有一个关于JVM名词定义的问题,说”JVM内存模型“,有人会说是关于JV ...

  4. SpringMVC(中)

    一.传值方式 (1)Map Controller @Controller public class MyController { @RequestMapping("first") ...

  5. centos安装redis 5.0版本的集群

    我在本地VM-Centos里安装5.0.5时安装遇到了些问题,参考了Blog:https://www.cnblogs.com/shawhe/p/9548620.html 顺利安装完成. 安装redis ...

  6. 001 okhttp3的POST使用

    继续使用上面的项目 1.被调用的项目 package com.jun.web2forokhttp.okhttp; import com.jun.web2forokhttp.bean.HttpDomai ...

  7. understand-show-slave-status-g

    https://dba.stackexchange.com/questions/22623/mysql-exec-master-log-pos-value-greater-than-read-mast ...

  8. [LeetCode] 290. Word Pattern 单词模式

    Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

  9. redis主从分节

    概述 在现有企业中80%公司大部分使用的是redis单机服务,在实际的场景当中单一节点的redis容易面临风险. 面临问题 机器故障.我们部署到一台 Redis 服务器,当发生机器故障时,需要迁移到另 ...

  10. spring security的BCryptPasswordEncoder加密和对密码验证的原理

    目录 BCryptPasswordEncoder加密和对密码验证的原理 一.加密算法和hash算法的区别 二.源码解析 1. encode方法 2. BCrypt.hashpw方法 3. matche ...