I use SpringSession+redis, it can save the session to redis,but I cant't get the session attribute the when i call "${sessionScope.user.name}" in jsp
this is web.xml
<filter>
<filter-name>springSessionRepositoryFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSessionRepositoryFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
this is applicationContext.xml
<!-- spring data redis -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="localhost"/>
<property name="port" value="6379"></property>
<property name="password" value="123456"></property>
<property name="database" value="0"></property>
<property name="usePool" value="true"></property>
</bean>
<bean class="org.springframework.data.redis.core.RedisTemplate" id="redisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
</bean>
<!-- spring session -->
<context:annotation-config/>
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
this is the controller:
#RequestMapping("/login")
public String login(String name, String pwd,HttpSession session){
User user=new User();
user.setName(name);
user.setPwd(pwd);
session.setAttribute("user",user);
return "forward:/success.jsp";
}
#RequestMapping("test")
public String test(HttpSession session){
//there,session.getAttribute("user")=null ???
return "forward:/test.jsp";
}
When i request the project, I can see the session has been saved in Redis
enter image description here
but when I request test.action ,It can't get the Seesion Attribute.
What's wrong?
Related
Versions (SpringBoot is not involved):
Spring: 5.2.16
web-app / servlet API: 4.0
JUnit: 5.8
Spring MVC Testing is not working for controller endpoint that returns ResponseEntity<ReturnStatus>, where ReturnStatus is a POJO with appropriate getters/setters. The exception triggered indicates that JSON conversion is not working for ReturnStatus. My research indicates that the annotation-based Java configuration for the WebApplicationContext is not loaded (and therefore the Jackson JSON converter is not recognized). Curiously, in a non-testing deployment in Tomcat, the controller endpoint works fine, presumably because the web.xml in the war-file is parsed by Tomcat.
QUESTION:
How can I adjust the setup for Spring MVC Test for this application so that the annotation-based Java configuration for the WebApplicationContext is properly loaded? Can this, for example, be done explicitly in the endpoint-test logic (ie, the JUnit test)?
Exception:
14:33:57,765 WARN DefaultHandlerExceptionResolver:199 - Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class com.acme.myapp.io.ReturnStatus] with preset Content-Type 'null']
14:33:57,765 DEBUG TestDispatcherServlet:1131 - Completed 500 INTERNAL_SERVER_ERROR
The Spring MVC app incorporates the following configurations:
test-context.xml, which houses Spring bean-configuration for access to data store:
web.xml, which declares and maps the DispatcherServlet with relevant setup for WebApplicationContext.
Annotation-based configuration in Java implementation of WebMvcConfigurer.
Relevant excerpt from test-context.xml:
<context:component-scan base-package="com.acme.myapp"/>
<jpa:repositories base-package="com.acme.myapp.repos"/>
<context:property-placeholder location="classpath:/application.properties" />
<!-- Data persistence configuration -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${db.showSql}" />
<property name="databasePlatform" value="${db.dialect}" />
<property name="generateDdl" value="${db.generateDdl}" />
</bean>
</property>
<property name="packagesToScan">
<list>
<value>com.acme.myapp.dao</value>
</list>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.user}" />
<property name="password" value="${db.pass}" />
<property name="initialSize" value="2" />
<property name="maxActive" value="5" />
<property name="accessToUnderlyingConnectionAllowed" value="true"/>
</bean>
<!-- Set JVM system properties here. We do this principally for hibernate logging. -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="java.lang.System" />
<property name="targetMethod" value="getProperties" />
</bean>
</property>
<property name="targetMethod" value="putAll" />
<property name="arguments">
<util:properties>
<prop key="org.jboss.logging.provider">slf4j</prop>
</util:properties>
</property>
</bean>
Relevant excerpt from web.xml (where application-context.xml is our production version of test-context.xml):
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>central-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.acme.myapp.MyAppWebAppConfig</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>central-dispatcher</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
Excerpt from Java implementation of WebMvcConfigurer (ie, where we incorporate Jackson JSON converter):
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = { "com.acme.myapp.controllers" })
public class MyAppWebAppConfig implements WebMvcConfigurer
{
private static final Logger logger = LoggerFactory.getLogger(MyAppWebAppConfig.class);
#Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters)
{
logger.debug("extendMessageConverters ...");
converters.add(new StringHttpMessageConverter());
converters.add(new MappingJackson2HttpMessageConverter(new MyAppObjectMapper()));
}
}
The controller endpoint looks like this (where the root is at /patients):
#RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ReturnStatus> readPatient(
#PathVariable("id") long id
)
{
ReturnStatus returnStatus = new ReturnStatus();
returnStatus.setVersionId("1.0");
...
return new ResponseEntity<ReturnStatus>(returnStatus, httpStatus);
}
Using JUnit5 and MockMvc, the endpoint-test looks like this:
#SpringJUnitWebConfig(locations={"classpath:test-context.xml"})
public class PatientControllerTest
{
private MockMvc mockMvc;
#BeforeEach
public void setup(WebApplicationContext wac) {
this.mockMvc = webAppContextSetup(wac).build();
}
#Test
#DisplayName("Read Patient from /patients API.")
public void testReadPatient()
{
try {
mockMvc.perform(get("/patients/1").accept(MediaType.APPLICATION_JSON_VALUE))
.andDo(print())
.andExpect(status().isOk());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Thanks!
Here are some options, possibly not exhaustive:
Per earlier comment, we can simply use <mvc:annotation-driven> directive in test-context.xml. For example:
<bean id="myappObjectMapper" class="com.acme.myapp.MyAppObjectMapper"/>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<constructor-arg ref="myappObjectMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
Effectively, this directive obviates the need for loading MyAppWebAppConfig, as <mvc:annotation-driven> in fact is the XML-equivalent of the annotation #EnableWebMvc in Java.
Implement WebApplicationInitializer so that effectively does in Java what we configure into web.xml. For example:
public class MyAppWebApplicationInitializer implements WebApplicationInitializer
{
#Override
public void onStartup(ServletContext container)
{
XmlWebApplicationContext appCtx = new XmlWebApplicationContext();
appCtx.setConfigLocation("classpath:application-context.xml");
container.addListener(new ContextLoaderListener(appCtx));
AnnotationConfigWebApplicationContext dispatcherCtx = new AnnotationConfigWebApplicationContext();
dispatcherCtx.register(MyAppWebAppConfig.class);
ServletRegistration.Dynamic registration = container.addServlet("central-dispatcher", new DispatcherServlet(dispatcherCtx));
registration.setLoadOnStartup(1);
registration.addMapping("/api/*");
}
}
For this solution, we expunge web.xml from the project; possibly we should parameterize the reference to application-context.xml as well.
Note that when I run JUnit5 tests, it appears that Spring does not instance MyAppWebApplicationInitializer, and that instead, the Spring context loaded for JUnit5 is the one referenced by the #SpringJUnitWebConfig annotation. I therefore recommend co-locating test-related configuration with test-context.xml, and reserving WebApplicationInitializer for production.
I'm sure there are other options, but I've only explored these two approaches.
This is my web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/app-root.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
This is my springmvc-servlet.xml
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:component-scan base-package="com.***.***">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
This is my app-root.xml
<import resource="classpath:spring/app-dao.xml"/>
<import resource="classpath:spring/shiro.xml"/>
<import resource="classpath:spring/app-timer.xml"/>
<import resource="classpath:spring/app-context.xml"/>
This is my app-context.xml
<context:component-scan base-package="com.xinshen.meeting">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
This is my app-datasource.xml
<bean id="adminTxManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="adminTxManager"/>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:spring/mybatis-config.xml"/>
<!--扫描entity包,使用别名-->
<property name="typeAliasesPackage" value="com.xinshen.meeting.model"/>
<property name="mapperLocations" value="classpath*:mappers/*.xml"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<value>
dialect=mysql
</value>
</property>
</bean>
</array>
</property>
</bean>
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.***.***.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
when I add #Transactional to Controller ,transaction it works but Service it does`t work!
the following pic is #Transactional on Service
enter image description here
the following pic is #Transactional on Controller
enter image description here
I really can`t finger it out,Thanks for help!
I think You have to enable transaction using configuration add this annotation #EnableTransactionManagement in a config class
Create a class for configuration :
#Configuration
#ComponentScan(basePackages = { "Your services package or base package" })
#EnableTransactionManagement
public class MyConfig {
}
If your service are not implementing interface, you need to set proxy-target-class="true" in tag tx:annotation-driven.
You also should add #Transactional on the service class, or on the function invoked by spring bean directly.
I have a problem integrating this two technologies.
We have an GWT application integrated with Spring but, additionally to GWT application we need to display HTML files using Thymeleaf for special modules.
The GWT application works well but when I try to run it with Controllers and Thymeleaf enabled this fail.
I've added this to my web.xml to support the Spring Controllers use:
<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/conf/spring/controller-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>
And my controller-context.xml has this beans:
<bean id="uiengineTemplateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/uiengine/target/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
<property name="cacheable" value="false" />
<property name="characterEncoding" value="UTF-8" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolvers">
<array>
<ref bean="uiengineTemplateResolver"/>
</array>
</property>
</bean>
And this at the end:
<context:component-scan base-package="com.enterprise.platform.*.gui" />
There is a way to integrate this two frameworks?
I'll appreciate your help!
Thanks.
I've resolved!
First you need to exclude the main HTML file for GWT from ThymeleafViewResolver so:
controller-context.xml
<bean id="viewResolver" class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="excludedViewNames">
<array>
<value>gwt-project.html</value>
</array>
</property>
</bean>
Allow the static access for the resources of GWT application:
<mvc:resources mapping="/gwt-project/**" location="/gwt-project/" />
Create a Spring Controller with access root method:
MyController.java
#Controller
public class MyController
{
#RequestMapping(value = "/{appBeanId}", method = RequestMethod.GET)
public String root(#PathVariable String appBeanId, Locale locale,
org.springframework.ui.Model model) {
....
}
}
That's it!.
I am trying to use Spring MVC 3 and Hibernate 4.1 to get declarative transaction management, providing an open session for the entire length of the request. I only have one "manager" layer for data access, which directly uses the session. This is annotated with #Transactional, and the session closes upon exiting this layer and I get a lazy load exception in the controller.
So I added the OpenSessionInViewFilter filter, and the logs state that this filter is correctly configured and they also show this filter opening a session. Unfortunately, my manager layer opens and closes its own session anyway, just as before, and I get the same lazy load exception in the controller.
Edit: noted that in my log, I get the filter session open, HibernateTransactionManager session open, HibernateTransactionManager session closed, lazy load exception, then filter session closed. So I know that there is an open session somewhere during the lazy load exception, but the object was loaded in a transaction associated with the other, closed session.
I thought that removing #Transactional from the manager class would remove session management from that layer and let the filter do its job, but then the sessionFactory().getCurrentSession() simply gets a closed session; it doesn't have access to the filter's provided open session.
How can I get access to the OpenSessionInViewFilter's clearly open session?
springapp-servlet.xml
<beans ..
<context:component-scan base-package="springapp.web" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<bean id="userManager" class="springapp.service.SimpleUserManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<import resource="hibernate-context.xml" />
</beans>
web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springapp-servlet.xml</param-value>
</context-param>
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
hibernate-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans ..
">
<context:property-placeholder location="/WEB-INF/hibernate.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${hibernate.connection.driver_class}" />
<property name="url" value="${hibernate.connection.url}" />
<property name="username" value="${hibernate.connection.username}" />
<property name="password" value="${hibernate.connection.password}" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven />
<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributeSource">
<bean class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource" />
</property>
</bean>
<bean id="managerTemplate" abstract="true" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan" value="databeans" />
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
</beans>
manager.java
#Service("userManager")
#Transactional
public class SimpleUserManager implements UserManager {
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
..
controller.java
#Controller
#RequestMapping("/users")
public class UserController {
#Autowired
private UserManager userManager;
..
and my exception, which occurs in the controller, on the first property read of an object loaded in the manager class and passed to that controller:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.LazyInitializationException: could not initialize proxy - no Session
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:119)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
I've been researching this for hours.. all I can find is a mix of solutions using hibernate 3 and grainy explanations on hibernate 4 session/transaction theory without examples.
Any thoughts?
UPDATE: FIXED!
Found this:
Spring MVC OpenSessionInViewInterceptor Not Working
which unfortunately has not helped the OP there, but it helped me. Notably, this:
"it will be better to not import applicationContext.xml in dispatcher-servlet.xml, instead load it using a ContextLoaderListener"
which, applied to my configuration, is exactly everything I have posted above, but instead of
<import resource="hibernate-context.xml" />
in my springapp-servlet.xml, I modified my ContextLoaderListener to:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springapp-servlet.xml, /WEB-INF/hibernate-context.xml</param-value>
</context-param>
and that was all it took for
sessionFactory.getCurrentSession()
to return to me the OSIV-created session. And, in fact, the second session that was being created is no longer, as I found these lovely little log lines:
2012-10-04 14:43:48,743 DEBUG http-8080-1 org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'transactionManager'
2012-10-04 14:43:48,743 TRACE http-8080-1 org.springframework.transaction.support.TransactionSynchronizationManager - Retrieved value [org.springframework.orm.hibernate4.SessionHolder#4146c5c0] for key [org.hibernate.internal.SessionFactoryImpl#12542011] bound to thread [http-8080-1]
2012-10-04 14:43:48,743 DEBUG http-8080-1 org.springframework.orm.hibernate4.HibernateTransactionManager - Found thread-bound Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] for Hibernate transaction
2012-10-04 14:43:48,743 DEBUG http-8080-1 org.springframework.orm.hibernate4.HibernateTransactionManager - Creating new transaction with name [springapp.service.SimpleUserManager.find]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
which show that, outside of my #Transactional service layer, the OSIV-created session was alive and well, and a new transaction was simply started for it.
Hope this helps someone else. I don't even want to think about how many hours I spent working on it.
I am having a trouble mapping a specific URL request to one of the controllers in my project.
the URL is : http://HOSTNAME/api/v1/profiles.json
the war which is deployed is: api.war
the error I get is the following:
[PageNotFound] No mapping found for
HTTP request with URI
[/api/v1/profiles.json] in
DispatcherServlet with name 'action'
The configuration I have is the following: web.xml :
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml,/WEB-INF/applicationContext-security.xml</param-value>
</context-param>
<!-- Cache Control filter -->
<filter>
<filter-name>cacheControlFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<!-- Cache Control filter mapping -->
<filter-mapping>
<filter-name>cacheControlFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring security filter -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<!-- Spring security filter mapping -->
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring Controller -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/v1/*</url-pattern>
</servlet-mapping>
The action-servlet.xml:
<mvc:annotation-driven/>
<bean id="contentNegotiatingViewResolver"
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="favorPathExtension" value="true" />
<property name="favorParameter" value="true" />
<!--
default media format parameter name is 'format'
-->
<property name="ignoreAcceptHeader" value="false" />
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller" />
</constructor-arg>
</bean>
</list>
</property>
</bean>
the application context security:
<sec:http auto-config='true' >
<sec:intercept-url pattern="/login.*" filters="none"/>
<sec:intercept-url pattern="/oauth/**" access="ROLE_USER" />
<sec:intercept-url pattern="/v1/**" access="ROLE_USER" />
<sec:intercept-url pattern="/request_token_authorized.jsp" access="ROLE_USER" />
<sec:intercept-url pattern="/**" access="ROLE_USER"/>
<sec:form-login authentication-failure-url ="/login.html"
default-target-url ="/login.html"
login-page ="/login.html"
login-processing-url ="/login.html" />
<sec:logout logout-success-url="/index.html" logout-url="/logout.html" />
</sec:http>
the controller:
#Controller
public class ProfilesController {
#RequestMapping(value = {"/v1/profiles"}, method = {RequestMethod.GET,RequestMethod.POST})
public void getProfilesList(#ModelAttribute("response") Response response) {
....
}
}
the request never reaches this controller.
Any ideas?
Annotations don't do anything until they are processed. You will need
<context:component-scan base-package="path.to.controllers"/>
as a child of your root "beans" tag in order to get Spring to scan for controllers. Spring will scan for controllers in the base-package and it's descendants.
This tags requires
xmlns:context="http://www.springframework.org/schema/context"
and
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
in your root "beans" tag.