Map Post Parameter With Dash to Model In Spring Controller - java

I have the following property that I need mapped to a post parameter in Spring. Is there an attribute I can use? It accepts application/x-www-form-urlencoded for string-based payloads, multipart/form-data for binary payloads. Other properties are mapping fine without underscores.
String deliveryAttemptId;
mapped to the post parameter
DELIVERY-ATTEMPT-ID
Controller
#Controller
#RequestMapping("/notifications")
public class NotificationController {
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public void grade(EventNotificationRequest request, HttpServletResponse response) throws Exception {
}
Model
public class EventNotificationRequest {
String deliveryAttemptId;

I just made a work around for this Spring limitation. This also fixes case sensitivity issues with parameters. Sorry I am used to .NET and how easy binding is so it's frustrating to run into these Spring issues.
HttpServletRequest parameter lowecase
#RequestMapping(method = RequestMethod.POST, value = "/grade")
#ResponseBody
public void grade(HttpServletRequest request, HttpServletResponse response) throws Exception {
EventNotificationRequest notificationRequest = new LearningStudioEventNotificationRequest();
notificationRequest.setDeliveryAttemptId(getCaseInsensitiveParameter(request, "DELIVERY-ATTEMPT-ID"));

Related

Spring MVC ModelAttribute values being lost

I'm running into a situation where my model attribute is losing values between pages.
I've got two controller methods that handle GET and POST requests respectively.
GET Method
#RequestMapping(value = "/checkout/billing", method = RequestMethod.GET)
public String getBillingPage(Model model, final HttpServletRequest request) throws CMSItemNotFoundException {
// other code
checkoutForm.setCustomFieldsForm(customFieldsForm);
model.addAttribute("checkoutForm", checkoutForm);
// other code
}
Debug View After GET Method completes
POST Method
#RequestMapping(value = "/checkout/billing", method = RequestMethod.POST)
public String submitPayment(
#Valid #ModelAttribute("checkoutForm") final CheckoutForm checkoutForm,
final BindingResult bindingResult,
Model model,
final HttpServletRequest request,
final HttpServletResponse response) throws CMSItemNotFoundException
{}
Debug View When POST Method is Invoked
The 1234 comes from the user entering that data in the form field. The other values should still be there and not null though.
What could be happening here?
Your model is not stored in the session. Each request creates a new model object. That's why it's empty.
You can add your model as a session attribute. Please find the documentation here https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-sessionattrib

Spring #RequestMapping

I have a question with Spring MVC RequestMapping annotation. need your help.
I have created one IPSLcontroller and i want that IPSLcontroller to handle all request url.i have created two method in this controller.
1)handleLogoutRequest :- this method should invoke on below url.
2)handleRequest :- this method should invoke on all request url otherthan logout.
http://localhost:9086/webapp/login
or
http://localhost:9086/webapp/add
or
http://localhost:9086/webapp/remove
here is my sample code. but it's not working as expected.
#Controller
public class IPSLController {
#RequestMapping(value={"/logout/*"},method = RequestMethod.POST)
protected void handleLogoutRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out
.println("........................IPSLController logout request.......................................");
}
#RequestMapping(method = RequestMethod.POST,value={"/*"})
protected void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out
.println("........................IPSLController all request Post.......................................");
}
}
You should use a general Prefix for every controller you use, so you can differ between them better. Also you donĀ“t need any "/" for calls like this.
#Controller
#RequestMapping("ispl")
public class IPSLController {
#RequestMapping(value={"logout"},method = RequestMethod.POST)
protected void handleLogoutRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out
.println("........................IPSLController logout request.......................................");
}
#RequestMapping(method = RequestMethod.POST,value={"hello"})
protected void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out
.println("........................IPSLController all request Post.......................................");
}
}
If you now want to call them over a ServletRequest or with a restService or something similar you should declare them like this
#GET
#Path("ispl/logout")
public void Method (HttpServletResponse ...)
Well it is working the way it should. You have a mapping for /* and for /logout/*. So when you post to /logout it invokes the method for /*. I suspect that if you post to /logout/something it would invoke your logout handler.
If you want it to work, you cannot have a wildcard mapping for the second method. At least use /something/* so that spring can make a correct decision on mappings.

MissingServletRequestParameterException: requird parameter not present

#RequestMapping(value = "/connect{accountDeviceId}", method = RequestMethod.GET)
public #ResponseBody
String showCompleteAuthorizat(HttpServletRequest request,
HttpServletResponse response,
#RequestParam("accountDeviceId") int accountDeviceId) throws Exception {
I'm getting this error
org.springframework.web.bind.MissingServletRequestParameterException: Required int parameter 'accountDeviceId' is not present
and this is the url that calls the above api
http://localhost:8080/gch-restful/fitbit/connect29?oauth_token=b1e939450e745664ce4bbbc194b4ed47f&oauth_verifier=9dc1045654dc775d2347ae2963d5ae878c
I'm new to spring and basically learning it, please tell me what am I doing wrong here.
Regards
You should use #PathVariable(value="accountDeviceId") instead of #RequestParam("accountDeviceId") in order to get a variable from url.

Restrict method on MultiActionController action

I have a MultiActionController with an action that I would only like to be reachable if the POST method is used.
public class MyController extends MultiActionController {
public ModelAndView myAction(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
// I don't want to hit this code unless POST was used
}
}
Is there a way to achieve this through annotations or am I stuck checking request.getMethod() ?
Use:
#RequestMapping(value={"action1","action2","action3"},
method = RequestMethod.POST)

How to read request parameter values Using HandlerInterceptor in spring?

I'm using HandlerInterceptor to trigger all the events/actions happens in my applications and save it to audit table. In table I'm saving the information like servername, session, parameters etc..
So using HandlerInterceptor how can I read all those parameters values and the pathvariable values what I'm passing in my controller.
Here is my code :
public class AuditInterceptor implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
LOG.debug("URL path"+request.getRequestURI());
return true;
}
#Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
LOG.debug("URL PATH :"+request.getRequestURI());
}
}
My controller class enter code here::
public class ABCDController {
#RequestMapping(value="categories",method=RequestMethod.GET)
#ResponseBody
public List<Category> getCategoryList(#RequestParam String divisions){
return service.getCategoryList(divisions);
}
}
So how can I read the parameter name and values using HandlerInterceptor's HttpServletRequest request object.
The Servlet API provides a way to read the Request Parameters. For example,
ServletRequest.getParameterMap() returns a map of key-values of the request parameters.
However, for Path variables and values, I don't know if Spring MVC offers a simplified way of doing it, but using Servlet API again, you can read the URI using HttpServletRequest.getRequestURI(). You'll have to have your own logic to split it up into appropriate Path parameters.
You should be able to get the variables and its values as a map using the following,
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
final Map<String, String> variableValueMap = (Map<String, String>) request
.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
variableValueMap.forEach((k,v)->System.out.println("Key:"+k+"->"+"Value : "+v));
return true;
}

Categories