#PathVariable is not working in spring - java

I have PersonController as below :
#Controller
#RequestMapping("person")
public class PersonController {
#RequestMapping(value= "/{personId}", method = RequestMethod.GET, produces={"application/json"})
public #ResponseBody Map<String, Object> getPerson(#PathVariable("personId") Integer personId) {
// code to get person
}
Tomcat starts up fine, I see this in the console :
Mapped "{[/person/{personId}],methods=[GET],params=[],headers=[] ,consumes=[],produces=[application/json],custom=[]}" onto public java.util.Map<java.lang.String, java.lang.Object> com.test.web.controller.PersonController.getPerson(java.lang.Integer)
But if I hit the url http://localhost:8080/sample/person/1 I get
HTTP Status 404 - /sample/person/1
In the web.xml
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet-context.xml</param-value>
</init-param-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/sample/*</url-pattern>
</servlet-mapping>

I copy/pasted your PersonController class and it worked fine here.
So I did check your web.xml and your app servlet is mapping the pattern "/sample/*".
If I am corret, I suspect your project is called "sample" in Eclipse. In that case, you have to access your site as follows:
http://localhost:8080/sample/sample/person/1
The mapping in your web.xml will always start from your root context, and that is why you are getting 404 error.
If you want to access your controller from the root domain (in this case it is your actual Eclipse project name by default, but it can be configured too) you can use your servlet mapping as follows:
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
I recommend that you use /rest/* or other mark since it will scale better for other types of content.
Let me know if it worked.

Related

Struts to spring migration getting 404 error

/spring/fetchAllUsers URL which am trying
web.xml
<servlet>
<servlet-name>user</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springContext/dataSource.xml</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>user</servlet-name>
<url-pattern>/spring/</url-pattern>
</servlet-mapping>
Controller Code
#RequestMapping(value = "/getAllUsers", method = RequestMethod.POST)
#ResponseBody
#Transactional(propagation=Propogation.REQUIRED,rollBackFor=Exception.class)
public String fetchAllUsers(){
setInputStream(userDelegate.fetchAllUsers());
return success;
Details:
And I have mvc annotation driven and mvc default servlet handler in user-servlet.xml
Getting 404 error code when try to access this URl when doing migration from struts to spring
Break point is not hit when this URL is hit and no errors in console as well.Please suggest on the above issue
According to your servlet mapping only one url is allowed localhost:8080/context/spring/ that is not mapped with your controller.
When we defined a servlet-mapping, we are using SimpleUrlHandlerMapping. To understand servlet url mapping let define a servlet mapping :
<servlet-mapping>
<servlet-name>user</servlet-name>
<url-pattern>/spring/*</url-pattern>
</servlet-mapping>
Now the handler will actually use the * part to find the controller. It will not search /spring/createUser, it will only search for /createUser to find a corresponding Controller.
#RequestMapping("/createUser")
In your case You need to either change your url to localhost:8080/spring/spring/createUser or remove prefix from Controller #RequestingMapping(/createUser).
since your servlet url mapping has already include /spring you don't need to include it in #RequestMapping.
try this:
#RequestMapping(value = "/createUser/", method = RequestMethod.POST)
Spring interprets urls /spring/createUser/ and /spring/createUser differently(atleast in POST methods that i just tested).
Change your #RequestMapping url to /spring/createUser.
Also mind that the url you call is /spring/createUser without a trailing slash("/").
Your method
#RequestMapping(value = "/spring/createUser", method = RequestMethod.POST)
Hope this helps.

Spring MVC: WARNING: No mapping found for HTTP request with URI

I have this class in my Spring Web model-view-controller (MVC) framework. The version of the Spring Web model-view-controller (MVC) framework is 3.2.8.
I have this web.xml file.
...
<servlet-mapping>
<servlet-name>ecolabelWeb</servlet-name>
<url-pattern>*.do</url-pattern>
<url-pattern>/newdesign/manage/manageapplications</url-pattern>
<url-pattern>/newdesign/manage/manageapplications/</url-pattern>
<url-pattern>/newdesign/manage/manageapplications/*</url-pattern>
<url-pattern>/newdesign/manage/home</url-pattern>
<url-pattern>/newdesign/manage/home/</url-pattern>
<url-pattern>/newdesign/manage/home/*</url-pattern>
<!-- Explicitly mention /welcome.do for usage as welcome page -->
<url-pattern>/welcome/welcome.do</url-pattern>
</servlet-mapping>
...
and this controller:
/**
*
*/
#RequestMapping(value = { "/newdesign/manage/home",
"/newdesign/manage/home/",
"/newdesign/manage/manageapplications",
"/newdesign/manage/manageapplications/"}, method = {RequestMethod.GET})
public String manageApplications (#ModelAttribute("aplicationListForm") final AplicationListForm aplicationListForm,
HttpServletRequest request,
Model model ) throws ExecutionException {
User sessionUser = (User)request.getSession().getAttribute(Const.SESSION_USER);
..
}
this URL works properly
/newdesign/manage/manageapplications
but with this one newdesign/manage/home
I got this error
WARNING: No mapping found for HTTP request with URI [/devices/newdesign/manage/home]
I am really getting crazy !
I also tried to put it in another method with the same result
#RequestMapping(value = { "/newdesign/manage/home",
"/newdesign/manage/home/"}, method = {RequestMethod.GET})
public String cbHome (Model model ) throws ExecutionException {
..
}
This URL is working
http://127.0.0.1:7001/devices/newdesign/manage/manageapplications
not this one (?!)
http://127.0.0.1:7001/devices/newdesign/manage/home
Your configuration doesn't work because in your web.xml you have limited your application to work only with these url:
<url-pattern>/newdesign/manage/manageapplications</url-pattern>
<url-pattern>/newdesign/manage/manageapplications/</url-pattern>
<url-pattern>/newdesign/manage/manageapplications/*</url-pattern>
This is a tipical web.xml:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
With this configuration you are telling Spring to use the dispatcher servlet mechanism to handle the incoming requests and the view rendering. This way he can handle all the url you are defining in controllers, like /newdesign/manage/home.
You need to create the dispatcher-servlet.xml file where you will configure the dispatcher.
See this link for more detailed informations: http://www.mkyong.com/spring-mvc/spring-mvc-hello-world-example/

Trouble with servlet url-pattern matching with wildcards

I am having difficulty getting requests mapped to the correct servlet when the servlet-mapping url-pattern uses a wildcard. I want all requests that begin with "/profile-api" to be mapped to a new REST service I'll be writing soon.
From web.xml:
<!-- default servlet -->
<servlet-mapping>
<servlet-name>professional</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- profile api -->
<servlet-mapping>
<servlet-name>profile-api</servlet-name>
<url-pattern>/profile-api/*</url-pattern>
</servlet-mapping>
Pseudo-code from the controller that allows a third-party system to update a user's "email communication opt-in status" (OptinResponse is a domain class that will ultimately be transformed to JSON and returned to caller):
#Controller
#RequestMapping("/profile-api")
public class ProfileAPIController {
#RequestMapping(method = RequestMethod.GET, value="/setoptin/{userID}")
public #ResponseBody OptinResponse setOptinStatus(#PathVariable String userID) {
return new OptinResponse("200", "Successfully set optin status for user: " + userID);
}
}
I would expect a request to "{localhost}/profile-api/setoptin/12345" to be correctly routed to the ProfileAPIController, but it is not.
Changing the servlet-mapping url-pattern to be more specific but still generic also fails:
<servlet-mapping>
<servlet-name>profile-api</servlet-name>
<url-pattern>/profile-api/setoptin/*</url-pattern>
</servlet-mapping>
The ONLY way I have been able to get my request routed as intended is to include the full, exact path:
<servlet-mapping>
<servlet-name>profile-api</servlet-name>
<url-pattern>/profile-api/setoptin/12345</url-pattern>
</servlet-mapping>
Obviously, that's unacceptable, as the user id must be variable.
In all cases, the request is instead mapped to the default "professional" servlet. I have tried reordering the servlet-mapping nodes to no avail. I have "alwaysUseFullPath" set to "true" in the AnnotationMethodHandlerAdapter bean in the servlet config (but have tried it as "false", too). I feel as though I'm overlooking something simple, but can't see the forest for the trees.

#ServerEndpoint( "/websocket") 404

I'm trying to implement this
http://www.byteslounge.com/tutorials/java-ee-html5-websocket-example
However I can't get it to map to /websocket on the class
#ServerEndpoint( "/websocket")
public class WebSocketController {
}
I can get a method to map using
#ResponseStatus(value = HttpStatus.OK)
#RequestMapping(value = "/websocket")
public WebSocketController<String> logError() {
}
But I can't use the same #RequestMapping on the Class, and #ServerEndpoint isn't having any effect.
Error is
30217 [qtp351496750-25] WARN org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/websocket] in DispatcherServlet with name 'Spring MVC Dispatcher Servlet'
Can anyone help!?
Thanks. The problem was the fact I'm using Spring and didn't add any details into web.xml.
<servlet>
<description>AtmosphereServlet</description>
<servlet-name>AtmosphereServlet</servlet-name>
<servlet-class>org.atmosphere.cpr.AtmosphereServlet</servlet-class>
<init-param>
<param-name>org.atmosphere.cpr.packages</param-name>
<param-value>*******</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AtmosphereServlet</servlet-name>
<url-pattern>/websocket/*</url-pattern>
</servlet-mapping>
Have used Atmosphere and it's working well thanks

Adding multiple servlets in single web.xml

I am trying to run two Servlet-class in a single web.xml but its not working, each servlet-class works fine independently.
web.xml:
<servlet>
<servlet-name>spring-ws</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
<init-param>
<param-name>transformWsdlLocations</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-ws</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>240</session-timeout>
</session-config>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-ws-servlet.xml
/WEB-INF/health-page-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>health-page</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>health-page</servlet-name>
<url-pattern>/health.htm</url-pattern>
</servlet-mapping>
Do let me know if you can figure something wrong that i am doing.
I tried the below link but it doesnt work for me
Can I use Spring MVC and Spring WS in one single application?
This isn't going to work. The one which is mapped on /* overtakes all requests. You need to map it on / instead so that it will only intercept on requests which are not matched by all other existing servlets (including the JSP servlet which is implicitly mapped on *.jsp and all "normal" static resources like CSS/JS/image files!). See also Difference between / and /* in servlet mapping url pattern.
If being able to serve static resources is also required, then better map it on a more specific URL pattern like /ws/* and create a Filter which checks the request URI and then forwards accordingly. That filter can in turn safely be mapped on /*. See also this answer for a more concrete code example: How to access static resources when mapping a global front controller servlet on /*.
I am using Java configuration in my project and following code works fine for the same purpose:
public class Initializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(ApplicationConfiguration.class);
ctx.setServletContext(servletContext);
MessageDispatcherServlet messageDispatcherServlet = new MessageDispatcherServlet();
messageDispatcherServlet.setApplicationContext(ctx);
messageDispatcherServlet.setTransformWsdlLocations(true);
Dynamic dynamic = servletContext.addServlet("messageDispatcherServlet", messageDispatcherServlet);
dynamic.addMapping("/ws/*");
dynamic.setLoadOnStartup(1);
dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
dynamic.addMapping("/");
dynamic.setLoadOnStartup(1);
}
}
you have a mapping for /* in the spring-ws section which is getting the request. you need to
come up with a different strategy... Try putting the /health.htm before the /* mapping.

Categories

Resources