I am learning spring MVC and come across these methos in spring contrller MVC 3.1
ControllerClass(){
#RequestMapping(....)
public String show( Model uiModel) {
return ".....";
}
#RequestMapping(value = "/{id}", params = "form", method = RequestMethod.POST)
public String update(#Valid Contact contact, BindingResult bindingResult, Model uiModel,
HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes, Locale locale,
#RequestParam(value="file", required=false) Part file) {
if (bindingResult.hasErrors()) {
...........
return ".....";
}
parameters like BindingResult , Model ,
HttpServletRequest , RedirectAttributes , Locale ,
#RequestParam(value="file", required=false) Part are optional but I wonder where I can find these optional parameter and under which situation it can appear in method.
Parameter:
BindingResult - imagine you have an registration-form and you would pre validate the user input, then you can use the BindingResult.
Model - After the user is registered, he wants to edit his own profile he goes to a edit site, in this site you would show the data from the user. Here you can search for the user and add the user-object to the model and in the template you can read the values from the model-attribute.
HttpServletRequest provides request information.
#RequestParam(value="file", required=false) from Spring:
annotated parameters for access to specific Servlet request parameters. Parameter values are converted to the declared method argument type
Imagine you have a table of users and you would edit one of these, you select an entry and there you can send the userId as a requestparam.
There is a similar attribute, it's called #PathVariable the main difference, the #PathVariable is mandatory. The #RequestParam is optional respectively for this exist a "fallback/default value".
The #PathVariable is a part from the url:
#RequestMapping(value = "/{login}/edit", method = RequestMethod.GET)
public ModelAndView editUserByLogin(#PathVariable("login") final String login, final Principal principal) {}
The other two I have not used yet.
Related
I am trying to receive data from an URL with two parameters like this one:
http://localhost:80000/xxx/xxx/tickets/search?codprovincia=28&municipio=110000
No matter the approach, I am always getting a 400 error, but if I access the URL without the two parameters, the controller returns the view correctly (without the parameters, naturally)
This is the code of my controller:
#Controller
#RequestMapping(value = "/xxx" )
public class BuscadorIncidenciasController extends BaseControllerWeb {
#RequestMapping("tickets")
public String tickets(Model model, #RequestParam ("codprovincia") String codprovincia, #RequestParam ("municipio") String municipio, HttpServletRequest request) throws NoAjaxException {
//...
return CONST.JSP_VIEW;
}
...}
Extra info: if I use this URL:
http://localhost:9081/xxx/xxx/tickets/search/28/790000
And this code:
#Controller
#RequestMapping(value = "/xxx" )
public class BuscadorIncidenciasController extends BaseControllerWeb {
#RequestMapping(value = "buscar/{codprovincia}/{municipio}", method = RequestMethod.GET)
public String buscar(#PathVariable Integer codprovincia, #PathVariable Integer municipio ,Model model, HttpServletRequest request) throws NoAjaxException {
//...
return CONST.JSP_VIEW;
}
...}
It gets the parameters correctly. The problem is that I have to use the first URL. I have reviewed similar questions about similar issues, and I have implemented the solutions to those issues, but I get the 400 error regardless what I try (add value="xxx=, required=false, and other suggestions.)
For RequestParam, you need to explicitly add 'name' attribute
#RequestParam(name = "codprovincia"), #RequestParam (name = "municipio")
No need to for HttpServletRequest, unless you have reason
Also, in your 'tickets' method, RequestMapping is not conforming to your URL path.
I think it should be
#RequestMapping("/xxx/tickets/search")
Cheers!
how to get both values #RequestBody and #RequestParam together??
below the code:
#RequestMapping(value = "/sign-up", method = RequestMethod.POST)
public ResponseEntity<?> addUser(#RequestBody User user,#RequestParam("location") String location,#RequestParam("deviceid") String deviceid) {
System.out.println(location);
System.out.println(deviceid);
it is possible?
for #RequestParam Content-Type application/x-www-form-urlencoded
and for #RequestBody Content-type application/json
i want both value location and deviceid if there is any other way?
#PathVariable is to obtain some placeholder from the uri (Spring
call it an URI Template) — see Spring Reference Chapter 16.3.2.2 URI
Template Patterns
#RequestParam is to obtain an parameter — see Spring Reference Chapter 16.3.3.3 Binding request parameters to method parameters with #RequestParam
If URL http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013 gets the invoices for user 1234 on December 5th, 2013, the controller method would look like:
#RequestMapping(value="/user/{userId}/invoices", method = RequestMethod.GET)
public List<Invoice> listUsersInvoices(
#PathVariable("userId") int user,
#RequestParam(value = "date", required = false) Date dateOrNull) {
...
}
Also, request parameters can be optional, but path variables cannot--if they were, it would change the URL path hierarchy and introduce request mapping conflicts. For example, would /user/invoices provide the invoices for user null or details about a user with ID "invoices"
I have a simple scenario:
User submits form, if there are binding errors I redisplay it, otherwise I set a flash attribute and redirect to the home page. I can't get the command object and RedirectAttributes to play together though, I can either validate the command object or use redirect attributes but not both. This gives me a 400 Bad Request
#RequestMapping(value = "/set", method = RequestMethod.POST)
public String setPassword(#AuthenticationPrincipal User currentUser,
#Validated #ModelAttribute("command") SetPasswordCommand command,
RedirectAttributes redirectAttributes,
BindingResult bindingResult) {
if (bindingResult.hasErrors())
return SET_PASSWORD_VIEW_PATH;
...
redirectAttributes.addFlashAttribute("flashMessage", "Password changed");
return "redirect:/";
}
This works but without the flash attrbute:
#RequestMapping(value = "/set", method = RequestMethod.POST)
public String setPasswordPost(#AuthenticationPrincipal User currentUser,
#Validated #ModelAttribute("command") SetPasswordCommand command,
BindingResult bindingResult) {
if (bindingResult.hasErrors())
return SET_PASSWORD_VIEW_PATH;
...
return "redirect:/";
}
What is the recommended pattern for handling this sort of thing?
Your method signature is wrong, as explained here the BindingResult must directly follow the model attribute.
org.springframework.validation.Errors / org.springframework.validation.BindingResult validation results for a preceding command or form object (the immediately preceding method argument).
So moving the RedirectAttributes after the BindingResult will make it work.
#RequestMapping(value = "/set", method = RequestMethod.POST)
public String setPassword(#AuthenticationPrincipal User currentUser,
#Validated #ModelAttribute("command") SetPasswordCommand command,
BindingResult bindingResult,
RedirectAttributes redirectAttributes) { ... }
I'm quite knowledgeable with Spring yet. I'm trying to learn. Please help me quite a bit.
I have a form which uses modelAttribute="projectBean" which is working perfectly fine and I'm able to manipulate data on the controller below
#RequestMapping( value = "projects/newProject", method = RequestMethod.POST )
public String newProject( #ModelAttribute( "projectBean" )
ProjectBean projectBean, HttpServletRequest request, ModelMap model )
{
model.addAttribute( "projectBean", projectBean );
return "redirect:../projects/projectItems.do";
}
I'm done saving it to the database so I want now to pass the projectBean to another controller
#RequestMapping( value = "/projects/projectItems", method = RequestMethod.GET )
public String projectItems( #RequestParam( defaultValue = "" )
String message, #RequestParam( defaultValue = "" )
String messageType, #RequestParam( defaultValue = "" )
String projectID, HttpServletRequest request, #RequestParam( "projectBean" )
ProjectBean projectBean, ModelMap model )
{
return "project/items";
}
But i'm having this exception: Required ProjectBean parameter 'projectBean' is not present
What am I doing wrong?
You don't generally pass a model from one Controller to another Controller. I assume you are trying to perform some logic before passing the model to another JSP page (project/items in this case).
You can achieve the same in newProject() controller rather than trying to pass the model to another Controller
#RequestMapping( value = "projects/newProject", method = RequestMethod.POST )
public String newProject( #ModelAttribute( "projectBean" )
ProjectBean projectBean, HttpServletRequest request, RedirectAttributes redirectAttributes)
{
//Call DAO class to save the model to database
//Call BusinessDelegate class to perform the additional logic
//Add beans to RedirectAttributes using addFlashAttribute() methods to make it available in next JSP page
redirectAttributes.addFlashAttribute("projectBean", projectBean);
return "redirect:/project/items";
}
Note: In order to apply POST-REDIRECT-GET pattern, you should use RedirectAttributes instead of ModelMap to make the model attributes available in redirected JSP page.
how to use #Requestparam #RequestBody together in spring restful
#RequestMapping(method = RequestMethod.POST, value = "/upate")
#ResponseBody
public ModelAndView availableCheck(
#RequestParam("key") String key, #RequestBody User user)
throws Exception {
//handle
//
}
I want to update user by unique key,so I need request key paramer and the new user json object.
Advance thanks!
There is some possible mistake: if you return a ModelAndView then it is highly unlikely that you want to be it the ResponseBody, therefore remove #ResponseBody.
The other problem is that RespondeBody is for strings. It mean put the Body string in this variable.
So it your user is the command object populated by some form, then just remove the #RequestBody annotation
#RequestMapping(method = RequestMethod.POST, value = "/upate")
public ModelAndView availableCheck(
#RequestParam("key") String key, User user)
throws Exception {
//handle
//
}