从请求到spring控制器方法

时间:2016-04-25 10:41:38

标签: java spring inject

我有一些spring @RestControllers方法,我希望将每个请求附带的值作为请求属性(包含用户)注入:

@RestController
@RequestMapping("/api/jobs")
public class JobsController {
     // Option 1 get user from request attribute as prop somehow
     private String userId = "user1";

    // Option 2 inject into method using aspect or something else
    @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<List<Jobs>> getJobs() throws ResourceNotFoundException {
       // currentUser is injected 
       this.getJobs(currentUser);
}

我知道我可以这样做:

@RestController
@RequestMapping("/api/jobs")
public class JobsController {

    @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<List<Jobs>> getJobs(HttpServletRequest request) throws ResourceNotFoundException { 
       String currentUser = null;
       if (request.getAttribute("subject") != null) {
           currentUser = request.getAttribute("subject").toString();
       }
       this.getJobs(currentUser);
}

但这需要我在我的程序中的每个方法中添加此代码,在我看来,这是一个非常糟糕的做法。
有没有办法达到我想要的目的?

如果答案确实需要方面,那么代码示例将非常受欢迎,因为我只阅读了它,但从未真正对方面做过什么。

更新
我建议的代码可以使用这个简化:

@RestController
@RequestMapping("/api/jobs")
public class JobsController {

    @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<List<Jobs>> getJobs(@Value("#{request.getAttribute('subject')}" String currentUser) throws ResourceNotFoundException { 
       this.getJobs(currentUser);
}

但仍需要我在每个方法中添加该参数。 这个参数能以某种方式注入每个方法吗?

3 个答案:

答案 0 :(得分:2)

您可以使用Filter填充存储该属性的ThreadLocal<String>变量:

public class MyFilter implements Filter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {}

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    ContextHolder.setSubject(request.getAttribute('subject'));
    chain.doFilter(request, response);
  }

  @Override
  public void destroy() {
    ContextHolder.removeSubject();
  }
}


public class ContextHolder {

  private static final ThreadLocal<String> SUBJECT = new ThreadLocal<String>() {
    @Override
    protected String initialValue() {
      return "empty";
    }
  };

  public static void setSubject(String subject) {
    SUBJECT.set(subject);
  }

  public static String getSubject() {
    return SUBJECT.get();
  }

  public static void removeSubject() {
    SUBJECT.remove();
  }
}

过滤器将配置为拦截所有请求并填充SUBJECT变量。通过使用ThreadLocal,您可以确保每个线程都拥有自己的subject值。您现在可以通过调用ContextHolder.getSubject()

在应用程序的任何位置获取该值
  @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<List<Jobs>> getJobs(HttpServletRequest request) throws ResourceNotFoundException { 
    this.getJobs(ContextHolder.getSubject());
  }

您还必须在web.xml文件中注册Filter

<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>com.MyFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

如果您有多个属性,则可以使用ThreadLocal<Map<String, String>>变量。

答案 1 :(得分:0)

如果您真的想了解属性,那么您应该查看spring的@RequestParam注释。你会这样使用它:

@RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Jobs>> getJobs(@RequestParam("subject") String currentUser) throws ResourceNotFoundException { 
   this.getJobs(currentUser);
}

答案 2 :(得分:0)

只需在其余 contorller

中添加@ResuestAttribute即可
@RestController
@RequestMapping(path="/yourpath")

@RequestMapping(method = RequestMethod.GET)
    public ResponseEntity getAll(
            @RequestAttribute(value = "yourAttribute") Object 

yourAttribute ......