Spring : No mapping found for HTTP request - java

I strangely have this problem :
[04/07/14 11:31:09:009 CEST] WARN servlet.PageNotFound: No mapping found for HTTP request with URI [/datapine-backend/heroku/resources] in DispatcherServlet with name 'rest'
However, I checked the logs and my method is already mapped!
annotation.RequestMappingHandlerMapping: Mapped "{[/heroku/resources/],methods=[POST],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}" onto public org.springframework.http.ResponseEntity<java.lang.String> com.datapine.heroku.HerokuController.provision(net.sf.json.JSONObject)
This my method :
#Controller
public class HerokuController {
#RequestMapping(value = "/heroku/resources/", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> provision(#RequestBody JSONObject body){
System.out.println("called! \n");
JSONObject response = new JSONObject();
response.put("id", 555);
response.put("message", "Provision successful!");
return new ResponseEntity<String>(response.toString(),HttpStatus.OK);
}
This is my web.xml
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/heroku/*</url-pattern>
</servlet-mapping>
and this is the rest-servlet.xml :
<beans:import resource="classpath:spring-properties-loader.xml"/>
<context:component-scan base-package="com.datapine.heroku" />
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
</beans:beans>
what can be the problem?
thanks.

Related

Spring #Autowired gives new instance instead of initialized session scoped bean

I am developing application using Spring and I need to initialize Ticket object in session and then get it from another controller.
I have two controllers, so there are two xml contexts.
web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring Web MVC Application</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/rest-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>index</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/index-context.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>index</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
rest-context.xml
<beans ...>
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="menu.MenuController"/>
</beans>
index-context.xml
<beans ...>
<mvc:annotation-driven/>
<mvc:resources mapping="/**" location="/"/>
<context:annotation-config/>
<bean class="auth.IndexWebController" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>
</beans>
In the spring-context I have my Ticket bean:
<bean id="tickerProvider" class="TicketProviderImpl" scope="session">
<aop:scoped-proxy/>
together with the other beans.
This are what my controllers look like:
IndexWebController.java
#Controller
#SessionAttributes("user")
public class IndexWebController {
private static Logger logger = LoggerFactory.getLogger(IndexWebController.class);
#Autowired
private TicketProviderImpl ticketProvider;
#ModelAttribute("user")
public User populateUser() {
return new User();
}
#RequestMapping(value = "/", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView printIndex(#ModelAttribute("user") User user,
#RequestParam(value = "iv-user", required = false) String login,
#RequestParam(value = "iv-groups", required = false) String groups) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index.html");
<...>
ticketProvider.setLogin(login);
logger.info("Пользователь установлен в " + login);
<...>
MenuController.java
#Controller
public class MenuController {
#Autowired
private TicketProviderImpl ticketProvider;
#ResponseBody
#RequestMapping("/getMenuList")
public MenuListDTO getMenuList(
#RequestParam(value = "menuId", required = true, defaultValue = "-1") long menuId,
#RequestParam(value = "parentId", required = true, defaultValue = "0") long parentId) {
<...>
System.out.println(ticketProvider.getLogin());
<...>
}
}
The problem is that when I autowire ticketProvider bean in the MenuController I get a new instance of it, not those that has been initialized in the IndexWebController. Actually I get null, but waiting for the login.
Where is the mistake or some misunderstanding of using session scoped beans?
According to this you will need another listener to expose your session to the application.
Hence adding <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> should do the trick.

two servlets which point on the same package and webservice

Can anyone tell me please if what i am doing is right ?
I have this web.xml file with my servlets declared inside, i wanted to creat another servlet that access [reach] the same webservice
it doesn't work and i don't know what i am missing can you help please ?
Here is my servlets and code:
<!-- old servlet-->
<servlet>
<servlet-name>api</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config/api-r-servlet.xml</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>api</servlet-name>
<url-pattern>/sitesApi/*</url-pattern>
</servlet-mapping>
<!-- my secod servmet V2 -->
<servlet>
<servlet-name>webservice</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config/api-web-servlet.xml</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>webservice</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
So for my other XML file, api-web-servlet it's quite the same :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
>
<context:annotation-config/>
<context:component-scan base-package="com.me.project.rest.api" />
<mvc:annotation-driven />
</beans>
for my URL test i use:
http://localhost:8080/sitesApi/v1/mysite?id=1&fields=site.name
and it works but when i try with the other servlet it doesnt :
http://localhost:8080/api/v1/mysite?id=1&fields=site.name
******* Edition*****
#RequestMapping(value = "/v1/mySite", method = RequestMethod.GET)
public #ResponseBody
Object SitesV1( #RequestParam(value = "ajouterstatus", required = false) Integer ajouterstatus,
#RequestParam(value = "monadresse", required = false) String monadresseHttpServletRequest request, HttpServletResponse responseHttp{
try {
appname = request.getHeaders( "Name" ).nextElement().toString();
} catch ( Exception e ) {
return new Result( "", ": AppName is Empty" );
}
So exactly the same thing with the other method
#RequestMapping(value = "/v2/mySite", method = RequestMethod.GET)
public #ResponseBody
Object SitesV2( #RequestParam(value = "ajouterstatus", required = false) Integer ajouterstatus,
#RequestParam(value = "monadresse", required = false) String monadresseHttpServletRequest request, HttpServletResponse responseHttp{
try {
appname = request.getHeaders( "Name" ).nextElement().toString();
} catch ( Exception e ) {
return new Result( "", ": AppName is Empty" );
}
Any idea ??
Thank you
You can use as many Dispatcher Servlets as you want but each one of them will need to be configured with their own xml file.
So, for your servlet named 'api', you must be having the configuration file in place named as: 'api-servlet.xml'.
Now, you need to have 'webservice-servlet.xml' in place for your 'webservice' dispatcher servlet to work.
You can refer to following answers:
How does DispatcherServlet work if we have multiple XML Configuration file?
Multiple application context, multiple dispatcher servlets?

Receiving payload request and displaying it on a webpage using spring

First of all I'm new to Spring and tried my best to get this working. So this is my question.
I have a spring MVC project which is supposed to receive a request payload (JSON request) and display the payload body on a webpage. Please see my project content and the controller class below
#Controller
public class CallbackPayloadController {
public CallbackPayloadController() {
System.out.println("In controller class!!!!");
}
#RequestMapping(value = "/requestreceiver", consumes = "application/json", method = RequestMethod.POST)
public void receivePayload(#RequestBody String payload) {
System.out.println("In the controller method....");
System.out.println("Payload is : " + payload);
}
}
Now if I do a POST to http://localhost:8080/PayloadReceiver/requestreceiver/ using POSTMAN it says HTTP STATUS 404. My Json content that I am posting is
{
"key":"123"
}
My web.xml is as follows
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>PayloadReceiver</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>requestreceiver</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>requestreceiver</servlet-name>
<url-pattern>/requestreceiver.jsp</url-pattern>
<url-pattern>/requestreceiver.html</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
Second question is if I successfully receive the payload, how do I display the payload content on a new webpage?
Try to add the return statement to your method like this:
#RequestMapping(value = "/requestreceiver",consumes="...",method = RequestMethod.POST)
public String receivePayload(...)
...
return "requestreceiver";

Spring Integration : int-http:inbound-gateway with url Path Variables

I am trying to test an Inbound http gatway using Spring Integration int-http:inbound-gateway:
<int-http:inbound-gateway id="correlateOutgoingMessage"
supported-methods="POST" request-channel="toOutCorrelator"
reply-channel="fromOutCorrelator" view-name="/correlateOutgoingMessage"
path="/correlateOut/{origin}/{msgtype}/{priority}"
reply-timeout="50000">
<int-http:header name="origin" expression="#pathVariables.origin" />
<int-http:header name="msgtype" expression="#pathVariables.msgtype" />
<int-http:header name="priority" expression="#pathVariables.priority" />
</int-http:inbound-gateway>
My Web.xml :
<servlet>
<servlet-name>correlateOut</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/intg-schema.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>correlateOut</servlet-name>
<!-- controler/* -->
<url-pattern>/correlateOut/*</url-pattern>
</servlet-mapping>
Using the RestTemplate I am trying to make a POST request to the gateway:
The
uri = "http://localhost:8080/test/correlateOutgoingMessage/{origin}/{msgtype}/{priority}"
String origin = "xxxx";
Integer msgtype = 2333;
Integer priority = 2;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
HttpEntity<?> request = null;
ResponseEntity<String> httpResponse = null;
request = new HttpEntity<Object>(messageContent);
httpResponse = template.exchange(uri, HttpMethod.POST, request,
String.class, getUrlParams(origin, msgtype, priority));
I am alway getting NOT FOUND 404, would you any please give me some hints?
Thank you very much!
First of all you should show the uri which you use to send HTTP request.
From other side if you map servlet to the /correlateOut/* you must not to use it in the target mapping, because all other endpoints are under that context.
So, your path should be path="{origin}/{msgtype}/{priority}"

How to use #RequestMapping headers?

I am studying springmvc. When I use #RequestMapping(value="/helloWorld", headers = "content-type=text/*") and connect to http://localhost:8080/SpringMVC_10100/helloWorld, the following is output in the console:
WARN
org.springframework.web.servlet.PageNotFound
- No matching handler method found for servlet request: path '/helloWorld',
method 'GET', parameters
map[[empty]]
My code is:
#Controller
public class HelloWordController {
private Logger logger = LoggerFactory.getLogger(HelloWordController.class);
#RequestMapping(value="/helloWorld", headers = "content-type=text/*")
public ModelAndView helloWorld() {
logger.debug("jin ru le");
logger.info("The helloWorld() method is use");
ModelAndView view = new ModelAndView();
view.setViewName("/helloworld");
return view;
}
}
web.xml is
<servlet>
<description>This is Spring MVC DispatcherServlet</description>
<servlet-name>SpringMVC DispatchServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>SpringContext</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC DispatchServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Why?
Its most likely the case that /helloworld is not inside the path configured for your dispatcher servlet
e.g. If i have a servlet configured like so:
<servlet>
<servlet-name>BMA</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>BMA</servlet-name>
<url-pattern>/bma/*</url-pattern>
</servlet-mapping>
And i have a controller configured like so:
#RequestMapping(value = "/planner/plan/{planId}/delete", method = RequestMethod.GET)
public ModelAndView deletePlanConfirm(HttpServletRequest request,
#PathVariable("planId") Long planId) {}
Then the request in browsder would be:
http://localhost:8080/bma/planner/plan/1223/delete
Edit:
Also if you have content-type header narrowing on your handler, make sure that content-type haeder is sent in your request.
In the below annotation remove the headers:
#RequestMapping(value="/helloWorld", headers = "content-type=text/*")
to:
#RequestMapping(value="/helloWorld", method = RequestMethod.GET)
or to:
#RequestMapping(value="/helloWorld")
should make it work.

Categories