Issue
I have a service that requires to read a special http query parameter. Therefore I have to access the current HttpServletRequest
somehow. As I cannot hand the request down as a parameter, I have to inject or read it somehow.
There are two possibilities: either get the request from RequestContextHolder
, or directly inject HttpServletRequest
. What is correct? Or maybe there is even a 3rd option?
@Service
public class MyUserDetailsService implements UserDetailsService {
//TODO is that correct? scope?
@Autowired
private HttpServletRequest req;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
req.getParameter("myparam");
}
}
Is that threadsafe, as MyUserDetailsService
is obviously as singleton, and HttpServletRequest
is supposed to be @RequestScope
?
Solution
You can get HttpServletRequest
in this way if you don't want to use @Autowired
in the controller:
HttpServletRequest request =
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
Answered By - august0490
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)