-1

As i consume a lot of data in httpservletrequest header and set a lot of values in request attribute in service class, I'm not sure if this would cause thread safety issues, I looked over the web if autowiring httpservlet request would cause threadsafety issues and i got mixed opinion

Following are the places where i autowire httpservletrequest

@RestController
Public class UserController {
 
 @Autowire
 HttpServletRequest httpServletRequest;

 @Autowire
 IAMService iamservice;
 
 @PostMapping("/addUser")
 public String addUser(@RequestBody UserDto userdto){
          return iamservice.addUser(userdto);
 }
}

@Service
Public Class IAMService {

 @Autowire
 HttpServletRequest httpServletRequest;

 @Autowire
 UserDao userDao;

 public String addUser(UserDto userdto){
    Long primaryKey = userDao.save(userdto,httpServletRequest.getHeader("loggedInUserId"));
    httpServletRequest.setAttribute("userPrimaryKey",primaryKey);
    return "User is added successfully";
 }
}

1 Answers1

1

We should not @Autowire HttpServletRequest. Consider modifying your code as below to have valid usage of request object and avoid thread-safety issues-

@RestController
Public class UserController {

 @Autowire
 IAMService iamservice;
 
 @PostMapping("/addUser")
 public String addUser(@RequestBody UserDto userdto, HttpServletRequest httpServletRequest){
          return iamservice.addUser(userdto, httpServletRequest);
 }
}

@Service
Public Class IAMService {

 @Autowire
 UserDao userDao;

 public String addUser(UserDto userdto, HttpServletRequest httpServletRequest){
    Long primaryKey = userDao.save(userdto,httpServletRequest.getHeader("loggedInUserId"));
    httpServletRequest.setAttribute("userPrimaryKey",primaryKey);
    return "User is added successfully";
 }
}
  • The problem is there are certain situation where i need the HttpServletRequest such as in the userdetailsservice of spring security, exception handler in controller advice. how do i achieve that? Also i heard spring uses proxy object to return current thread's servletrequest is that not true? – vishal sundararajan Nov 09 '20 at 16:20
  • seems this works https://stackoverflow.com/questions/36736861/spring-security-access-request-parameters-inside-userdetailsservice-implementa – vishal sundararajan Nov 09 '20 at 16:26