java - get cookie value by name in spring mvc - java

I'm working on a java spring mvc application. I have set a cookie in one of my controller's methods in this way:
#RequestMapping(value = {"/news"}, method = RequestMethod.GET)
public ModelAndView news(Locale locale, Model model, HttpServletResponse response, HttpServletRequest request) throws Exception {
...
response.setHeader("Set-Cookie", "test=value; Path=/");
...
modelAndView.setViewName("path/to/my/view");
return modelAndView;
}
This is working fine and I can see a cookie with name test and value "value" in my browser console. Now I want to get the cookie value by name in other method. How can I get value of test cookie?

The simplest way is using it in a controller with the #CookieValue annotation:
#RequestMapping("/hello")
public String hello(#CookieValue("foo") String fooCookie) {
// ...
}
Otherwise, you can get it from the servlet request using Spring org.springframework.web.util.WebUtils
WebUtils.getCookie(HttpServletRequest request, String cookieName)
By the way, the code pasted into the question could be refined a bit. Instead of using #setHeader(), this is much more elegant:
response.addCookie(new Cookie("test", "value"));

You can also use org.springframework.web.util.WebUtils.getCookie(HttpServletRequest, String).

private String getCookieValue(HttpServletRequest req, String cookieName) {
return Arrays.stream(req.getCookies())
.filter(c -> c.getName().equals(cookieName))
.findFirst()
.map(Cookie::getValue)
.orElse(null);
}

Spring MVC already gives you the HttpServletRequest object, it has a getCookies() method that returns Cookie[] so you can iterate on that.

private String extractCookie(HttpServletRequest req) {
for (Cookie c : req.getCookies()) {
if (c.getName().equals("myCookie"))
return c.getValue();
}
return null;
}

Cookie doesnt have method to get by value try this
Cookie cookie[]=request.getCookies();
Cookie cook;
String uname="",pass="";
if (cookie != null) {
for (int i = 0; i < cookie.length; i++) {
cook = cookie[i];
if(cook.getName().equalsIgnoreCase("loginPayrollUserName"))
uname=cook.getValue();
if(cook.getName().equalsIgnoreCase("loginPayrollPassword"))
pass=cook.getValue();
}
}

Related

Get request header in spring boot

How do I get the header and body of the current request from an application which called my Springboot application? I need to extract this information. Unfortunately this does not work. I tried to get the current request with this code sample (https://stackoverflow.com/a/26323545/5762515):
public static HttpServletRequest getCurrentHttpRequest(){
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
return request;
}
throw new IllegalArgumentException("Request must not be null!");
}
And then I tried to get the body
ContentCachingRequestWrapper requestWrapper = (ContentCachingRequestWrapper) currentRequest;
String requestBody = new String(requestWrapper.getContentAsByteArray());
Can someone tell me what im doing wrong?
Thanks in advance
#RestController
public class SampleController {
#PostMapping("/RestEndpoint")
public ResponseEntity<?> sampleEndpoint(#RequestHeader Map<String, String> headers,#RequestBody Map<String,String> body) {
//Do something with header / body
return null;
}
}
If the application's are communicating through a rest endpoint I believe this would be the simplest solution. In spring you can add RequestHeader and RequestBody annotations to method arguments to have them setup to be used.
Of course you can map RequestBody directly to some POJO instead of using a map but just as an example.
Let me know if this is what you were looking for !
#TryHard, You're using spring boot then following way is more preferable for you,
#RestController
public class SampleController {
#RequestMapping("/get-header-data")
public ResponseEntity<?> sampleEndpoint(HttpServletRequest request) {
// request object comes with various in-built methods use as per your requirement.
request.getHeader("<key>");
}
}
you can get header with your code but need apply some changes.
private String getRequest() throws Exception {
RequestAttributes attribs = RequestContextHolder.getRequestAttributes();
if (attribs != null) {
HttpServletRequest request = ((ServletRequestAttributes) attribs).getRequest();
return request ;
}
throw new IllegalArgumentException("Request must not be null!");
}
after you can extract header info from request. For example if you want get Accept-Encoding
String headerEncoding = getRequest().getHeader("Accept-Encoding");
obliviusly you don't use this approce if not necessary.
If you want exract the body NOT use this solution

How to retrieve value of parameters annotated by #RequestBody from a HttpServeletRequest object?

in a springcloud project
if a backend microservice has the following:
#RequestMapping("/test")
pubilc void test(#RequestBody MyPram myParam){
...
}
how can I retrive the "myParam" value in a zuul filter?
in other words, since I can have the following code segment in a zuul filter
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
how can I retrive the "myParam" value from a request?
i don't know in Spring Cloud but tried in springMVC (spring version 3) we can get the Request body HttpServeletRequest object or method.
#RequestMapping(value="/employee/{id}")
public #ResponseBody String demo(HttpServletRequest request, #PathVariable("id") Integer id) {
if (request.getMethod().equalsIgnoreCase("POST")) {
return "POST MEhod";
} else if (request.getMethod().equalsIgnoreCase("GET")) {
return "GET Method";
}
}
Its not exact what you are looking but it will give you hint to solve your problem

Using CookieParam annotation with Spring MVC Controller

I'm trying to use the javax.ws.rs.CookieParam annotation to grab a cookie from the HTTP request to a method on my controller.
#Override
public void cookieTest( #CookieParam("testToken") String testCookie, HttpServletRequest request ) {
Cookie[] cookies = request.getCookies();
for( Cookie cookie : cookies ) {
if( cookie.getName().equals( "testToken" ) ) {
System.out.println( "found testToken" );
}
}
}
However I get the following error:
Caused by: java.lang.IllegalStateException: No parameter name specified for argument of type [java.lang.String], and no parameter name information found in class file either.
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.getRequiredParameterName(HandlerMethodInvoker.java:729)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestParam(HandlerMethodInvoker.java:488)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:348)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
... 67 more
The controller does have an interface, but I added the CookieParam annotation in both places with the correct name. If I remove the testCookie parameter, I can iterate through the request.getCookies() and see that the cookie does exist. Is there a step I'm missing?
I'm using Spring 3 and Java 6.
You are using wrong annotation. Use #CookieValue instead https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/CookieValue.html
This is the declaration of one of my controller methods that makes use of a cookie :
#RequestMapping(value = {"/"}, method = RequestMethod.GET)
public String home(ModelMap model, HttpServletRequest request,
#CookieValue(value = "aCookie", defaultValue = "someRandomValue") String aValue)

Spring + Tiles. How to return 301 redirect (instead of 302) in Controller

I am using the code like:
#RequestMapping(value="/oldPath")
public String doProductOld(
#PathVariable(value = "oldProductId") Long oldProductId,
Model model
) throws Exception {
Product product = productDao.findByOldId(oldProductId);
return "redirect:" + product.getUrlNewPath();
}
All works fine but this redirect returns 302 response code instead of 301 which is needed for SEO. How to easily (without ModelAndView or Http response) update it to return 301 code?
PS. I found solutions when ModelAndView object return from controller but need solution for Tiles when tiles alias (String) is returned.
Try to add #ResponseStatus annotation for your method, see below an example:
#ResponseStatus(HttpStatus.MOVED_PERMANENTLY/*this is 301*/)
#RequestMapping(value="/oldPath")
public String doProductOld(...) throws Exception {
//...
return "redirect:path";
}
General idea is:
#RequestMapping(value="/oldPath")
public ModelAndView doProductOld(
#PathVariable(value = "oldProductId") Long oldProductId,
Model model
) throws Exception {
Product product = productDao.findByOldId(oldProductId);
RedirectView red = new RedirectView(product.getUrlNewPath(),true);
red.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
return new ModelAndView(red);
}
There is a newer, simpler way, add this before the return "redirect:"...:
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.MOVED_PERMANENTLY);
[sic] you have to set the attribute on the Request object.
Can be done in WebMvcConfigurer also:
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("oldpath","newpath").setStatusCode(HttpStatus.MOVED_PERMANENTLY);
}

How to change "pathInfo" of HttpServletRequest

I am afraid to ask a strange question but I want to change "pathInfo" of HttpServletRequest at a handler method of a Controller. Please take look at below.
I know I can get "pathInfo" by using getPathInfo(). However. I don't know how to set up the pathInfo. Is it possible ? Any help will be appreciated
#RequestMapping(value = "show1" method = RequestMethod.GET)
public String show1(Model model, HttpServletRequest request) {
// I want to set up "PathInfo" but this kind of methods are not provided
//request.setPathInfo("/show2");
// I thought that BeanUtils.copy may be available.. but no ideas.
// I have to call show2() with the same request object
return show2(model, request);
}
// I am not allowed to edit this method
private String show2(Model model, HttpServletRequest request) {
// I hope to display "http://localhost:8080/contextroot/show2"
System.out.println(request.getRequestURL());
return "complete";
}
You can't set these values.
The only option is to create a wrapper for your request, something like this:
return show2(model, new HttpServletRequestWrapper(request) {
public StringBuffer getRequestURL() {
return new StringBuffer(
super.getRequestURL().toString().replaceFirst("/show1$", "/show2"));
}
});
Path Info is set by the browser (client) when it requests a certain URL.

Categories

Resources