Spring + Tiles - 404 error when accessing jsp folder - spring

Basically, what happens when I launch my project is that the views are all resolved properly and the correct jsp is being looked for, however there seems to be something blocking tiles access to my jsp folder inside the WEB-INF folder.
The exact problem is that when I go to localhost/FitterBlog/index.htm I get a 404 error:
The requested resource (/FitterBlog/jsp/layout/layout.jsp) is not available.
I have the following code:
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>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
dispatcher-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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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.fitterblog.controllers"/>
<context:annotation-config/>
<!-- tiles configuration -->
<bean id="tilesViewResolver" 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>
tiles.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="baseLayout" template="/jsp/layout/layout.jsp">
<put-attribute name="title" value="FitterBlog" />
<put-attribute name="header" value="/jsp/layout/header.jsp" />
<put-attribute name="nav" value="/jsp/layout/nav.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/jsp/layout/footer.jsp" />
</definition>
<definition name="index" extends="baseLayout">
<put-attribute name="body" value="/jsp/index.jsp" />
</definition>
</tiles-definitions>
MainController.java:
package com.fitterblog.controllers;
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 MainController {
#RequestMapping(value="index.htm", method=RequestMethod.GET)
public ModelAndView index() {
return new ModelAndView("index");
}
}
I have triple checked that all the JSP files are located in the correct location, as in the layout.jsp file that gets the 404 error is located in WEB-INF/jsp/layout/layout.jsp.

In my application the jsp's are located in subdirectories of WEB-INF.
If it is the same for you you need to change the tiles config a bit
<tiles-definitions>
<definition name="baseLayout" template="/WEB-INF/jsp/layout/layout.jsp">
<put-attribute name="title" value="FitterBlog" />
<put-attribute name="header" value="/WEB-INF/jsp/layout/header.jsp" />
<put-attribute name="nav" value="/WEB-INF/jsp/layout/nav.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/jsp/layout/footer.jsp" />
</definition>
<definition name="index" extends="baseLayout">
<put-attribute name="body" value="/WEB-INF/jsp/index.jsp" />
</definition>
</tiles-definitions>

If You want to store your JSPs in WEB-INF then just set the prefix property in the ViewResolver
<beanid="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>

Related

Spring custom login form issue with Spring Security 4.0.2

I am using Spring MVC 4.2, Hibernate 4.2.20, Apache Tiles 3.0.5 & Spring Security 4.0.2.
Well, my project was running well until I tried to use CUSTOM login page and it fails.
Please look at below page when it works with in-built login.
Now when I tried to use CUSTOM login page I get below error and nothing specific error in the console.
I am NOT sure what could be wrong. Please look at further info below.
Project Structure
My Jars under /lib folder
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>SpringMVCHibernateProject</display-name>
<!-- global variables -->
<context-param>
<param-name>appRootPath</param-name>
<param-value>SpringMVCHibernateProject</param-value>
</context-param>
<!-- front controller -->
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 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>
dispatcher-servlet.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<!-- default page to show when app starts -->
<!-- <mvc:view-controller path="/" view-name="Home"/> --> <!-- this is one way; another way defined in the HomeController.java (preferred) -->
<!-- essentially sets you your Spring context to allow for dispatching requests to Controllers -->
<mvc:annotation-driven />
<!-- used to load static resources like css, js etc... -->
<mvc:default-servlet-handler/>
<!-- automatically wire values into properties, methods, and constructors. -->
<context:annotation-config/>
<!-- scan for components like #Controller, #Repository, #Service, #Component etc...-->
<context:component-scan base-package="au.com.snh.*" />
<!-- spring view resolver bean....commented out in favour of Apache Tiles -->
<!--
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
-->
<!-- apache tiles...template framework -->
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="tilesViewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles3.TilesView
</value>
</property>
<property name="order" value="0" />
</bean>
<!-- load database properties file -->
<context:property-placeholder location="classpath:database.properties"/>
<!-- declare beans -->
<bean id="regionDao" class="au.com.snh.dao.RegionDaoImpl" />
<bean id="regionService" class="au.com.snh.service.RegionServiceImpl" />
<!-- declare datasource bean -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.user}" />
<property name="password" value="${db.pwd}" />
</bean>
<!-- hibernate -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="au.com.snh.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- resource bundles -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/propertybundle/common"/>
</bean>
<!-- spring secruity -->
<security:http auto-config="true" use-expressions="false">
<security:intercept-url pattern="/**" access="ROLE_USER" />
<security:form-login
login-page="/login"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password"
/>
<security:logout logout-success-url="/login?logout"/>
<security:csrf/>
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="hitesh" password="hitesh123" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
tiles.xml (Apache tiles)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
"http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>
<definition name="base" template="/WEB-INF/views/tiles/Template.jsp">
<put-attribute name="title" value="" />
<put-attribute name="header" value="/WEB-INF/views/tiles/Header.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/views/tiles/Footer.jsp" />
</definition>
<definition name="login" extends="base">
<put-attribute name="title" value="Welcome to Spring MVC and Hibernate World!" />
<put-attribute name="body" value="/WEB-INF/views/login.jsp" />
</definition>
<definition name="Home" extends="base">
<put-attribute name="title" value="Welcome to Spring MVC and Hibernate World!" />
<put-attribute name="body" value="/WEB-INF/views/Home.jsp" />
</definition>
<!-- Location Views -->
<definition name="LocationList" extends="base">
<put-attribute name="title" value="Location List" />
<put-attribute name="body" value="/WEB-INF/views/LocationList.jsp" />
</definition>
<definition name="LocationAddEdit" extends="base">
<put-attribute name="title" value="Add/Edit Location" />
<put-attribute name="body" value="/WEB-INF/views/LocationAddEdit.jsp" />
</definition>
<!-- Region Views -->
<definition name="RegionList" extends="base">
<put-attribute name="title" value="Regions" />
<put-attribute name="body" value="/WEB-INF/views/RegionList.jsp" />
</definition>
<definition name="RegionAdd" extends="base">
<put-attribute name="title" value="Add Region" />
<put-attribute name="body" value="/WEB-INF/views/RegionAdd.jsp" />
</definition>
<definition name="RegionEdit" extends="base">
<put-attribute name="title" value="Edit Region" />
<put-attribute name="body" value="/WEB-INF/views/RegionEdit.jsp" />
</definition>
<!-- Student Admission Views -->
<definition name="AdmissionForm" extends="base">
<put-attribute name="title" value="Edit Region" />
<put-attribute name="body" value="/WEB-INF/views/AdmissionForm.jsp" />
</definition>
<definition name="AdmissionFormSuccess" extends="base">
<put-attribute name="title" value="Edit Region" />
<put-attribute name="body" value="/WEB-INF/views/AdmissionFormSuccess.jsp" />
</definition>
</tiles-definitions>
SecurityController.java
package au.com.snh.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class SecurityController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(#RequestParam(value = "error", required = false) String error, #RequestParam(value = "logout", required = false) String logout) {
System.out.println("login() start =>");
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
System.out.println("login() start <=");
return model;
}
}
My Custom Login Form
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<div id="pageHeading">Login with Username and Password</div>
<div id="bodyContent">
<c:if test="${not empty error}">
<div class="error">${error}</div>
</c:if>
<c:if test="${not empty msg}">
<div class="msg">${msg}</div>
</c:if>
<form name='loginForm' action="<c:url value='j_spring_security_check' />" method='POST'>
<table>
<tr>
<td>Username:</td>
<td><input type='text' id="username" name='username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' id="password" name='password' /></td>
</tr>
<tr>
<td colspan='2'>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<input name="submit" type="submit" value="Login" />
</td>
</tr>
</table>
</form>
</div>
<script language="javascript">
document.getElementById("username").focus();
</script>
Can someone please tell me what could be wrong?
Looking forward to getting some help.
Thanks - Hitesh
Your login page is now a normal page displayed through DispatcherServlet instead of being generated by a Spring Security filter. So it must be accessible to non authenticated user. Currently, your security configuration requires a ROLE_USER for all pages... including /login. So here is what happens:
you make a request for any page before being authenticated
spring security detects that and redirect to /login page
browser sends a request for /login page without being authenticated
spring security detects that and redirect to /login page !
You must allow all accesses to /login page in dispatcher-servlet.xml:
<!-- spring secruity -->
<security:http auto-config="true" use-expressions="false">
<security:intercept-url pattern="/login"
access="IS_AUTHENTICATED_FULLY,IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/**" access="ROLE_USER" />
...
alternatively, you can create a dedicated security zone for /login fully by-passing security:
<!-- spring secruity -->
<security:http pattern = "/login*" security="none">
<security:http auto-config="true" use-expressions="false">
<security:intercept-url pattern="/**" access="ROLE_USER" />
...
It is not redirecting properly
Try to add the default-target-url
<security:form-login login-page="/login" default-target-url="/" authentication-failure-url="/login?error=true" />

Spring MVC Themes Not working

I am trying to execute a Spring MVC application that uses Spring MVC theme feature. I am following this example https://www.youtube.com/watch?v=OiQql85qsos But somehow its not working, here is the project structure in STS
I just have a HomeController
#Controller
public class HomeController {
#RequestMapping("/")
public String getHomePage(){
return "home";
}
}
Here 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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SpringMVCThemes</display-name>
<servlet>
<servlet-name>config</servlet-name>
<servlet- class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>config</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Below is the config-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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">
<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan base-package="co.edureka.controllers"/>
<mvc:resources mapping="/resources/**" location="/resources/*" />
<mvc:resources mapping="/images/**" location="/resources/images/" />
<mvc:resources mapping="/css/**" location="/resources/css/" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="themeSource"
class="org.springframework.ui.context.support.ResourceBundleThemeSource">
<property name="basenamePrefix" value="META-INF.theme-" />
</bean>
<bean id="themeChangeInterceptor"
class="org.springframework.web.servlet.theme.ThemeChangeInterceptor">
<property name="paramName" value="theme" />
</bean>
<bean id="themeResolver"
class="org.springframework.web.servlet.theme.CookieThemeResolver">
<property name="defaultThemeName" value="default" />
</bean>
<mvc:interceptors>
<ref bean="themeChangeInterceptor"/>
</mvc:interceptors>
</beans>
Here is the content of theme-black.properties (under WebContent/META-INF)
css=resources/css/theme-black.css
Below is the content of theme-black.css (under WebContent/resources/css)
body {
background-color: #DBF5FF;
color: #007AAB;
}
Here is the home.jsp but on clicking on other themes link it does not change the themes
I checked the cookies , there is a cookie with name org.springframework.web.servlet.theme.CookieThemeResolver.THEME
How to make it work ?
First off all your interceptor setup is flawed. You are using <mvc:annotation-driven /> and as such should use the <mvc:interceptors /> to register your interceptors. You should remove the DefaultAnnotationHandlerMapping bean.
<mvc:interceptors>
<ref bean="themeChangeInterceptor"/>
</mvc:interceptors>
Next to be able to use the selected theme in your JSP you have to use the theme tag from the Spring tag library.
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
Then in your header include the stylesheet you want to use.
<head>
<link rel="stylesheet" href="<spring:theme code='styleSheet'/>" type="text/css"/>
</head>

Spring mvc with Tiles use .xhtml files instead of .jsp

In my project I need to use tiles with spring and use .xhtml as my view pages, but I cant make the project work whit.xhtml files, only with .jsp
my tile.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="base.definition" template="/WEB-INF/views/templates/layout.xhtml">
<put-attribute name="title" value="" />
<put-attribute name="header" value="/WEB-INF/views/templates/header.xhtml" />
<put-attribute name="menu" value="/WEB-INF/views/templates/menu.xhtml" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/views/templates/footer.xhtml" />
</definition>
<definition name="Contact" extends="base.definition">
<put-attribute name="title" value="Spring MVC - Contact Manager" />
<put-attribute name="body" value="/WEB-INF/views/contact.xhtml" />
</definition>
<definition name="/" extends="base.definition">
<put-attribute name="title" value="Spring MVC - Home" />
<put-attribute name="body" value="/WEB-INF/views/home.xhtml" />
</definition>
</tiles-definitions>
my servlet config
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Tiles Configuration -->
<beans:bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<beans:property name="definitions" value="/WEB-INF/tiles.xml" />
</beans:bean>
<beans:bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<beans:property name="viewClass"
value="org.springframework.web.servlet.view.tiles2.TilesView" />
</beans:bean>
<!-- <beans:bean id='viewResolver' class='org.springframework.web.servlet.view. -->
<!-- InternalResourceViewResolver'> -->
<!-- <beans:property name='prefix' value='/WEB-INF/'/> -->
<!-- <beans:property name='suffix' value='.xhtml' /> -->
<!-- </beans:bean> -->
<!-- End Tiles Configuration -->
<context:component-scan base-package="edu.youtube.tutorial" />
</beans:beans>
my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
my template.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:tiles="http://tiles.apache.org/tags-tiles">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Estatistica</title>
</h:head>
<h:body>
<table border="1" cellpadding="2" cellspacing="2" align="center">
<tr>
<td height="30" colspan="2"><tiles:insertAttribute name="header" /></td>
</tr>
<tr>
<td height="250"><tiles:insertAttribute name="menu" /></td>
<td width="350"><tiles:insertAttribute name="body" /></td>
</tr>
<tr>
<td height="30" colspan="2"><tiles:insertAttribute name="footer" /></td>
</tr>
</table>
</h:body>
</html>
and my footer.xhtml ( as a example)
work tork borrk test
my HomeController.java
package edu.youtube.tutorial.controller;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "/";
}
}
so, I found that viewresolver
<!-- <beans:bean id='viewResolver' class='org.springframework.web.servlet.view. -->
<!-- InternalResourceViewResolver'> -->
<!-- <beans:property name='prefix' value='/WEB-INF/'/> -->
<!-- <beans:property name='suffix' value='.xhtml' /> -->
<!-- </beans:bean> -->
but didn't work

spring mvc 3 (3.2.5) + tiles 3 error 404 not resource found

when i load my app i get only 404 resource not found error.. no logs on tomcat at all..
here you can see my project configuration:
this is my web.xml file:
<?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>Spring Web MVC Application</display-name>
<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>/pages/*</url-pattern>
<!--url-pattern>*.jsp</url-pattern-->
</servlet-mapping>
<urlrewrite default-match-type="wildcard">
<rule>
<from>/</from>
<to>/pages/</to>
</rule>
<rule>
<from>/**</from>
<to>/pages/$1</to>
</rule>
<outbound-rule>
<from>/pages/**</from>
<to>/$1</to>
</outbound-rule>
</urlrewrite>
<filter>
<filter-name>urlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>urlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml,
/WEB-INF/spring-security.xml,
/WEB-INF/spring-database.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 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>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
tiles.xml file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="base.definition"
template="/WEB-INF/pages/layout.jsp">
<put-attribute name="title" value="" />
<put-attribute name="header" value="/WEB-INF/pages/header.jsp" />
<put-attribute name="menu" value="/WEB-INF/pages/menu.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/pages/footer.jsp" />
</definition>
<definition name="contact" extends="base.definition">
<put-attribute name="title" value="Contact Manager" />
<put-attribute name="body" value="/WEB-INF/pages/prueba2.jsp" />
</definition>
</tiles-definitions>
mvc-dispatcher-servlet.xml
<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"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
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">
<context:component-scan base-package="com.mkyong.common.controller" />
<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>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>mymessages</value>
</list>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles3.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:annotation-config />
</beans>
spring-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.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
<!--import resource="../database/spring-database.xml"/-->
<http auto-config="true" access-denied-page="/accessDenied">
<intercept-url pattern="/login*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/*" access="ROLE_USER" />
<form-login login-page="/login" default-target-url="/prueba2"
authentication-failure-url="/loginfailed.jsp"/>
<logout logout-success-url="/logout" />
</http>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="
select username,password, enabled
from users where USERNAME=?"
authorities-by-username-query="
select u.username, ur.authority from users u, user_roles ur
where u.user_id = ur.user_id and u.username =? "
/>
</authentication-provider>
</authentication-manager>
</beans:beans>
this is my controller:
#Controller
#RequestMapping("/prueba2")
public class controller2 extends AbstractController {
Stock stock=new Stock();
List stockList=new ArrayList<Stock>();
ApplicationContext appContext = new ClassPathXmlApplicationContext("spring/config/BeanLocations.xml");
StockBo stockBo = (StockBo)appContext.getBean("stockBo");
/*#RequestMapping(method = RequestMethod.GET)
public Stock returnCustomer(ModelMap model) {
stock=stockBo.findByStockCode("7668");
model.addAttribute("miStock", stock);
return stock;
}*/
protected ModelAndView handleRequestInternal (HttpServletRequest req, HttpServletResponse res) throws Exception{
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername();
Map<String, Object> model = new HashMap<String, Object>();
stockList=stockBo.findAll();
stock=stockBo.findByStockCode("7668");
model.put("listaStock",stockList);
model.put("miStock", stock);
model.put("nombreUsuario", name);
System.out.println("lista objetos--->" + stockList.toString());
return new ModelAndView( "prueba2", "model", model );
}
public StockBo getStockBo() {
return stockBo;
}
public void setStockBo(StockBo stockBo) {
this.stockBo = stockBo;
}
}
I don't know the answer to your question directly, but here's how I'd approach it:
First, if I understand your problem correctly, you're expecting that going to the url http://localhost:8080/SpringExample will redirect you to the login page, but that's not happening (you're seeing a 404). I assume that you've checked that your application is actually deployed to the SpringExample context.
You've several things that could influence how URLs are interpreted and redirected. First, you've got Spring, which maps any request starting with /pages/ to the Spring dispatcher. Next, you've got some URL rewriting, which because it's done in a filter, should happen ahead of the spring dispatcher servlet. You've also got a listener that loads all of the spring context configs. Third, you've got Spring Security which is implemented in a filter. Lastly, you've got the tiles configuration, which could in theory also cause a 404 error if a resource isn't found, though it looks like yours is ok.
This is pretty complex, and if things don't happen in the correct order, you'll have a problem. What I would do is strip out each of these components, and then start adding them back in one by one. First, take everything out except the welcome-file configuration and see if you can get to /index.jsp by going to your url. Then add Spring back in and see if you can still get to it. Then add in URL redirection, then security, then tiles. This will help you to narrow down your problem.
<bean id="viewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver"/>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
Try to write the code =>
No need to write this code tiles integration is enough
/WEB-INF/pages/
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

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