maven and spring mvc is not working? - spring

I'm trying to build an application using Spring MVC and Maven 3.0 within Eclipse using the webapp. I'm not able to get to the initial page, or navigate to any other pages from there w/out getting a 404 error. Please let me know if there's something I'm missing. Thanks!
mvc-dispatcher.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:jdbc="http://www.springframework.org/schema/jdbc" 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/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="se.guards.controller" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
<context:annotation-config />
<!-- show pictures -->
<mvc:default-servlet-handler />
<!-- also add the following beans to get rid of some exceptions -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>mymessages</value>
</list>
</property>
</bean>
web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.js.resource.ResourceServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-dispatcher-servlet.xml,
/WEB-INF/spring-database.xml,
</param-value>
</context-param>
<!-- Spring Security -->
<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>
database.xml
<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-3.0.xsd">
<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="password" />
</bean>
userController.java
package se.guards.controller;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import se.datalayer.guards.service.UserService;
import se.guard.User;
#Controller
#RequestMapping(value="/")
public class UserController
{
#SuppressWarnings("unused")
#Autowired
private UserService userService;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String findAllUsers(Model model){
Collection<User> userList= new ArrayList<User>();
model.addAttribute("users", userList);
return "showallusers";
}
}
showallusers.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4 /loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>found users</title>
</head>
<body>
<table>
<c:forEach var="allusers" items="${users}">
<tr>
<td>${allusers.firstname}</td>
<td>${allusers.lastname}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Answer to the questions:
This is the code I'm using.
The #Controller annotation must be there.
As I said before I get :
HTTP Status 404 - /guard_weblayer/ type Status report message /guard_weblayer/
description The requested resource (/guard_weblayer/) is not available.
Apache Tomcat/7.0.25
I use a restfule design, a domainlayer, datalayer and weblayer. Can it effecting the weblayer?

You might want to start over and use an example from springbyexample. It contains everything you need in a understandable fashion (and its in maven as well.)
Most likely that's easier than debugging the current code.

Related

Spring not accessing JSP inside /WEB-INF/jsp/ folder

I am new to Spring MVC and developing an application. I developed a project with the help of Spring MVC Tutorial.Initially, it was working. But as soon as I upgraded my project with Hibernate 4 and Spring 4. It stopped working. Whenever, I am invoking any \WEB-INF\jsp, I am getting 404 Error.
Files
LoginController
public class LoginController {
#RequestMapping(value="/login", method=RequestMethod.GET)
public ModelAndView showLoginPage(String path, ModelMap model){
ModelAndView mv = new ModelAndView("login");
model.addAttribute("welcome to Flight Services", "welcomeMessage");
return mv;
}
}
Spring-servlet.xml
<beans ......-mvc-4.0.xsd">
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:annotation-config/>
<mvc:annotation-driven />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties">
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}"
p:username="${jdbc.username}"
p:password="${jdbc.password}">
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
web.xml
<display-name>AirportService</display-name>
<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>
<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>
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#include file="/WEB-INF/jsp/include.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<c:redirect url="/home" />
</body>
</html>
Now everytime, I am launching my index page. I am getting this error
org.apache.jasper.JasperException: /index.jsp (line: 3, column: 5) File "/WEB-INF/jsp/include.jsp" not found
org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:42)
org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:443)
org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:133)
org.apache.jasper.compiler.Parser.processIncludeDirective(Parser.java:322)
org.apache.jasper.compiler.Parser.parseIncludeDirective(Parser.java:357)
org.apache.jasper.compiler.Parser.parseDirective(Parser.java:467)
org.apache.jasper.compiler.Parser.parseFileDirectives(Parser.java:1779)
org.apache.jasper.compiler.Parser.parse(Parser.java:135)
org.apache.jasper.compiler.ParserController.doParse(ParserController.java:242)
org.apache.jasper.compiler.ParserController.parseDirectives(ParserController.java:119)
org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:193)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:373)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:646)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
You are trying to load some file "/WEB-INF/jsp/include.jsp", that does not exist. In your index.jsp file you have the line:
<%#include file="/WEB-INF/jsp/include.jsp" %>
According to the error logs, this file does not exist. Are you sure it is in the correct directory?
Anyways, I downgraded spring and Hibernate versions to 3.x and it is working. Seems like I am missing a trick here with version 4.
If i am correct, your index.jsp is outside your WEB-INF and the resource you are trying to access is inside WEB-INF. Remember that the resources outside your WEB-INF (like images, HTMLs and other static HTML stuff) cannot access the content present in WEB-INF.
So you cannot do <%#include file="/WEB-INF/jsp/include.jsp" %>
You can do this:
<%#include file="include.jsp" %> where both include.jsp and index.jsp are in the same location within or outside WEB-INF.
(Optional) In your web.xml
replace <url-pattern>/</url-pattern> to <url-pattern>*.htm</url-pattern> .htm can be replaced with any extension that you are interested in

Authentication is not happening in spring security, directly going to the authenticated page

My security xml is ::
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<security:http auto-config="true">
<security:intercept-url method="POST" pattern="/admin**" access="ROLE_USER" />
<security:http-basic />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="user" password="pass" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
I am using spring-security 3.2.xsd. In this application it should prompt for login while accessing the /admin pages. But it is directly going to the /admin pages without the authentication.
Please specify me where i am wrong.
My dispatcher servlet :::
<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"
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">
<context:component-scan base-package="com.suva.*" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
My web.xml is::::
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- Loads Spring Security config file -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<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>
</web-app>
My controller class ::
*
package com.suva.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class HelloController {
#RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
public ModelAndView welcomePage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Hello World");
model.addObject("message", "This is welcome page!");
model.setViewName("hello");
return model;
}
#RequestMapping(value = "/admin**", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Hello World");
model.addObject("message", "This is protected page!");
model.setViewName("admin");
return model;
}
}
The JSP files::
hello.jsp ::
*
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page session="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Title : ${title}</h1>
<h1>Message : ${message}</h1>
</body>
</html>
*
admin.jsp
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%#page session="true"%>
<html>
<body>
<h1>Title : ${title}</h1>
<h1>Message : ${message}</h1>
<c:if test="${pageContext.request.userPrincipal.name != null}">
<h2>Welcome : ${pageContext.request.userPrincipal.name}
<a href="<c:url value="/j_spring_security_logout" />" > Logout</a></h2>
</c:if>
</body>
</html>
Thats it nothing else.. please help me find out where i am wrong
The problem can be solved simply by changing the following in your web.xml
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name >
<url-pattern>/*</url-pattern>
</filter-mapping>

Not able to run spring application using XML configuration

I am new to spring, trying to run the Spring application through XML configuration, but i am not getting any error in console. But the application is not running and i am getting the 404 error. I didn't add the servlet-api jar in WEB-INF/lib. Can anyone please help me? Thanks in advance.
package com.raistudies.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HelloWorldAction extends AbstractController {
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
System.out.println(" helloworld... ");
ModelAndView mav = new ModelAndView();
mav.setViewName("hello");
mav.addObject("helloMessage", "Hello World from My First Spring 3 mvc application with xml configuration...");
return mav;
}
}
hello.jsp - WEB-INF/jsp/
<html>
<head>
<title>Hello World with spring 3 MVC XML configuration</title>
</head>
<body>
<h1>Welcome! Spring MVC XML configuration is working well</h1>
${helloMessage}
</body>
</html>
index.jsp - WEB-INF
<html>
<head>
<title>rai studies</title>
</head>
<body>
Welcome...
<br>Click here to check the output :-)
</body>
</html>
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_3_0.xsd"
id="WebApp_ID_1" version="3.0">
<display-name>HWEWS3MVCIEA</display-name>
<servlet>
<servlet-name>SpringMVCDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVCDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
app-config.xml
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<bean name="/hello.htm" class="com.raistudies.action.HelloWorldAction" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
libraries under the WEB-INF/lib
commons-logging-1.1.2.jar
jstl-1.2.jar
log4j-1.2.16.jar
spring-aspects-3.2.5.RELEASE.jar
spring-beans-3.2.5.RELEASE.jar
spring-context-3.2.5.RELEASE.jar
spring-core-3.2.5.RELEASE.jar
spring-expression-3.2.5.RELEASE.jar
spring-web-3.2.5.RELEASE.jar
spring-webmvc-3.2.5.RELEASE.jar
supportingLibrary under WEB-INF/supportingLibrary
servlet-api-2.5.jar
Your bean definition of the Action is not correct. You have to define a controller bean with some valid name like:
<bean name="helloWorldController" class="com.raistudies.action.HelloWorldAction" />
Then you need to add the url mapping definition to your configuration to map requests to the defined controller.
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/hello.htm">helloWorldController</prop>
</props>
</property>
</bean>

Spring-security does not work properly

The application is supposed to only give access to ROLE_ADMIN users to /secret addresses but it does not give access to anyone (either authorized or non authorized ones), another problem is that even when I enter a wrong username and password it allows to sign in and does not redirect to error.page.
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
<context-param>
<param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>
<listener>
<listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/medics-security.xml
/WEB-INF/login-service.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>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
medics-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns='http://www.springframework.org/schema/security'
xmlns:beans='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-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd'>
<beans:import resource='login-service.xml'/>
<http auto-config="true" access-denied-page="/error.jsp">
<intercept-url pattern="/register*" access="ROLE_ADMIN" />
<intercept-url pattern="/secret*" access="ROLE_ADMIN" />
<form-login login-page="/login.html" authentication-failure-url="/login?error=true"/>
<remember-me/>
<logout/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="secret" authorities="ROLE_ADMIN"/>
<user name="user" password="secret" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
applicationContext.xml
<?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'
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'>
<context:component-scan base-package='com.myproject'/>
<bean id='internalResourceResolver'
class='org.springframework.web.servlet.view.InternalResourceViewResolver'>
<property name='prefix' value='/Web Pages/'/>
<property name='suffix' value='.jsp'/>
</bean>
<bean
class='org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping'/>
<bean class='org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter'/>
<bean id='placeholderConfig'
class='org.springframework.beans.factory.config.PropertyPlaceholderConfigurer'/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
</beans>
j_spring_security_check.java
public class j_spring_security_check {
public String execute(){
System.out.append("here in spring check.java");
return "SUCCESS";
}
}
struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- Configuration for the default package. -->
<constant name="struts.action.extension" value="html"/>
<constant name="struts.enable.SlashesInActionNames" value="true"/>
<package name="default" namespace="/" extends="struts-default">
<result-types>
<result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult"/>
</result-types>
<action name="*">
<result type="tiles">{1}</result>
</action>
<action name="j_spring_security_check"
class="com.myproject.struts.j_spring_security_check">
<result name="SUCCESS" type="tiles">register</result>
</action>
</package>
</struts>
register.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>secret page</title>
</head>
<body>
<p>register</p>
secret
</body>
</html>
Try to remove this code:
<action name="j_spring_security_check"
class="com.myproject.struts.j_spring_security_check">
<result name="SUCCESS" type="tiles">register</result>
</action>
from struts.xml. Normally you do not need to handle this URL. Spring Security has built-in filter responsible for processing of credentials.
Try to replace your
<intercept-url pattern="/secret*" access="ROLE_ADMIN" />
pattern by
<intercept-url pattern="/secret.jsp*" access="ROLE_ADMIN" />
if you have single secret.jsp page.

Spring Security Method Security Annotations

Recently, I have begun a bit of a personal project, and I decided to implement Spring Security. I have attempted to do so before, but I had no better luck that time than I am now. I got around the problem then, but that method (accessing the security context directly from the code and checking the string of roles it contains for the current user) feels like a hack, and I would like to get it right this time.
Right now I have Spring Security MOSTLY functioning, as far as I know...I can attempt to go to a page with a role-based redirect, and it will redirect me to the login page. I can log in with good or bad information and be sent to the proper location. What I cannot do, what I have never managed to do, is get the #Secured or #PreAuthorize annotation to function as I would hope.
Let me try to explain (code will follow). My welcome/login page is index.jsp and, when you log in, Spring Security sends you to login.html which is where I have a method in my LoginController class mapped. Inside that method, I try to call a large set of other methods: none of this is supposed to be final, I am just trying to get prove to myself that things are running.
I call two methods that are secured by #Secured, and two methods that are secured by #PreAuthorize, one "ROLE_ADMIN" and one "ROLE_USER" each. The account that I am logging into only has the ROLE_USER authority. This being the case, I would expect to get redirected to my accessdenied.jsp page as per having set that as the target of my Spring Security's access-denied-page attribute. What I do not expect, and what I am seeing, is that every method is successfully called and run when I log in.
I have (at least attempted to) follow the tutorials. I have spent days on Google, reading everything that I can find. I have merged my security context into my context, and everything else that came to my attention as a potential solution. I apologize if I have been a mite long-winded, but I would rather provide too much information than too little. To that end, the following is my code:
index.jsp
<html>
<body>
<form action="j_spring_security_check" method="POST">
<label for="j_username">Name:</label>
<input id="j_username" type='text' name='j_username' />
<br />
<label for="j_password" class="passwordField">Password:</label>
<input id="j_password" type='password' name='j_password' />
<br />
<input id="proceed" type="submit" value="Submit" />
</form>
</body>
</html>
LoginController.java
package cribbage.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.jdbc.core.JdbcTemplate;
import cribbage.database.entity.Test;
#Controller
public class LoginController {
#Autowired
JdbcTemplate t;
#RequestMapping(value = "/login")
public ModelAndView login(HttpServletRequest request) {
test();
test2();
test3();
test4();
return new ModelAndView("test.jsp");
}
#Secured("ROLE_ADMIN")
public void test(){
System.out.println("Test One");
}
#Secured("ROLE_USER")
public void test2(){
System.out.println("Test Two");
}
#PreAuthorize("hasRole('ROLE_ADMIN')")
public void test3(){
System.out.println("Test Three");
}
#PreAuthorize("hasRole('ROLE_USER')")
public void test4(){
System.out.println("Test Four");
}
}
web.xml
<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">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<display-name>Spring Security Tutorial Application</display-name>
<!-- - Location of the XML file that defines the root application context
- Applied by ContextLoaderListener. -->
<context-param>
<description>Spring context file</description>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/applicationContext-security.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>
<!-- - Provides core MVC application controller. See bank-servlet.xml. -->
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/applicationContext-security.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-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/aop
http://www.springframework.org/schema/aop/spring-aop.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">
<context:property-placeholder location="classpath:*.properties" />
<mvc:annotation-driven />
<!-- Which packages to scan when looking for beans defined with #Component -->
<context:component-scan scoped-proxy="targetClass"
base-package="cribbage.controller
cribbage.database.dao
cribbage.database.entity" />
<context:annotation-config />
<!-- Turn on AspectJ #Configurable support -->
<!-- Turn on #Autowired, #PostConstruct etc support -->
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<!-- Add Transaction support -->
<!-- Use #Transaction annotations for managing transactions -->
<tx:annotation-driven transaction-manager="txManager" />
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource" />
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver"
p:defaultLocale="en_US" />
<!-- For database, uses maven filtering to fill in place holders -->
<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.username}" />
<property name="password" value="${db.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="1" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
<security:global-method-security
secured-annotations="enabled" pre-post-annotations="enabled" />
applicationContext-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http pattern="/CSS/**" security="none" />
<http auto-config="true" use-expressions="true" access-denied-page="/accessdenied.jsp">
<form-login always-use-default-target="false"
login-processing-url="/j_spring_security_check" default-target-url="/login.html"
login-page="/index.jsp" authentication-failure-url="/loginFailed.jsp" />
<logout logout-url="/j_spring_security_logout" />
<intercept-url pattern="/test.jsp" access="hasRole('ROLE_USER')" />
</http>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select username,user_password,enabled from users where username=?"
authorities-by-username-query="select username,authority,enabled from users where username=?" />
</authentication-provider>
</authentication-manager>
Thank you for any help that you can provide.
actully spring security works only if aspect/security interceptor involved. In your code test(),test2(),test3(),test4() are invoked directly from controller method login. so there will not be any aspect involvement causing security to be bypassed.
if test methods are part of another spring bean then this should work as you have been expecting.
or if they are in same class then it should be invoked with spring bean instead of this (current object).

Resources