I am a newbie on Spring framework and maybe this is an easy question.
I have a link as follows and attempt Spring controller handles the value"201610061023" of this link.However,my code did not work.
I know this value can be attached as a parameter or pathvariable in path but I just curious can I pass this value implicitly?
Thank you very much.
201610061023
#RequestMapping(value = "/Order")
public String requestHandlingMethod(#ModelAttribute("test") String name, HttpServletRequest request) {
return "nextpage";
}
Spring will not handle the title of the link simply because the title of the link will not be sent by the browser. To send it you can either:
add the value as parameter: 201610061023
add the value as path variable: 201610061023
add a JavaScript that will copy the title onClick into the href or send the generated URL with document.location. This can be automated, but it's pretty uncommon.
Your a-tag is wrong, you need to submit the id, there is no implicit way to submit the link-text (except a lot of java script code)!
201610061023
#RequestMapping(value = "/Order/{orderId}")
public String requestHandlingMethod(#PathVariable("orderId") long orderId, #ModelAttribute("test") String name, HttpServletRequest request) {
return "nextpage";
}
or
201610061023
#RequestMapping(value = "/Order")
public String requestHandlingMethod(#RequestParam("orderId") long orderId, #ModelAttribute("test") String name, HttpServletRequest request) {
return "nextpage";
}
See #RequestParam vs #PathVariable for the difference between this two approaches
Related
I am using spring to build a REST api with PageAble, to get numberofPages,itens...
first, i did a mapping like this
public ResponseEntity<Data> findByName(#PathVariable(value="name",required=true) String name, #RequestParam(value="page", defaultValue="0") Integer page, #RequestParam(value="qtd", defaultValue="10") Integer linesPerPage, #RequestParam(value="sort", defaultValue="nome") String sort, #RequestParam(value="direction", defaultValue="ASC") String direction)
So in my url i get for example "url?name=erick&direction=asc" but i need to change to "url?name=erick!asc"
How can i change it?
You can do this. Look at page 3 of https://www.ietf.org/rfc/rfc1738.txt
In you case,you should use #RequestParam("name") instead of #PathVariable.Then the request url will be like "url?name=erick&direction=asc"
Spring has three kinds of Annotation.
#PathVariable
This annotation means the variable is on the url.For example:
#RequestMapping("/{id}")
public void pathVariable(#PathVariable("id") Long id){}
The variable was put between the brace at the url.
#RequestParam
This annotation means the variable is part of the quest param,the request url looks like
stackoverflow.com?name=hhhh
For example:
#RequestMapping("/")
public void requestParam(#RequestParam("id")Long id){}
#RequestBody
This annotation means you will receive some data from request body.And some kind of converter,like jackson,will convert it into a properly object.For example:
#PostMapping("/")
public void requestBody(#RequestBody Example example){}
I have a Spring controller that as return a redirection to another controller.
First looks like this
#RequestMapping(value = "/some-url", method =
{ RequestMethod.POST, RequestMethod.GET })
public String test(final Model model)
{
...
return "redirect:http://someurl/checkout/response";
}
The second is hooking the call of the first controller so it looks like this:
#RequestMapping("/**/response")
public String handleResponse(#RequestParam final MultiValueMap<String, String> params, #Valid #ModelAttribute final Cyber cyber,
final BindingResult bindingResult, final Model model, final HttpSession session, final HttpServletRequest request) throws CMSItemNotFoundException...
I am wondering how to pass the '#RequestedParam params' and the Cyber object from the first controller to the second.
If you additionally want these attributes to be erased automatically from the session after they where consumed, you can alternatively use FlashAttributes. For this you have to declare a RedirectAttributes parameter in method handleResponse and call addFlashAttribute on it. For example addFlashAttribute("cyber", cyber). Those will be available as model attributes in the targeted controller and will be gone out of the session automatically.
You can use #SessionAttributes and send the model to another content.
For more click here
Hi thank you guys I found a solution googleing your suggestion in this link :
http://www.concretepage.com/spring/spring-mvc/spring-mvc-redirectview-example-add-fetch-flash-attributes-redirectattributes-model-requestcontextutils
This is exactly my case.
Can you give me a brief explanation and a sample in using #PathVariable in spring mvc? Please include on how you type the url?
I'm struggling in getting the right url to show the jsp page. Thanks.
suppose you want to write a url to fetch some order, you can say
www.mydomain.com/order/123
where 123 is orderId.
So now the url you will use in spring mvc controller would look like
/order/{orderId}
Now order id can be declared a path variable
#RequestMapping(value = " /order/{orderId}", method=RequestMethod.GET)
public String getOrder(#PathVariable String orderId){
//fetch order
}
if you use url www.mydomain.com/order/123, then orderId variable will be populated by value 123 by spring
Also note that PathVariable differs from requestParam as pathVariable is part of URL.
The same url using request param would look like www.mydomain.com/order?orderId=123
API DOC
Spring Official Reference
Have a look at the below code snippet.
#RequestMapping(value="/Add/{type}")
public ModelAndView addForm(#PathVariable String type) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("addContent");
modelAndView.addObject("typelist", contentPropertyDAO.getType() );
modelAndView.addObject("property", contentPropertyDAO.get(type,0) );
return modelAndView;
}
Hope it helps in constructing your code.
If you have url with path variables, example www.myexampl.com/item/12/update where 12 is the id and create is the variable you want to use for specifying your execution for instance in using a single form to do an update and create, you do this in your controller.
#PostMapping(value = "/item/{id}/{method}")
public String getForm(#PathVariable("id") String itemId ,
#PathVariable("method") String methodCall , Model model){
if(methodCall.equals("create")){
//logic
}
if(methodCall.equals("update")){
//logic
}
return "path to your form";
}
#PathVariable used to fetch the value from URL
for example: To get some question
www.stackoverflow.com/questions/19803731
Here some question id is passed as a parameter in URL
Now to fetch this value in controller all you have to do is just to pass #PathVariable in the method parameter
#RequestMapping(value = " /questions/{questionId}", method=RequestMethod.GET)
public String getQuestion(#PathVariable String questionId){
//return question details
}
Annotation which indicates that a method parameter should be bound to a URI template variable. Supported for RequestMapping annotated handler methods.
#RequestMapping(value = "/download/{documentId}", method = RequestMethod.GET)
public ModelAndView download(#PathVariable int documentId) {
ModelAndView mav = new ModelAndView();
Document document = documentService.fileDownload(documentId);
mav.addObject("downloadDocument", document);
mav.setViewName("download");
return mav;
}
Let us assume you hit a url as www.example.com/test/111 .
Now you have to retrieve value 111 (which is dynamic) to your controller method .At time you ll be using #PathVariable as follows :
#RequestMapping(value = " /test/{testvalue}", method=RequestMethod.GET)
public void test(#PathVariable String testvalue){
//you can use test value here
}
SO the variable value is retrieved from the url
It is one of the annotation used to map/handle dynamic URIs. You can even specify a regular expression for URI dynamic parameter to accept only specific type of input.
For example, if the URL to retrieve a book using a unique number would be:
URL:http://localhost:8080/book/9783827319333
The number denoted at the last of the URL can be fetched using #PathVariable as shown:
#RequestMapping(value="/book/{ISBN}", method= RequestMethod.GET)
public String showBookDetails(#PathVariable("ISBN") String id,
Model model){
model.addAttribute("ISBN", id);
return "bookDetails";
}
In short it is just another was to extract data from HTTP requests in Spring.
have a look at the below code snippet.
#RequestMapping(value = "edit.htm", method = RequestMethod.GET)
public ModelAndView edit(#RequestParam("id") String id) throws Exception {
ModelMap modelMap = new ModelMap();
modelMap.addAttribute("user", userinfoDao.findById(id));
return new ModelAndView("edit", modelMap);
}
If you want the complete project to see how it works then download it from below link:-
UserInfo Project on GitLab
Is there a way to get the whole query string without it being parsed? As in:
http://localhost:8080/spring-rest/ex/bars?id=100,150&name=abc,efg
I want to get everything following the ? as one string. Yes I will parse it later, but this allows my controller and all follow-on code to be more generic.
So far I've tried using #PathParam, #RequestParam as well as #Context UriInfo with the results following. But I can't seem to get the whole string. This is what I want:
id=100,150&name=abc,efg
Using curl #PathParam using
http://localhost:8080/spring-rest/ex/bars/id=100,150&name=abc,efg
produces id=100,150
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/spring-rest/ex/qstring/{qString}")
public String getStuffAsParam ( #PathParam("qstring") String qString) {
...
}
#RequestParam using
http://localhost:8080/spring-rest/ex/bars?id=100,150&name=abc,efg
gives name not recognized.
http://localhost:8080/spring-rest/ex/bars?id=100,150;name=abc,efg
produces exception.
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/spring-rest/ex/qstring")
public String getStuffAsMapping (#RequestParam (value ="qstring", required = false) String[] qString) {
...
}
EDIT - THE APPROACH BELOW IS WHAT I'D LIKE TO FOCUS ON.
This works almost. It doesn't give me the full query string in the MultivaluedMap. It is only giving me the first string up to the &. I've tried using other characters as the delimiter and still doesn't work. I need to get this string in its undecoded state.
#Context with UriInfo using
http://localhost:8080/spring-rest/ex/bars?id=100,150&name=abc,efg
gives value for queryParams id=[100,150]. Again the name= part was truncated.
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/spring-rest/ex/qstring")
public String getStuffAsMapping (#Context UriInfo query) {
MultivaluedMap<String, String> queryParams = query.getQueryParameters();
...
}
I'm thinking the query string is being decoded which I don't really want. How do I get the whole string?
Any help is greatly appreciated.
You should have a look at the list of supported parameters:
https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-methods
In your case, you can add a HttpServletRequest parameter and call getQueryString():
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/spring-rest/ex/qstring")
public String getStuffAsMapping(HttpServletRequest request) {
String query = request.getQueryString();
...
}
Another way is to use the #Context UriInfo, then call UriInfo.getRequestUri() followed by URI.getQuery():
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/spring-rest/ex/qstring")
public String getStuffAsMapping(#Context UriInfo uriInfo) {
String query = uriInfo.getRequestUri().getQuery();
...
}
I would go with
http://localhost:8080/spring-rest/ex/bars?id=100,150;name=abc,efg
and have this RequestMapping
#RequestMapping(value="/spring-rest/ex/bars")
public String getStuffAsParam(#RequestParam("id")String id, #RequestParam("name")String name)
If you need access to the raw query you need to get it from the request object. Refer to this old question to get access to it. Even though the answer is not accepted it is a well researched response.
Spring 3 MVC accessing HttpRequest from controller
The following code snippet should give the query string once you get access to HttpServletRequest
httpservletrequest.getQueryString()
After I posted this I see #Andreas has posted a similar answer. Accept his answer if the solution helps you.
The question sounds weird, I'm playing around with Spring MVC and am trying to move between two pages and basically I'm creating a JSP page using Spring Form JSTL's so it just uses a POST, and I use a controller to move from one page to the next. But Models are lost from page to page, and I'd like to hide the actual variable so QueryStrings are out of the question(as
far as I know). I know I can use a InternalResourceView, but only allows me to use a model.
I want to transfer a variable that will be exclusive to that page, what's the best way without a model or using QueryStrings?
I was planning on using SessionAttribute to easily define them, but was wondering, how do you remove a SessionAttribute created variable? I tried HttpSession.removeAttribute and it didn't seem to work.
You can also use SessionStatus.setComplete() like this:
#RequestMapping(method = RequestMethod.GET, value="/clear")
public ModelAndView clear(SessionStatus status, ModelMap model, HttpServletRequest request) {
model.clear();
status.setComplete();
return new ModelAndView("somePage");
}
or DefaultSessionAttributeStore.cleanUpAttribute like this:
#RequestMapping(method = RequestMethod.GET, value="/clear")
public ModelAndView clear(DefaultSessionAttributeStore status, WebRequest request, ModelMap model) {
model.remove("mySessionVar");
status.cleanupAttribute(request, "mySessionVar");
return new ModelAndView("somePage");
}
I use it like this on one of my forms that has mulitple sessionAttributes and I want to remove only one of them.
Yes... HttpSession.removeAttribute
You can use the removeAttribute method from the HttpSession class.
you can use WebRequest.removeAttribute(String name, int scope) that works with Spring #SessionAttributes. Quote from #SessionAttributes javadoc - "Alternatively, consider using the attribute management capabilities of the generic {#link org.springframework.web.context.request.WebRequest} interface."
Also look at my example.
#Controller
#SessionAttributes({"sessionAttr"})
public class MyController {
#ModelAttribute("sessionAttr")
public Object defaultSessionAttr() {
return new Object();
}
#RequestMapping(value = "...", method = RequestMethod.GET)
public String removeSessionAttr(WebRequest request, Model model) {
request.removeAttribute("sessionAttr", WebRequest.SCOPE_SESSION);
model.addAttribute("sessionAttr", defaultSessionAttr());
return "myView";
}
}