How do I extract client data from the httpheaders? - spring

I have a login post request.
#RequestMapping(value = EWPRestContants.DO_LOGIN, method = RequestMethod.POST, consumes=MediaType.APPLICATION_XML_VALUE,produces=MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> doLogin(#RequestBody Loginrequest logReq,#RequestHeader HttpHeaders headers, HttpServletRequest request, HttpServletResponse httpResponse) throws Exception {
//........
}
I want to extract data from the header. Is there an API to do so?
Suppose my header contains customer msIsdn number and name. How do I fetch those details. getFirst() is used to get the user-agent details or the start line only.
This is the answer.
String id= headers.getFirst("ID");

like
#RequestHeader(value="User-Agent", defaultValue="foo") String userAgent
#RequestMapping(value = EWPRestContants.DO_LOGIN, method = RequestMethod.POST, consumes=MediaType.APPLICATION_XML_VALUE,produces=MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> doLogin(#RequestBody Loginrequest logReq,#RequestHeader(value="User-Agent", defaultValue="foo") String userAgent,#RequestHeader(value="Accept-Language") String acceptLanguage, HttpServletRequest request, HttpServletResponse httpResponse) throws Exception {
//........
}
or from
#RequestMapping(value = EWPRestContants.DO_LOGIN, method = RequestMethod.POST, consumes=MediaType.APPLICATION_XML_VALUE,produces=MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<String> doLogin(#RequestBody Loginrequest logReq,#RequestHeader HttpHeaders headers, HttpServletRequest request, HttpServletResponse httpResponse) throws Exception {
String userAgent = headers.getFirst(HttpHeaders.USER_AGENT);
}

Related

Spring missing query parameters exception handling

I have this code:
#GetMapping(value = "/users/{id}")
#ResponseStatus(HttpStatus.OK)
public DtoUser getUserById( #PathParam("id") #PathVariable("id") #RequestParam Long id) {
return adminService.getUserById(id);
}
and this code:
#ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
#Override
public ResponseEntity<Object> handleHttpMessageNotReadable(
HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return error_with_my_info;
}
#Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(
MissingServletRequestParameterException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {{
return error_with_my_info;
}
...
}
The problem is that when I send a request WITHOUT a parameter, it is handleHttpMessageNotReadable that is called, not handleMissingServletRequestParameter.
Why is that?
Can other API endpoints affect this behaviour, like having a PUT request handler with the same endpoint?
How can I make it so that handleMissingServletRequestParameter?
Improvised :
#GetMapping(value = "/users")
#ResponseStatus(HttpStatus.OK)
public DtoUser getUserById( #RequestParam(value="id" , required=true)Long id) {
return adminService.getUserById(id);
}
localhost:8080?id=test
now if you dont pass id it will give you handleMissingServletRequestParameter.

Spring boot: How to set & read cookie

I am trying to set the cookie in the response after login & I want to read that cookie on every further rest api calls.. I tried the code like below but I am not getting the cookie value.. please help me.. thanks in advance..
#RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "text/plain")
public String setCookie(HttpServletRequest request, HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException, ServiceException
{
response.addCookie(new Cookie("token", generateToken()));
return "login success";
}
#RequestMapping(value = "/getResource", method = RequestMethod.POST, consumes = "text/plain")
public String getCookie(HttpServletRequest request, HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException, ServiceException
{
Cookie[] cookies = request.getCookies();
if (cookies != null) {
Arrays.stream(cookies)
.forEach(c -> System.out.println(c.getName() + "=" + c.getValue()));
}
return "resource list";
}
Set cookie:
Cookie cookie= new Cookie("userName", authentication.getName());
response.addCookie(cookie);
Use Cookie Value:
public String hello(Model model, HttpServletRequest request, HttpServletResponse response,#CookieValue("userName") String usernameCookie) {
console.log(usernameCookie);
}
hope this helps

How to check if PathVariable in the URI in Spring MVC's request mapping?

In my controller there is such code.
#RequestMapping(value = "/{scene}/{function}/**")
public void processProxyCall(#PathVariable("scene") final String scene, #PathVariable("function") final String function,
final HttpServletRequest request,final HttpServletResponse response) throws IOException {
...
}
In testing phase, where the possible values of {scene} is "sit" or "uat". And there are some additional logic to handle this variable in the phase.
So it's well fit for such URI "/sit/student/add". The scene is sit, and the function is student.
But in production there isn't any "sit" nor "uat" anymore , the URI in this case will be "/student/add". There is no need to handle the scene variable either.
The question is how to do some checking against the PathVariable "scene" in above code snippet. If production case the scene will be automatically mapped to "student" which is terribly wrong.
I was trying to add another RequestMapping as below to handle the production case, and remain the testing one no change. But got 404...
#RequestMapping(value = "/{function}/**")
public void processProxyCall(#PathVariable("function") final String function, final HttpServletRequest request,
final HttpServletResponse response) throws IOException {
}
#RequestMapping(value = {"/{scene}/{function}/**", "/{function}/**"})
public void processProxyCall(#PathVariable(value="scene", required=false) final String scene, #PathVariable("function") final String function,
final HttpServletRequest request,final HttpServletResponse response) throws IOException {
...
}
Define multiple mappings and make scene path variable required=false
UPDATE:
#RequestMapping(value = "/{scene}/{function}/**")
public void processProxyCall(#PathVariable(value="scene", required=false) final String scene, #PathVariable("function") final String function,
final HttpServletRequest request,final HttpServletResponse response) throws IOException {
...
}
#RequestMapping(value = "/{function}/**")
public void processProxyCallShort(#PathVariable(value="scene", required=false) final String scene, #PathVariable("function") final String function,
final HttpServletRequest request,final HttpServletResponse response) throws IOException {
processProxyCall(null, function, request, response);
}

HTTP redirect: 301 (permanent) vs. 302 (temporary) in Spring

I want to make a 301 redirect in Spring, So here the piece of code I use
#RequestMapping(value = { "/devices" } , method = RequestMethod.GET)
private String initGetForm(#ModelAttribute("searchForm") final SearchForm searchForm,
BindingResult result,
HttpServletRequest request,
HttpServletResponse response,
Model model, Locale locale) throws Exception {
String newUrl = "/devices/en";
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", newUrl);
response.setHeader("Connection", "close");
return "redirect:" + newUrl;
}
But checking the IE Developer Tools I got this Status 302 Moved Temporarily !
Spring is resetting your response headers when it handles the redirection since you are returning a logical view name with a special redirect prefix.If you want to manually set the headers handle the response yourself without using Spring view resolution. Change your code as follows
#RequestMapping(value = { "/devices" } , method = RequestMethod.GET)
private void initGetForm(#ModelAttribute("searchForm") final SearchForm searchForm,
BindingResult result,
HttpServletRequest request,
HttpServletResponse response,
Model model, Locale locale) throws Exception {
String newUrl = request.getContextPath() + "/devices/en";
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", newUrl);
response.setHeader("Connection", "close");
}
You can use RedirectView with TEMPORARY_REDIRECT status.
#RequestMapping(value = { "/devices" } , method = RequestMethod.GET)
private ModelAndView initGetForm(#ModelAttribute("searchForm") final SearchForm searchForm,
BindingResult result,
HttpServletRequest request,
HttpServletResponse response,
Model model, Locale locale) throws Exception {
....
RedirectView redirectView = new RedirectView(url);
redirectView.setStatusCode(HttpStatus.TEMPORARY_REDIRECT);
return new ModelAndView(redirectView);
}

Converting a responseEntity to httpServletResponse with spring

My controller method looks like this :
public void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
and I want to do this
ResponseEntity<String> responseEntity = restTemplate.postForEntity(testPrefix + "/login", map, String.class);
response = responseEntity;
or similar, basically make a restcall and return the HttpReponseEntity as the response n its enitirety
From updated comments I assume that you are wanting to return the result of the restTemplate.postForEntity() call from your Controller.
As shown by the Spring MVC documentation, ResponseEntity is a valid return type from a Controller method. So you can simply return the result of your restTemplate.postForEntity() call from the doLogin() method. As an example:
#Controller
public class MyController
{
#AutoWired
private RestTemplate restTemplate;
#RequestMapping("/yourPath")
public ResponseEntity<String> doLogin(HttpServletRequest request) throws IOException
{
return restTemplate.postForEntity(testPrefix + "/login", map, String.class);
}
}
Spring MVC will take care of marshalling the ResponseEntity into the HTML response using a HTTPMessageConverter.

Resources