How to prevent Spring MVC parameter from being truncated after "." - java

I am working on a web project and using Spring MVC 3.1.1. Spring MVC is used to serve REST services (using URL annotations)
Regarding to my problem:
Let's say my url path for a service is as;
http://localhost:8080/MyAppName/services/meteo/queryWeatherData/lon/39.1123/lat/39.3123
And my controller method is as;
#RequestMapping(method = RequestMethod.GET, value = {"/queryWeatherData/lon/{lon}/lat/{lat}"})
public void queryWeatherData(
final #PathVariable("lon") float lon,
final #PathVariable("lat") float lat,
final HttpServletResponse response, final HttpServletRequest request) {
//
// DO STUFF and prepare response
//
}
I see that the second parameter (lat) is truncated after "." so I see that the value is 39.0 in server side.
I tried declaring a DefaultAnnotationHandlerMapping bean in my app-context.xml and set its useDefaultSuffixPattern to false but it did not work.
How can I solve this issue?

Declaring the DefaultAnnotationHandlerMapping bean with useDefaultSuffixPattern=false is the right approach, but make sure you also comment out:
<mvc:annotation-driven />
See: How to change Spring MVC's behavior in handling url 'dot' character

Related

How to get URI value coming from HTML to Variable in Spring (There are multiple Links associated with corresponding method)

I have multiple links in my HTML, which are referring to URI in Controller Class,
How can I get this URI in some variable which can be used further, at last, I want to store these URI in DB.
HTML Code :
<td>Win Report</td>
<td>Win Report</td>
Spring Controller Class :
#RequestMapping(value = "/ui/report/win", method = RequestMethod.GET)
public String winReport() {
return "win_report";
}
#RequestMapping(value = "/ui/report/niw", method = RequestMethod.GET)
public String niwReport() {
return "niw_report";
}
You can use the below solution to retrieve the page Url as well as avoid using repetitive method calls.
You can use a Spring Boot HandlerInterceptor, here's a brief description of the same :
Handler interceptors are used when you want to apply specific
functionality to certain or all requests.
Handler Interceptors should implement the interface HandlerInterceptor. HandlerInterceptor can be used to avoid repetitive handler code.
We can use HandlerInterceptor for different purposes like authorization checks, locale checks, logging, creating common application parameters etc.
HandlerInterceptor works similar to the servlet filter. But in some cases filters are more powerful than HandlerInterceptor.
In Spring-MVC the HandlerInterceptor is configured in spring application context xml file or by Java configuration.
HandlerInterceptor has three methods.
preHandle( ) : It is executed before actual handler is executed.
postHandle( ) : It is executed after handler is executed.
afterCompletion( ) : It is executed after the complete request is finished.
For more details, you can use an example from the below link
https://www.tuturself.com/posts/view?menuId=3&postId=1071
You can get the entire sample project which can help you with the setup at
https://github.com/ninja-panda
To get the request url you can do the following:
#RequestMapping(value = "/ui/report/win", method = RequestMethod.GET)
public String winReport(HttpServletRequest request){
String request = request.getRequestURI();
// do somehting here
return "win_report"
}
Spring will automatically inject the HttpServletRequest.
Update:
If your want get the urls for all of your methods in your controller, you can go with RequestMappingHandlerMapping:
private final RequestMappingHandlerMapping handlerMapping;
#Autowired
public YourController(RequestMappingHandlerMapping handlerMapping) {
this.handlerMapping = handlerMapping;
}
With handlerMapping.getHandlerMethods(), you can access all mappings decleared in your controller. With reflection and getMappingAnnotation, you can then read the value of each RequestMapping annotation.
You can try the getServletPath() like following:
#RequestMapping(value = "/ui/report/win", method = RequestMethod.GET)
public String winReport(HttpServletRequest request){
String mapping = request.getServletPath();
// do somehting here
System.out.println(mapping); // Will print /ui/report/win
return "win_report"
}

Get header from request in service layer of Spring Boot application

Is there any way in spring boot to grab header from request in any point of application?
Some static stuff will be great.
Please, be aware that #RequestHeader does not work for me since I need this value on service layer.
You can inject HttpServletRequest object in your service layer like this :
#Autowired
HttpServletRequest request;
private void method() {
request.getHeader("headerName");
}
but remember, that bean HttpServletRequest has HTTP request scope. So, you can't inject that into asynchronous methods etc, because it will throw Runtime Exception.
hope it helps.
I was searching the same question before, i found out that you can use header parameters in the RestController methods with #RequestHeader as you said. So why not direct them into your service layer methods:
#Autowired
ServiceLayerObj serviceLayerObj;
...
#RequestMapping
public YourReturnObj someRestServiceMethod(
#RequestBody SomeObj body,
#RequestHeader(value = "username") String username
){
return serviceLayerObj.yourServiceLayerMethod(body,username);
}

HTTP 404 Not Found Error in Spring 3.2.8 application

I have an application based in the Spring Web model-view-controller (MVC) framework
I have this controller
#Controller
public class ApplicantApplicationsListController extends ApplicantController {
/**
* #throws Exception
*
*/
#RequestMapping(value = { "/medrano/applicant/home",
"/medrano/applicant/home/"}, method = {RequestMethod.GET})
public String viewProductApplications (#ModelAttribute("applicationApplicationsListForm") final ApplicationApplicationsListForm applicationApplicationsListForm,
HttpServletRequest request,
Model model ) throws Exception {
return "applicantApplicationsView";
}
But I got a 404 in the browser when I put
http://127.0.0.1:7001/cage/medrano/applicant/home
You have a mapping problem with your request mapping:
The annotation #RequestMapping value property expects an array of Strings, in your case:
value = {"/medrano/applicant/home",
"/medrano/applicant/home/",}
Is not a valid String[], you have an additional , at the end, just remove it.
You can check the Spring MVC #RequestMapping Annotation Example with Controller, Methods, Headers, Params, #RequestParam, #PathVariable tutorial for further exmaples on how to use it.
Edit:
There's no need to use the brackets with a single value for both
value and method properties.
And why would you use the same value "/medrano/applicant/home"
twice in your RequestMapping.
It could simply be like this:
#RequestMapping(value = "/medrano/applicant/home",
method = RequestMethod.GET)
I forgot to Configure the Spring DispatcherServlet in the file web.xml with:
...
<servlet-mapping>
<url-pattern>//medrano/applicant/home</url-pattern>
<url-pattern>//medrano/applicant/home/</url-pattern>
</servlet-mapping>
...

#RequestMapping does not work on type and method in Spring 2.5

I have been reading on Spring 3.2 lately and I am now trying the following code using Spring 2.5. From what I have read this should mean that it should map profile/tags/me. However it doesn't. It just throws a No mapping found for HTTP request with URI .... What is wrong with the code, or didn't Spring 2.5 work like it does in Spring 3?
Problem when using Spring 2.5
#Controller
#RequestMapping("/profile/tags")
public class ProfileController { ... }
And this is the method inside ProfileController class:
#RequestMapping(value = "/me", method = RequestMethod.GET)
public String show(#RequestParam final long id, final ModelMap model) { ... }
According to Spring documentation, I imagine you're missing the required configuration to receive the request parameter, if you mean to receive this request parameter:
#RequestMapping(value = "/me/{id}", method = RequestMethod.GET)
public String show(#RequestParam("id") final long id, final ModelMap model) { ... }
Or you should remove RequestParam.
Update for Spring 2.5
Additionally, since you're using Spring 2.5, make sure that you've configured your DispatcherServlet in the expected way; Sections 13.11, subsections 1, 2, and 3. In summary:
DispatcherServlet should be told to load annotated RequestMappings.
DispatcherServlet should be told to load Controller annotations.
Not sure but maybe you need to refine the paths you use for the request mappings.
Hope this helps.

Find whether URL mapping exists in Spring MVC 3.1 using code in a controller

I am using Spring 3.1 MVC and in one of the request I get parameter which is URL.
e.g. http:/myapp/controllername?url=someurl
I need to find out in my controller method whether some URL is configured in my application.
I tried using RequestMappingHandlerMapping instance to get
Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
But I have a string which is URL, I will need to create a RequestMappingInfo object out of this to look up in this map, which doesn't have any constructor based on just URL.
How to find whether an URL mapping exists in spring mvc 3.1 using code in a controller?
You can use requestMappingInfo.getPatternsCondition() to check the mapping path; and it has toString method for you to compare with your url string.
Set<RequestMappingInfo> rmSet = handlerMapping.getHandlerMethods().keySet();
for (RequestMappingInfo rm : rmSet) {
if("[YourURLPath]".equals(rm.getPatternsCondition().toString())) {
// URL mapping matched
}
}
Example: For url http://mydomain/test/abc the above condition should be as
if("[/test/abc]".equals(rm.getPatternsCondition().toString()))
I believe you have already autowired handlerMapping object in your controller, as below
#Autowired
private RequestMappingHandlerMapping handlerMapping;

Categories

Resources