Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
To my knowledge both serves the same purpose. Except the fact that #PathVariable is from Spring MVC and #PathParam is from JAX-RS. Any insights on this?
#PathVariable and #PathParam both are used for accessing parameters from URI Template
Differences:
As you mention #PathVariable is from spring and #PathParam is from JAX-RS.
#PathParam can use with REST only, where #PathVariable used in Spring so it works in MVC and REST.
QueryParam:
To assign URI parameter values to method arguments. In Spring, it is #RequestParam.
Eg.,
http://localhost:8080/books?isbn=1234
#GetMapping("/books/")
public Book getBookDetails(#RequestParam("isbn") String isbn) {
PathParam:
To assign URI placeholder values to method arguments. In Spring, it is #PathVariable.
Eg.,
http://localhost:8080/books/1234
#GetMapping("/books/{isbn}")
public Book getBook(#PathVariable("isbn") String isbn) {
#PathParam is a parameter annotation which allows you to map variable URI path fragments into your method call.
#Path("/library")
public class Library {
#GET
#Path("/book/{isbn}")
public String getBook(#PathParam("isbn") String id) {
// search my database and get a string representation and return it
}
}
for more details : JBoss DOCS
In Spring MVC you can use the #PathVariable annotation on a method argument to bind it to the value of a URI template variable
for more details : SPRING DOCS
#PathParam is a parameter annotation which allows you to map variable URI path fragments into your method call.
#PathVariable is to obtain some placeholder from the URI (Spring call it an URI Template)
Some can use #PathParam in Spring as well but value will be null when URL request is being made
Same time if We use #PathVarriable then if value is not being passed then application will throw error
#PathVariable
#PathVariable it is the annotation, that is used in the URI for the incoming request.
http://localhost:8080/restcalls/101?id=10&name=xyz
#RequestParam
#RequestParam annotation used for accessing the query parameter values from the request.
public String getRestCalls(
#RequestParam(value="id", required=true) int id,
#RequestParam(value="name", required=true) String name){...}
Note
whatever we are requesting with rest call i.e, #PathVariable
whatever we are accessing for writing queries i.e, #RequestParam
#PathParam: it is used to inject the value of named URI path parameters that were defined in #Path expression.
Ex:
#GET
#Path("/{make}/{model}/{year}")
#Produces("image/jpeg")
public Jpeg getPicture(#PathParam("make") String make, #PathParam("model") PathSegment car, #PathParam("year") String year) {
String carColor = car.getMatrixParameters().getFirst("color");
}
#Pathvariable: This annotation is used to handle template variables in the request URI mapping ,and used them as method parameters.
Ex:
#GetMapping("/{id}")
public ResponseEntity<Patient> getByIdPatient(#PathVariable Integer id) {
Patient obj = service.getById(id);
return new ResponseEntity<Patient>(obj,HttpStatus.OK);
}
Related
An argument to a Spring MVC method can be declared as RequestBody or RequestParam. Is there a way to say, "Take this value from either the body, if provided, or the URL parameter, if not"? That is, give the user flexibility to pass it either way which is convenient for them.
You can make both variables and check them both for null later on in your code
like this :
#RequestMapping(value = GET_SOMETHING, params = {"page"}, method = RequestMethod.GET)
public
#ResponseBody
JSONObject getPromoByBusinessId(
#PathVariable("businessId") String businessId, #RequestParam("page") int page,
#RequestParam("valid") Boolean valid,
#RequestParam("q") String promoName) throws Exception {}
and then use a series if if-else to react to requests.
I wrote it to work with any of the three params be null or empty, react to all different scenarios.
To make them optional, see :
Spring Web MVC: Use same request mapping for request parameter and path variable
HttpServletRequest interface should help solve this problem
#RequestMapping(value="/getInfo",method=RequestMethod.POST)
#ResponseBody
public String getInfo(HttpServletRequest request) {
String name=request.getParameter("name");
return name;
}
Now, based on request data coming from body or parameter the value will be picked up
C:\Users\sushil
λ curl http://localhost:8080/getInfo?name=sushil-testing-parameter
sushil-testing-parameter
C:\Users\sushil
λ curl -d "name=sushil-testing-requestbody" http://localhost:8080/getInfo
sushil-testing-requestbody
C:\Users\sushil
λ
I am using Spring Boot 1.5.3.RELEASE and using a Controller that takes a MultipartFile with some other information as arguments and returns a file.
Now I am facing the org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException when the file exceeds the maximum Sizes.
spring.http.multipart.maxFileSize=17728640
spring.http.multipart.maxRequestSize=17728640
This works well but i need a custom Response and actually the Exception is throwed only at server side before the method call.
Can anyone tell me how can I define a Custom Error Handler that handles this exception and response something like ResponseEntity.status(HttpStatus.CONFLICT).body("size_exceeded")
My Method:
#SuppressWarnings("rawtypes")
#RequestMapping(value = "/{Id}/attachments", method = RequestMethod.POST)
public ResponseEntity addTaskAttachment(#RequestParam("file") MultipartFile file, #PathVariable Long Id,
#CurrentUser User currentUser) {
// Some code here
ResponseEntity.status(HttpStatus.OK).body(attachmentAsByteArray);
}
You are correct in your observation that an Exception Handler with #RestControllerAdvice wouldn't work for multi part exceptions and reason being MultipartFile parsing & validation step preceding the mapping resolver step.
As advised in first accepted answer by geoand for this SO question here , you need to define and register an ErrorController.
Also, note that as already mentioned in that answer , Spring Boot already defines a BasicErrorController that you can extend to add new content types to return a JSON etc ( since default is text/html ) by adding a new public method with #RequestMapping & #Produces .
I am very new to WebApp in general and Spring MVC in particular. I am writing a small project where I wish to get the key value pair posted by a client. I can do it if I know the value of the key beforehand. The tutorials I've read in parameter processing also assumes that you know the parameter name. But what if I don't know the parameter name.
#Controller
#RequestMapping(value = "/keyvaluepost")
public class ProcessController {
#RequestMapping(method = RequestMethod.POST)
public String doPost(
HttpServletRequest request,
HttpServletResponse response,
#RequestParam("knownKey") String knownKey) {
// process knownKey here
// but what if i do not know the key?
}
Basically, I am looking for something similar to $_POST in php where I can get the key value pair. Any help will be greatly appreciated. Thanks.
I have some questions from a design point of view in Spring Web MVC.
Is it good practice to use Request Object in controller? If not, then what is alternative way to pass pass one text fields value to controller? Do I need to create one new from bean for this single fields?
It depends of the situation, in a few cases I used the HttpServletRequest; for example for writing a file to the output stream.
If you want to get the Request Parameters you can use the annotation #RequestParam, that it´s more easy to get the parameters from the request.
Depends that you want to handle, for example for a form you can use #ModelAttribute and this attribute can be in a session or in the request.
For example:
#Controller
public class YourController {
#RequestMapping(value = "someUrl", method = RequestMethod.GET)
public String someMethod(#RequestParam("someProperty") String myProperty)
{
// ... do some stuff
}
}
Check the documentation here:
#RequestParam
#ModelAttribute
#PathVariable
I have a Spring MVC controller set up like so:
#RequestMapping("activityChart")
public ModelAndView activityChart(
#RequestParam(required=false, value="parent") String parent,
#RequestParam(required=false, value="expand") String[] expand,
#ModelAttribute PaginationArgs paginationargs) throws IOException {
// ... return template renderer
}
Where PaginationArgs is a two-field POJO. I want to construct a URL string that includes values for paginationargs. It's easy to do for parent and expand - activityChart?parent=foo&expand=bar&expand=baz, but what's the right way to encode a POJO's fields?
JSP takes care of this in Spring with a <form:form modelAttribute='paginationargs'> tag, but our project isn't using JSP but Jamon instead.
In the simple case parameter names should be the same as the corresponding field names of the model object. So, if PaginationArgs has fields page and size, it would be like page=1&size=10.
In more complex cases Spring can accept parameters whose names are formed as described in 5.4 Bean manipulation and the BeanWrapper.