Static Content with Spring - css

I'm using
<mvc:resources mapping="/resources/**" location="/resources/" />
To handle static content in my SpringMVC app. This works fine. I am able to upload images and retrieve them within the application using the "/resources" url .I want to use an jpeg for a background image in a jsp, so I though I would simply drop the jpeg into the resources folder in my workspace. However, there is no resource folder in my workspace folder anywhere. Where is spring storing these images? How do I get to this folder to add my background image?
as requested 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" xmlns:web="http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringMVCTest</display-name>
<servlet>
<servlet-name>springMVCTest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVCTest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
servlet.xml to clarify everything is configured properly.
<?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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<tx:annotation-driven />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="/"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:maxUploadSize="1000000" />
<bean id="personService" class="PersonServiceImpl" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="/" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
The call to the save image method
saveImage(context.getRealPath("/resources/" + person.getId() + ".jpg"), image);

However, there is no resource folder in my workspace folder anywhere
It should be present in WebContent. If its not there then <mvc:resource> is not being used to serve static content.
How do I get to this folder to add my background image?
Create resources folder under WebContent and put your images into it. Access the images by /resources/foo.jpeg.

Related

LocalContainerEntityManagerFactoryBean hibernate configuration bean is initialized in a loop

I have my hibernate entity manager factory declared in jpa.xml, hazecast configured in hazelcast.xml and I have domain model setup and I have corresponding componentContext.xml present in the domain model project where my entity manager factory class is implemented in it. But the problem I am
facing is that my bean in componentContext.xml is getting intialized in a loop (observed from hibernate.log)
My Web.xml has only com.sun.faces.config.ConfigureListener listenere configured.
My Stack
Spring - 4.3.8
Hibernate - 5.0.10-FINAL
hazelcast-hibernate5 - 1.3.0
JPA.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"
xsi:schemaLocation="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">
<context:property-placeholder location="classpath:dataSources.properties" />
<!-- Default JPA configuration for OpenJPA and Hibernate -->
<!-- Hibernate configuration -->
<bean id="hibernateEntityManagerFactory" abstract="true" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.max_fetch_depth" value="3" />
<entry key="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider" />
<entry key="hibernate.enable_lazy_load_no_trans" value="true" />
<entry key="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />
<entry key="hibernate.current_session_context_class" value="jta" />
</map>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="${dbDialect}" />
</bean>
</property>
</bean>
<alias name="hibernateEntityManagerFactory" alias="entityManagerFactory" />
</beans>
componentContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:cache="http://www.springframework.org/schema/cache" 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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
xmlns:jpa="http://www.springframework.org/schema/data/jpa">
<context:component-scan base-package="com.volvo.myfirstdomain.base />
<context:annotation-config />
<!-- JPA EntityManagerFactory -->
<!-- Based on choice of implementation between OpenJPA and Hibernate, parent attribute in bean should be set. For OpenJPA: parent = "openJpaEntityManagerFactory"
For Hibernate: parent = "hibernateEntityManagerFactory" Here, OpenJPA is chosen as you can see below. -->
<bean id="myDomainEntityManagerFactory" parent="entityManagerFactory">
<property name="persistenceUnitName" value="MYDomainPU" />
<property name="packagesToScan" value="com.volvo.myfirstdomain.entity" />
<property name="jpaProperties">
<props>
<prop key="hibernate.default_schema">DOMAIN_ONE</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect </prop>
<prop key="hibernate.cache.region.factory_class">com.hazelcast.hibernate.HazelcastCacheRegionFactory</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="javax.persistence.sharedCache.mode">ENABLE_SELECTIVE</prop>
</props>
</property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
</beans>
I have tried debugging multiple times but I am not able to figure out why the initialzing is happening multiple times (as if in a loop). Any pointers greatly appreciated!
I finally figured out the reason! There was an additional #ComponentScan annotation specified in the application configuration class which was causing the loop to be triggered.

Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-mvc-crud-demo-servlet.xml]

I am new to spring mvc and facing this issue with session factory
"Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-mvc-crud-demo-servlet.xml]"
I added all required jars to class path but it still exists
here is my spring-mvc-crud-demo-servlet.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.luv2code.springdemo" />
<mvc:annotation-driven/>
<!-- Configuration defining views files -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/customer_db?useSSL=false"/>
<property name="user" value="newuser"/>
<property name="password" value="newuser"/>
<property name="minPoolSize" value="5"/>
<property name="maxPoolSize" value="20"/>
<property name="maxIdleTime" value="3000"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan" value="com.luv2code.springdemo.entity"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.mySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
and this is my web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<web-app>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-crud-demo-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<prop key="hibernate.dialect">org.hibernate.dialect.mySQLDialect</prop>
must be
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
Here you reference a class and this is case sensitiv. So my must be My with uppercase M

Circular view path [index.jsp]: would dispatch back to the current handler URL [/index.jsp] again

It's My Project
enter image description here
It's My spring-mvc.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.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<context:component-scan base-package="com.SpringDemo.Controller"/>
<!-- Thymeleaf Template Resolver -->
<bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML" />
<property name="order" value="1" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<property name="enableSpringELCompiler" value="true" />
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="viewNames" value="thymeleaf/*"/>
<property name="templateEngine" ref="templateEngine" />
</bean>
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="" />
<!--<property name="suffix" value=".jsp" />-->
<property name="order" value="2" />
<property name="viewNames" value="*.jsp" />
</bean>
<!-- 支持上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
</beans>
It's My Controller
#Controller
public class HomeController{
//It's OK
#RequestMapping("/home")
public String showHomePage(Model model){
model.addAttribute("name","spring-mvc");
return "thymeleaf/testTh";
}
//It's WRONG
#RequestMapping("/index")
public ModelAndView test(ModelAndView mv){
mv.addObject("name","erer");
mv.setViewName("index.jsp");
return mv;
}
}
It's My Exception
enter image description here
In's My Web.xml
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<!-- 加载springMVC的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
I want that all requests are first passed through the controller.
And then return to the page
Please import spring-boot-starter-thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
I think the problems may be located on the returned view name. Since the view name is the same as the /index path, so maybe it will be dispatched by spring dispatcher again. Maybe you can try to change the view as another name to have a try.

Tomcat not find the index.jsp when it starting

I have a J2ee application with spring. I have apply some modify at the page but now, when I try to start the server, I have this:
This is the application-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:p="http://www.springframework.org/schema/p"
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-3.0.xsd">
<bean id="lo4gjConfigurator" class="com.springmvcapp.log.LoggerFactory">
<property name="logReInit">
<value>true</value>
</property>
<property name="fileName">
<value>log4j.xml</value>
</property>
</bean>
<context:component-scan base-package="com.springmvcapp.controller" />
<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>
<bean id="simpleUrlMapping" class="com.springmvcapp.security.AccessDecisionUrlMapping">
<property name="alwaysUseFullPath" value="true" />
<property name="mappings">
<props>
<prop key="/index.html">homeController</prop>
<prop key="/registrazione.html">registrazioneController</prop>
</props>
</property>
</bean>
<bean id="homeController" class="com.springmvcapp.controller.HelloWorld">
<property name="methodNameResolver">
<bean
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="defaultMethodName">
<value>loadPage</value>
</property>
<property name="paramName">
<value>method</value>
</property>
</bean>
</property>
</bean>
<bean id="registrazioneController" class="com.springmvcapp.controller.RegistrazioneController">
<property name="methodNameResolver">
<bean
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="defaultMethodName">
<value>loadPage</value>
</property>
<property name="paramName">
<value>method</value>
</property>
</bean>
</property>
</bean>
</beans>
This is the 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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>SpringMVCApp</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springmvcapp</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvcapp</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
This is the jsp file:
I don't know why the tomcat don't find the index.jsp.
Your index.jsp is located in directory "WEB-INF" which cannot be accessed by url. Move it to the root of your application.
Another option is to redirect the first call to a spring controller. Create an index.html for example and add a redirect to it, i.E.:
<meta http-equiv="refresh" content="0; url=/app/">
You have to keep you index.jsp file in public folder i.e. WebContent folder for direct access.

Spring Security + MVC - #Secured - Already declared global-method-security in *servlet.xml

Hope someone could help me.
I am trying to configure Spring Security 3.1 with Spring MVC 3.0.8 but the annotated controllers does not get the access restricted by Spring.
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/Spring/applicationContext-security.xml
/WEB-INF/Spring/applicationContext.xml
</param-value>
</context-param>
<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>
<!-- Sitemash -->
<filter>
<filter-name>sitemesh</filter-name>
<filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>/*</url-pattern>
<!-- <servlet-name>referencia</servlet-name> -->
</filter-mapping>
<!-- Spring Listeners -->
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<error-page>
<error-code>500</error-code>
<location>/erroInterno.jsp</location>
</error-page>
<servlet>
<servlet-name>stc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>stc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:security="http://www.springframework.org/schema/security"
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/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<!-- import the dataSource definition -->
<import resource="applicationContext-dataSource.xml"/>
<!-- Pacote base que sera scaneada por componentes annotados que serao auto-registrados como Spring beans.-->
<context:component-scan base-package="br.com.cielo.portalcontestacao" />
<!-- Ativa a detecao de annotations nas classes -->
<context:annotation-config />
<!-- 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 />
<!-- Recursos utilizados nos imports das páginas -->
<mvc:resources mapping="/resources/**" location="/static/" cache-period="31556926"/>
<!-- Template para uso nos DAOs -->
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
<task:executor id="taskExecutor" pool-size="0-3" queue-capacity="0" rejection-policy="CALLER_RUNS" keep-alive="300"/>
<task:annotation-driven executor="taskExecutor" />
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler">
</bean>
<!-- Configuração de Locale -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="pt_BR" />
</bean>
<!-- Annotação para controle de transações na aplicação -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Indica qual o transaction manager a ser utilizado -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
<property name="nestedTransactionAllowed" value="true"/>
</bean>
<!-- Mensagens do sistema -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="mensagens" />
</bean>
<bean name="stcProperties" class="br.com.cielo.portalcontestacao.service.utils.STCProperties"/>
<bean name="serviceInvoker" class="br.com.cielo.portalcontestacao.service.ServiceInvokerImpl"/>
</beans>
applicationContext-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<http pattern="/static/**" security="none"/>
<http pattern="/" security="none"/>
<http auto-config='true' disable-url-rewriting="true" use-expressions="true">
<intercept-url pattern="/pages/login" access="anonymous or fullyAuthenticated" />
<form-login login-page="/pages/login" />
<session-management session-fixation-protection="newSession">
<concurrency-control max-sessions="1" />
</session-management>
</http>
<beans:bean id='userDetailsService'
class="br.com.cielo.portalcontestacao.security.UserDetailsServiceImpl">
<beans:property name="jdbcTemplate" ref="jdbcTemplate"/>
<beans:property name="namedParameterJdbcTemplate" ref="namedParameterJdbcTemplate"/>
</beans:bean>
<beans:bean id='stcAuthenticationProvider'
class="br.com.cielo.portalcontestacao.security.AuthenticationProviderServiceImpl">
<beans:property name="serviceInvoker" ref="serviceInvoker"/>
<beans:property name="userDetailsService" ref="userDetailsService"/>
</beans:bean>
<authentication-manager erase-credentials="true">
<authentication-provider ref='stcAuthenticationProvider' />
</authentication-manager>
</beans:beans>
stc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- DispatcherServlet application context for web tier. -->
<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:security="http://www.springframework.org/schema/security"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="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-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<!--context:annotation-config/-->
<security:global-method-security secured-annotations="enabled"/>
<mvc:view-controller path="/pages/login" view-name="login"/>
<mvc:view-controller path="/pages/home" view-name="index"/>
<mvc:view-controller path="/pages/acessonegado" view-name="acessoNegado"/>
<!-- Declara as Exceptions a serem tratadas pelo framework -->
<!--bean class="br.com.cielo.portalcontestacao.service.exceptions.GenericException">
<property name="exceptionMappings">
<props>
<prop key="java.lang.Exception">dataAccessFailure</prop>
<prop key="org.springframework.web.servlet.PageNotFound">pageNotFound</prop>
<prop key="org.springframework.dao.DataAccessException">dataAccessFailure</prop>
<prop key="org.springframework.transaction.TransactionException">dataAccessFailure</prop>
</props>
</property>
</bean-->
<!-- Declaracao dos Views Resolvers utilizados na aplicacao -->
<bean class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="0" />
</bean>
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views"/>
<property name="order" value="1" />
</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"/>
<property name="order" value="0" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="mensagens"/>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="10000000" />
</bean>
</beans>
Here is some class that I want the access restricted by Spring Security:
imports ommited
ImportacaoArquivo.java
#Secured("ROLE_SCHEDULE")
#Controller
public class ImportacaoArquivo {
#Secured("ROLE_SCHEDULE")
#RequestMapping(value = "/pages/schedules", method = RequestMethod.GET)
public final ModelAndView exibirPageLinks(final HttpServletRequest request) {
return new ModelAndView("arquivo");
}
}
<security:global-method-security /> should be declared in the same context where beans you want to secure are declared.
Since your controller is declared (by <context:component-scan />) in the root context, <security:global-method-security /> should be declared there as well.
So, this is the information I've gathered from reading different sources:
Your <security:global-method-security /> has to be declared in stc-servlet.xml
<context:component-scan /> for your your controllers has to be declared in stc-servlet.xml. The scanning for the rest of your beans may remain in applicationContext.xml. This would work best if your controllers are contained inside one package and nothing else is there (for instance br.com.cielo.portalcontestacao.controllers).
Also on stc-servlet.xml you need to define <aop:config proxy-target-class="true" />. This instructs Spring to use CGLib to advice methods and classes, and you need that because your controllers do not implement any interface.
Alternative solutions:
Use regular intercept-url to define which endpoints have to be secure.
Use #Secured annotation on your services instead of using it on the controllers.
delete 'final' keyword from the method in your ImportacaoArquivo.java file:
#Secured("ROLE_SCHEDULE")
#RequestMapping(value = "/pages/schedules", method = RequestMethod.GET)
public ModelAndView exibirPageLinks(final HttpServletRequest request) {
return new ModelAndView("arquivo");
}

Resources