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>
...
Related
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"
}
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
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.
Is there existing solution to get mapped URL from (controller-name, action-name) in Spring MVC3, like UrlHelper in asp.net mvc or rails? I think it's very useful!
thx....
Probably, you want something like this:
in your #Controller class, you can add to your "action" method extra parameter of type HttpServletRequest.
Example:
#Controller
public class HelloWorldController {
#RequestMapping("/helloWorld")
public void helloWorld(HttpServletRequest request) {
//do call #getRequestURI(), or #getRequestURL(), or #getPathInfo()
}
}
With default configuration, Spring will "automagically" inject request, and then you can extract path info by calling one of HttpServletRequest#getPathInfo(), HttpServletRequest#getRequestUrl() methods (see explanation here: http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#method_summary)
In Spring 3 MVC, I have a controller that I call SettingsController, and it has methods such as displayUsers() for displaying a list of users, saveUser(), and deleteUser(). SettingsContoller also controls roles and other things.
I'd love to be able to use URL routing such that /settings/users would call displayUsers(), /settings/users/save would call saveUser(), and /settings/users/delete would call deleteUser().
My code is below, and I'm getting the error message that follows the code. What am I doing wrong? Thanks!
#Controller
#RequestMapping("/settings")
public class SettingsController {
#Transactional
#RequestMapping(value = {"/users/save"}, method = {RequestMethod.POST})
public ModelAndView saveUser(details removed){
//details removed
}
#RequestMapping(value = {"/users/delete"}, method = {RequestMethod.POST})
public ModelAndView deleteUser(details removed){
//details removed
}
#RequestMapping(value = {"/users"}, method = RequestMethod.GET)
public ModelAndView settingsUsers(details removed){
//details removed
}
}
Error:
HTTP ERROR: 500
Could not resolve view with name 'settings/users/delete' in servlet with name 'spring'
RequestURI=/das-portal/srv/settings/users/delete
Caused by:
javax.servlet.ServletException: Could not resolve view with name 'settings/users/delete' in servlet with name 'spring'
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1029)
...
It looks to me like you've set up your controller correctly. As you pointed out, the problem might be in how Spring parses annotations upon start up.
How did you configure Sprint to parse annotations such as #Controller? Do you explicitly set up any sort of HandlerMapping? If you use <context:component-scan>, then it registers a DefaultAnnotationHandlerMapping for you.
The good news is that you can chain multiple handler mapping classes together. The DispatcherServlet will check each one in the order that you specify via the order property of the handler mapping beans (in other words, use the order property to indicate the precedence of your handlers).
So, throw <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> into your configuration and set its order property as appropriate.
What about using just one method checking mode?
#RequestMapping(value = "/users/{action}", method = RequestMethod.POST)
public String userAction(#PathVariable String action, ...) {
if (mode.equals("save")) {
//your save code here
}
}