Controller #RequestMapping error URLs - java

My application doesn't work with requestmapping, the request always works with the same method handleRequest, the controller is RestController.java and the URLs redirects to it when has the path /REST2/*, it works well but always with the same method. But the method "update" never works when I send the request to locahost:9080/myapp/REST2/rrr and if I change the URL i.e. localhost:9080/myapp/REST2/XXX also the request is going to handleRequest method.
The RequestMapping doesn't work well, I tried with other solutions but doesn't work..
Do you have any idea?
Restcontroller.java
public class RestController implements Controller{
private Configuration config;
private static String[] requestHeaders = {"accept", "pragma"};
private static String[] responseHeaders = {};
public void setConfig(Configuration config)
{
this.config = config;
}
#RequestMapping(value="/rrr") public ModelAndView update(HttpServletRequest request, HttpServletResponse response) throws Exception
{
String asset_name = request.getParameter("assetid");
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
String values = "Working"+ asset_name;
response.setContentLength(values.length());
PrintWriter out = response.getWriter();
out.println(values);
return null;
}
#RequestMapping(value ="/home")public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception
{
Arrays.sort( requestHeaders );
Arrays.sort( responseHeaders );
String values;
String asset_name = request.getParameter("assetid");
...
response.setContentLength(values.length());
//
PrintWriter out = response.getWriter();
out.println(values);
return null;
}}
spring-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- View resolver. Prepends prefix /WEB-INF/jsp and suffix .jsp to view names. -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Always use full path when mapping URLs to bean names. -->
<bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
</bean>
<!-- Home page. -->
<bean name="/home.app" class="com.fatwire.wem.sample.HomeController">
<property name="config" ref="config" />
</bean>
<!-- Installation page. -->
<bean name="/install.app" class="com.fatwire.wem.sample.InstallController">
<property name="config" ref="config" />
</bean>
<!-- Layout page. -->
<bean name="/layout.app" class="com.fatwire.wem.sample.LayoutController" />
<!-- REST proxy page. -->
<bean name="/REST/**" class="com.fatwire.wem.sample.ProxyController">
<property name="config" ref="config" />
</bean>
<!-- REST proxy page. -->
<bean name="/REST2/**" class="com.fatwire.wem.sample.RestController">
<property name="config" ref="config" />
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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" >
<!-- Bootstrap Spring configuration to be used by both SSO and MVC -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- WEM SSO Listener -->
<listener>
<listener-class>com.fatwire.wem.sso.SSOListener</listener-class>
</listener>
<!-- Configure Spring MVC -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.app</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/REST/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/REST2/*</url-pattern>
</servlet-mapping>
<!-- WEM SOO Filter -->
<filter>
<filter-name>WEM SSO Filter</filter-name>
<filter-class>com.fatwire.wem.sso.SSOFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>WEM SSO Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Request AJAX
function load_form(data){
var asset_id = data;
$.post('REST2/home', {
assetid : data,
}, function(responseText) {
alert(responseText);
});
}
function update_form(){
var asset_id = "XXX";
$.post('REST2/rrr', {
assetid : asset_id,
}, function(responseText) {
alert(responseText)
});

Try to add #Controller and #RequestMapping annotations to RestController classlike this:
#Controller
#RequestMapping(value="/REST2")
public class RestController implements Controller{
And add method=RequestMethod.POST the #RequestMapping of methods like this:
#RequestMapping(value ="/home", method=RequestMethod.POST)
...
#RequestMapping(value ="/rrr", method=RequestMethod.POST)

Related

Controller method not getting called in spring mvc

I am modifying on a project that I found on a particular site.
Issue is when I am running the project on server ,the home.jsp page gets displayed which contains a US map . I have made the map clickable .When I am clicking on the map state .The new URL generated is localhost:7001/SpringMVCAngularJS/home.jsp?statechoice=ME .As per spring mvc logic , the getUSCity() method should be called . But it is not getting called . Even if I am hitting just localhost:7001/SpringMVCAngularJS/home.jsp ,its not getting called .
Whereas if I hit localhost:7001/SpringMVCAngularJS/springAngularJS.web ,the particular method is called . Could you let me know if I am missing any mapping or so .
#Controller
public class SpringMVCController {
#Autowired
Top10LanesService lanesService;
#RequestMapping(value = "/angularJS.web", method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
return "Home";
}
#RequestMapping(value = "/springAngularJS.web", method = RequestMethod.GET, produces = { "application/xml",
"application/json" })
public #ResponseBody List<LmWebShipment> getTop10Lanes() {
List<LmWebShipment> al = new ArrayList<LmWebShipment>();
// Top10LanesDAOImpl top10LanesDaoImpl = new Top10LanesDAOImpl();
al = lanesService.getTop10Lanes();
return al;
}
// Called on Click of US state
#RequestMapping(value = "/home.web", method = RequestMethod.GET, produces = { "application/xml",
"application/json" })
#ResponseBody
public void getUSCity(#PathVariable("statechoice") String statechoice) {
System.out.println("In getUSCity" + statechoice);
}
}
I have something like this in my home.jsp file .
<area shape='polygon' coords='489,52,502,31,513,32,518,54,490,71' href='home.jsp?statechoice=ME' target="right" alt='Maine'>
Dispatcher-servlet.xml
<context:property-placeholder location="classpath:database/database.properties"/>
<context:component-scan base-package="com.javahonk.controller" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/Views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- bind messages.properties -->
<bean class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property name="basename" value="messages/messages" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="top10LanesDAO" class="com.javahonk.DAO.Top10LanesDAOImpl" />
<bean id="top10LanesService" class="com.javahonk.services.Top10LanesServiceImpl" />
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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_2_5.xsd"
version="2.5">
<display-name>Archetype Created Web Application</display-name>
<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>*.web</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>angularJS.web</welcome-file>
</welcome-file-list>
<display-name>SpringAngularJS</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
According to path variable concept in spring it should be as follows.you are missing the path variable in the url
#RequestMapping(value = "/home.web/{statechoice}", method = RequestMethod.GET, produces = { "application/xml",
"application/json" })
#ResponseBody
public void getUSCity(#PathVariable("statechoice") String statechoice) {
System.out.println("In getUSCity" + statechoice);
}
And the url you should hit is localhost:7001/SpringMVCAngularJS/home.web/ME according to the spring syntax.where ME is the value that you will get in state choice.

GET request processed by wrong DispatcherServlet (spring, tiles2, thymeleaf)

I decided to move my authorization functionality to another controller, however this caused some issues for me. Mainly, my callback controller cannot forward the GET request to the appropriate dispatcher servlet
DispatcherServlet with name 'Auth' processing GET request for [/user/username] (this should be 'Dashboard' dispatcher servlet)
My view layer is making use of spring, tiles 2, and thymeleaf integration. I have found this comment on stackoverflow, which shed some light on my situation. https://stackoverflow.com/a/13406096/2276284
"Secondly, when using Spring + Tiles, and returning some JSP in your tiles definition, it is treated as an internal forward request, and handled by the same servlet as the original request."
I found this stackoverflow comment as well, but it did not work for me. https://stackoverflow.com/a/17232532/2276284 Suggesting returning a new ModelAndView, or using the HttpServletResponse to redirect.
How can I successfully redirect to another controller/view?
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="pue" version="3.1">
<!-- webapp properties -->
<display-name>PUE</display-name>
<description>Personal User Engagement for Instagram</description>
<!-- session listener -->
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<!-- root context -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/app-context.xml</param-value>
</context-param>
<!-- spring security filter -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- custom redirect filter -->
<filter>
<filter-name>pueUsernameAuthFilter</filter-name>
<filter-class>abnd.pue.auth.service.impl.PUEUsernameAuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>pueUsernameAuthFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- servlet config -->
<servlet>
<servlet-name>Auth</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/servlets/auth-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>IgOauth</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/servlets/igoauth-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>Dashboard</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/servlets/dashboard-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- servlet mapping config -->
<servlet-mapping>
<servlet-name>Auth</servlet-name>
<url-pattern>/logout</url-pattern>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>IgOauth</servlet-name>
<url-pattern>/ig/oauth/callback</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Dashboard</servlet-name>
<url-pattern>/user/{username}</url-pattern>
<url-pattern>/user/{username}/profile</url-pattern>
<url-pattern>/user/{username}/assets</url-pattern>
</servlet-mapping>
<!-- mime types -->
<mime-mapping>
<extension>ico</extension>
<mime-type>image/x-icon</mime-type>
</mime-mapping>
</web-app>
spring-thymeleaf-tiles.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- thymeleaf view resolvers with tiles integration -->
<bean id="tilesConfigurer" class="org.thymeleaf.extras.tiles2.spring4.web.configurer.ThymeleafTilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles/tiles.xml</value>
</list>
</property>
</bean>
<!-- template resolver -->
<bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/tiles/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
<property name="characterEncoding" value="utf-8" />
<property name="cacheable" value="false" />
</bean>
<!-- template engine -->
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<property name="additionalDialects">
<set>
<bean id="tilesDialect" class="org.thymeleaf.extras.tiles2.dialect.TilesDialect" />
</set>
</property>
</bean>
<!-- tiles view resolver -->
<bean id="tilesViewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="viewClass" value="org.thymeleaf.extras.tiles2.spring4.web.view.ThymeleafTilesView" />
<property name="templateEngine" ref="templateEngine" />
<property name="characterEncoding" value="utf-8" />
<property name="order" value="1" />
</bean>
</beans>
IgOauthController
package abnd.pue.ig.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import abnd.pue.ig.service.intf.IgOauthService;
#Controller
public class IgOauthController {
#Autowired
private IgOauthService igOauthService;
private static final Logger logger = LoggerFactory.getLogger(IgOauthController.class);
/**
*
* #param request
* #return String
* #throws IOException
*/
#RequestMapping(value="/ig/oauth/callback")
public ModelAndView igCallback(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
// get code parameter
String code = request.getParameter("code");
// attempt to get user name from callback
String username = igOauthService.processCallbackRequest(request, session, code);
// if username isn't empty redirect to user page
if (!username.isEmpty()) {
logger.info("username set: " + username);
return new ModelAndView ("redirect:/user/" + username);
}
logger.info("no username set");
// otherwise return to index TODO error display
return new ModelAndView("redirect:/");
}
}
Alright, thanks for the help guys. So, the issue was that I could not redirect my view away from the default DispatcherServlet. I was also using invalid url patterns in my web.xml, while trying to create dynamic urls.
The answer was restructuring the wiring of my servlet paths, and changing the default servlet from Auth, to Dashboard. I also implemented UrlRewriteFilter to redirect all traffic from root context ("/") to "/login"
Here are the affected changes.
web.xml
<!-- servlet mapping config -->
<servlet-mapping>
<servlet-name>Auth</servlet-name>
<url-pattern>/login</url-pattern>
<url-pattern>/logout</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>IgOauth</servlet-name>
<url-pattern>/ig/oauth/callback</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Dashboard</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
IgOauthController
#Controller
#RequestMapping(value = "/ig/oauth")
public class IgOauthController {
#Autowired
private IgOauthService igOauthService;
private static final Logger logger = LoggerFactory.getLogger(IgOauthController.class);
/**
*
* #param request
* #return String
* #throws IOException
*/
#RequestMapping(value="/callback")
public void igCallback(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
// get code parameter
String code = request.getParameter("code");
// attempt to get user name from callback
String username = igOauthService.processCallbackRequest(request, session, code);
// if username isn't empty redirect to user page
if (!username.isEmpty()) {
logger.info("username set: " + username);
response.sendRedirect("/" + username + "/dashboard");
return;
}
logger.info("no username set");
// otherwise return to index TODO error display
response.sendRedirect("/login");
return;
}
}
DashboardController
#Controller
#RequestMapping(value = "/{username}")
public class DashboardController {
#RequestMapping(value = "/dashboard", method=RequestMethod.GET)
public ModelAndView userDashboard() throws InstagramException {
...
}
#RequestMapping(value = "/profile", method=RequestMethod.GET)
public ModelAndView userProfile() throws InstagramException {
...
}
#RequestMapping(value = "/assets", method=RequestMethod.GET)
public ModelAndView userAssets() throws InstagramException {
...
}
}

404 Error on Google App Engine Java Production

I have been working with Google App Engine for last 3 years but never faced any such issue before. I have created a project using Spring-4 and Objectify.
The issue I am facing is that on local all URLs are working fine, but when I am deploying the same to the appspot I am getting 404 errors on the URLs which needs to return the JSP pages, although the URL which should return the JSON or XML response those URL are working fine.
Appengine logs are also not providing any relevant information. I cannot understand just one thing that if it running fine locally why is it not working on appspot.
Following are my configuration files.
appengine-web.xml
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>swissinfos</application>
<version>2</version>
<threadsafe>true</threadsafe>
<system-properties>
<property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
</system-properties>
<sessions-enabled>true</sessions-enabled>
</appengine-web-app>
applicationContext.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />
<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
For example #Controller and #Service. Make sure to set the correct base-package-->
<context:component-scan base-package="com.lumin.mytalk." />
<!-- Configures the annotation-driven Spring MVC Controller programming model.
Note that, with Spring 3.0, this tag works in Servlet MVC only! -->
<mvc:annotation-driven />
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang"></property>
</bean>
</mvc:interceptors>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>WEB-INF/common.properties</value>
</list>
</property>
</bean>
<bean id="converter" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.lumin.mytalk.common.util.DozerConverter">
<property name="mapper">
<bean class="org.dozer.spring.DozerBeanMapperFactoryBean">
<property name="mappingFiles">
<value>/WEB-INF/classes/dozer/dozer-bean-mappings.xml</value>
</property>
</bean>
</property>
</bean>
</list>
</property>
</bean>
</beans>
spring-servlet.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.lumin.mytalk." />
<!-- Application Message Bundle -->
<bean class="org.springframework.context.support.ReloadableResourceBundleMessageSource" id="messageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
<filter>
<filter-name>ObjectifyFilter</filter-name>
<filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ObjectifyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/jsp/error.jsp</location>
</error-page>
<welcome-file-list>
<welcome-file>jsp/index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>SystemServiceServlet</servlet-name>
<servlet-class>com.google.api.server.spi.SystemServiceServlet
</servlet-class>
<init-param>
<param-name>services</param-name>
<param-value/>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SystemServiceServlet</servlet-name>
<url-pattern>/_ah/spi/*</url-pattern>
</servlet-mapping>
</web-app>
API Controller Sample
#Controller
public class CategoryController extends AbstractGenericController{
#Autowired
private CategoryService categoryService;
#ResponseBody
#RequestMapping(value = Path.Url.API + Path.Url.CATEGORY + Path.OperationUrl.CREATE, method = RequestMethod.POST, produces = {"application/json", "application/xml" })
public Object create(#RequestBody Category category) {
Category isExisting = categoryService.getCategoryByName(category.getCategoryName());
if (isExisting == null) {
Long id = categoryService.createWithID(category);
return new Response(null, STATUS.SUCCESS, "Category created successfully. Id :" + id);
}else{
return new Response(null, STATUS.FAILURE, "Category already exist. Please use update category function.");
}
}
}
Web Controller Sample
#Controller
public class LoginLogoutController {
#RequestMapping(value = Path.Url.LOGIN)
public String loginPage(#RequestParam(value = "error", required = false) boolean error, #RequestParam(value = "maidID", required = false) String maidID, ModelMap map) {
if (error == true) {
map.put("error", "You have entered an invalid username or password!");
}if( maidID != null && !maidID.equals("")){
map.addAttribute("maidID", maidID);
}
if((error == true) && (maidID != null && !maidID.equals(""))){
map.put("error", "You have entered an invalid username or password!");
map.addAttribute("maidID", maidID);
}
return Path.Jsp.LOGIN_PAGE;
}
}
GAE Log Entry
2014-09-04 13:08:27.302 / 404 44ms 0kb Mozilla/5.0 (Windows NT 6.1; rv:35.0) Gecko/20100101 Firefox/35.0 module=default version=2
123.63.241.35 - - [04/Sep/2014:00:38:27 -0700] "GET / HTTP/1.1" 404 256 - "Mozilla/5.0 (Windows NT 6.1; rv:35.0) Gecko/20100101 Firefox/35.0" "swissinfos.appspot.com" ms=44 cpu_ms=87 cpm_usd=0.000029 app_engine_release=1.9.10 instance=00c61b117c9c5e35c6e16583e442bfebd62dc8f0

Spring 3 MVC - Url mapping not found (404) in production

My app works fine on local tomcat 7 but on the prod tomcat 7 only index url ("/") and resources urls works, other urls are not found, "/login" for example.
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
<!-- FreeMarker Config -->
<beans:bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<beans:property name="templateLoaderPath" value="/WEB-INF/views/" />
</beans:bean>
<!-- FreeMarker View Resolver -->
<beans:bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<beans:property name="cache" value="true" />
<beans:property name="prefix" value="" />
<beans:property name="suffix" value=".html" />
</beans:bean>
<context:component-scan base-package="com.x.y" />
</beans:beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Trying to resolve I changed the servlet-mapping from <url-pattern>/</url-pattern> to <url-pattern>/*</url-pattern> and I got no success, but it started to find the urls if I put the suffix ".jsp", eg: /login.jsp.
Can anyone help me understand why the tomcat is waiting this ".jsp" suffix? I'm not even using jsp in my app :s
Controller sample:
#Controller
public class Application extends BaseController {
//...
#RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Model model, HttpSession session) {
//..
return "application/index";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, HttpSession session) {
//..
return "application/login";
}
//...
}
Thanks.
Sounds like you might have apache sitting in front of tomcat in your production environment, and it is only passing through certain url's, eg: *.jsp
Alternatively, it could be a firewall blocking certain URL's.

How does Spring resolve views?

I've been having a little trouble with View Resolution under Spring 2.5.5. Basically I'm just trying to show my view with a message from the controller passed in. The issue comes when the Controller returns the ModelAndView but the DispatcherServelt says it can't find a Handler.
All the files seem to be in the correct place. I think the issue is that Spring can't resolve the view. From what I've seen I'm using the InternalResourceResolver correctly. I'm just at a loss as to why it is failing.
Once I've made a request this is whats in the catalina.out log:
Feb 8, 2010 3:27:24 PM com.madebymn.newsExample.web.IndexController handleRequest
INFO: Handling a Request: /index.jsp
Feb 8, 2010 3:27:24 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/newsExample/WEB-INF/jsp/index.jsp] in DispatcherServlet with name 'catchAll'
Here's my web.xml:
<web-app 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>A News Example</display-name>
<description>A News Example</description>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-jdbc.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>catchAll</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>catchAll</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>jsp/index.jsp</welcome-file>
</welcome-file-list>
Here's the Servlet XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean name="indexController" class="com.madebymn.newsExample.web.IndexController" />
<bean name="authorController" class="com.madebymn.newsExample.web.AuthorController">
<constructor-arg>
<ref bean="authorService" />
</constructor-arg>
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/index.jsp">indexController</prop>
<prop key="/author/*">authorController</prop>
</props>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
And here's my IndexController Class:
public class IndexController implements org.springframework.web.servlet.mvc.Controller
{
protected final Log logger = LogFactory.getLog(getClass());
#Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
logger.info("Handling a Request: " + request.getServletPath());
ModelAndView modelAndView = new ModelAndView("index");
modelAndView.addObject("message", "someMessage");
return modelAndView;
}
}
The problem is that you mapped your DispatcherServlet as *.jsp, when views are JSPs too. Try to map DispatcherServlet to something different, like *.html

Categories