Pass javascript value to controller in spring mvc - java

I am new with Spring mvc. I need to pass an javascript variable to controller. How to achieve this??
Form tag solution is not appropriate in case of my application.
I need to pass this start variable of JS to my controller.In some cases this variable can be null or not available as per requirements.
Please suggest asap!!!
My JS code is:
function clickPaginate(start){
var X = '<%=url%>';
window.location.href=X+'/library/${publisher}';
}
and controller is:
#RequestMapping(value = "/library/{publisher}", method = RequestMethod.GET)
public String getPublisherDetails(#PathVariable("publisher") String publisher, ModelMap model) throws FeedsException {
}

There is an annotation #RequestParam that you'll have to use in the method. In your case
window.location.href=X+'/library/${publisher}?foo=bar';
foo is the request parameter with value bar that you are passing to your method.
Your method should be like
public String getPublisherDetails(#RequestParam("foo") String foo, #PathVariable("publisher") String publisher, ModelMap model)
Check out this mvc doc

Related

Spring restful API, is there a method being used like router to get other method's end points or URL?

#RequestMapping("/accounts")
public class controller {
#GetMapping("/get/{id}")
public final ResponseEntity<?> getHandler(){
}
#PostMapping(value = "/create")
public final ResponseEntity<?> createHandler(){
/*
trying to use some spring library methods to get the url string of
'/accounts/get/{id}' instead of manually hard coding it
*/
}
}
This is the mock code, now I am in createHandler, after finishing creating something, then I want to return a header including an URL string, but I don't want to manually concat this URL string ('/accounts/get/{id}') which is the end point of method getHandler(), so I am wondering if there is a method to use to achieve that? I know request.getRequestURI(), but that is only for the URI in the current context.
More explanation: if there is some library or framework with the implementation of route:
Routes.Accounts.get(1234)
which return the URL for the accounts get
/api/accounts/1234
The idea is, that you don't need to specify get or create (verbs are a big no-no in REST).
Imagine this:
#RequestMapping("/accounts")
public class controller {
#GetMapping("/{id}")
public final ResponseEntity<?> getHandler(#PathVariable("id") String id) {
//just to illustrate
return complicatedHandlerCalculation(id).asResponse();
}
#PostMapping
public final ResponseEntity<?> createHandler() {
//return a 204 Response, containing the URI from getHandler, with {id} resolved to the id from your database (or wherever).
}
}
This would be accessible like HTTP-GET: /api/accounts/1 and HTTP-POST: /api/accounts, the latter would return an URI for /api/accounts/2 (what can be gotten with HTTP-GET or updated/modified with HTTP-PUT)
To resolve this URI, you could use reflection and evaluate the annotations on the corresponding class/methods like Jersey does.
A Spring equivalent could be:
// Controller requestMapping
String controllerMapping = this.getClass().getAnnotation(RequestMapping.class).value()[0];
and
//Method requestMapping
String methodMapping = new Object(){}.getClass().getEnclosingMethod().getAnnotation(GetMapping.class).value()[0];
taken from How do i get the requestmapping value in the controller?

Receive Collection/Iterable as arguments in spring boot controller

I am new to Spring and I want to write a controller which will take Collection/Iterable as arguments. Like this:
#RequestMapping(value = "friends", method = RequestMethod.POST)
public #ResponseBody Callable<Iterable<User>>
getFriendsOfUser(#RequestParam(required = true, name = "mobiles") Iterable<String> mobs) {
// return callable
}
There is no compilation error, but I cannot make it work. Can you say how will this work? And how shall be the request to this api be constructed?
public String getFriendsOfUser(#RequestParam(required = true, value = "mobiles") String[] mobiless){
....
}
and your mobile should be
mobiles=myValue1&mobiles=myValue2&mobiles=myValue3
or
mobiles=myvalue1,myValue2,myValue3
still if you have any doubt post your front-end code and Ajax call.
You've mapped a POST method so you might need #RequestBody instead of #RequestParam
#RequestParam is, as the name implies, for request parameters: [host]/endpoint?param=foo&secondParam=bar
whereas
#RequestBody is for JSON/XML or any other type content sent as the request's body.

On Java Controller how to get the value of annotation #RequestMapping("/getThisValueFromOtherClass")?

On Java MVC Controller how to get the value of annotation #RequestMapping("/getThisValueFromOtherClass")? I know we can extract this by using java reflections but is there any other way? Thank you.
#RequestMapping("/getThisString")
public class MyController{}
If the purpose is just to avoid changing the url at every place, I will suggest define a string constant in some class and instead of using hard coded string in request mapping use that constant every where.
In future if u want tp\o change the url, simple update the constant value at one place
final String constUrl = "/myurl";
#RequestMapping(value=constUrl)
you can make the constant static, if defining in another class
The value of the annotation can be read programmatically:
#RequestMapping("/endpoints")
public ResponseEntity<String> getPath() {
String path = getClass().getAnnotation(RequestMapping.class).value()[0];
return new ResponseEntity<String>(path, HttpStatus.OK);
}
To obtain the path, you should pass the Request i.e. HttpServletRequest as a parameter to your handler method.
#RequestMapping(value={"/getThisString"}, method=RequestMethod.GET)
public String handlerMethod (Model model, HttpServletRequest request) throws Exception {
String getThatString = request.getServletPath();
....
}
Reference:
HttpServletRequest
In your case if an URI pattern “/getThisString” is requested, it will map to this MyController, and handle the request with method where #RequestMapping(method = RequestMethod.GET) is declared.
You can refer this tutorial #RequestMapping example
Hope it helps.

Spring MVC incoming parameters #RequestParam String requestedURL

I have two Spring MVC actions that in this example takes one parameter from a form when submitted:
public ModelAndView login(HttpServletResponse response, HttpServletRequest request,
#RequestParam String requestedURL )
I would like to know if the attribute requestedURL can refer to a declared variable that actually hold the name of the incoming attribute input name="requestURL" ...
class Core {
static String requestedURL = "requestedURL";
}
pseudo code:
public ModelAndView login(..., #RequestParam String #ReadFrom(Core.RequestedURL) )
Notice the #ReadFrom
This is to avoid redundancy. Right now it is called requestedURL but in the future someone might want to change the input parameter name, this shouldn't be a hardcoded string in the applicaton in my opinion.
and
<input name="<%= Core.requestedURL %>" value="<%= requestedURL %>" />
and is read in the method when submitted. But does the attribute name have to be hardcoded in the incoming parameter of the action method?
Thanks!
Yes, it has to be hardcoded as part of the #RequestParam annotation - either hardcoded or refer to a static final variable.
The alternative is to take in a Model/Map as an additional parameter in the method and getting the attribute from that:
public ModelAndView login(HttpServletResponse response, HttpServletRequest request,
Model model ){
String requestedURL = model.asMap().get(Core.requestedURL);
}
Update
You can refer to a static final variable this way:
assuming:
public abstract class Core {
public static final String requestedURL = "requestedURL";
}
public ModelAndView login(..., #RequestParam(Core.requestedURL) String requestedURL)

How do you handle an Ajax.Request call in a Spring MVC (3.0) app?

I have the following call in my JavaScript:
new Ajax.Request('/orders/check_first_last/A15Z2W2',
{asynchronous:true, evalScripts:true,
parameters:{first:$('input_initial').value,
last:$('input_final').value,
order_quantity:$('input_quantity').value}});
What do I need to do to get Spring MVC (3.0) to handle this?
#Controller
#RequestMapping("/orders")
public OrderController {
#RequestMapping("/check_first_last/{code}")
#ResponseBody
public Result checkFirstLast(#PathVariable String code,
#RequestParam int first,
#RequestParam int last,
#RequestParam("order_quantity") int orderQuantity) {
// fetch the result
Result result = fetchResult(...);
return result;
}
}
A few notes:
#PathVariable gets a variable defined with {..} in the request mapping
#RequestParam is equvallent to request.getParameter(..). When no value is specified, the name of the parameter is assumed (first, last). Otherwise, the value (order_quantity) is obtained from the request.
#ResponseBody means you need Jackson or JAXB present on the classpath, and <mvc:annotation-driven> in the xml config. It will render the result with JSON or XML respectively.
If you want to write HTML to the response directly, you have two options:
change the return type to String and return the HTML as a String variable
add an HttpServletResponse response parameter to the method and use the response.getWriter().write(..) method to write to the response
Resource: Spring MVC documentation

Categories