Spring MVC rendering index.jsp on its own - spring-mvc

I am trying to create a simple application using Spring MVC + Spring Security + Hibernate.
I want a distinct URI for 2 different flows which will be like:-
<context>/candidate/... and <context>/admin/...
To achieve this, I am now facing a weird issue where MVC is picking index.jsp from nowhere (I couldn't understand where actually). Here are my files:
web.xml
<display-name>spring</display-name>
<welcome-file-list>
<welcome-file>WEB-INF/pages/login.jsp</welcome-file>
</welcome-file-list>
<!-- Enables 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>
<!-- End of Spring Security Configuration -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>5</session-timeout>
</session-config>
<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/spring-security.xml
</param-value>
</context-param>
</web-app>
applicationContext.xml
<context:annotation-config />
<context:property-placeholder location="/config/appConfig.properties" />
<context:component-scan base-package="com.ctlin">
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.jdbcurl}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
<property name="initialSize" value="${db.minPoolSize}" />
</bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.ctlin.bean.CandidateDetailsBean</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<!-- <prop key="hibernate.default_schema">${db.default_schema}</prop> -->
<prop key="hibernate.dialect">${db.dialect}</prop>
<prop key="hibernate.format_sql">${db.format_sql}</prop>
<prop key="hibernate.show_sql">${db.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="authenticateDao" class="com.ctlin.dao.impl.AuthenticateUserDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="authenticateService" class="com.ctlin.service.impl.AuthenticateUserServiceImpl">
<property name="authenticateUserDao" ref="authenticateDao" />
</bean>
</beans>
mvc-dispatcher-servlet.xml
<context:annotation-config />
<context:component-scan base-package="com.ctlin.web.controller" />
<mvc:annotation-driven/>
<mvc:resources mapping="/**assets**" location="/assets/" />
<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>
spring-security.xml
<http auto-config="true" use-expressions="true">
<!-- <access-denied-handler error-page="AccessDenied"/> -->
<intercept-url pattern="/candidate**" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/**/assets/**" access="permitAll" />
<intercept-url pattern="/**/login" access="permitAll" />
<!-- <intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" /> -->
<intercept-url pattern="/**" access="isFullyAuthenticated()" />
<csrf/>
<session-management invalid-session-url="/login"
session-authentication-error-url="/login?sessionexpired"
session-fixation-protection="migrateSession">
<concurrency-control error-if-maximum-exceeded="true" expired-url="/login" max-sessions="1"/>
</session-management>
<form-login login-page="/candidate/login" authentication-failure-url="/candidate/login?error"
username-parameter="userId" password-parameter="password"
default-target-url="/candidate/registerDetails"
login-processing-url="/j_spring_security_check"/>
<logout delete-cookies="JSESSIONID" logout-success-url="/candidate/login?logout"
invalidate-session="true" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="test" password="test" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
Controller
#Controller
#RequestMapping("/candidate")
public class CandidateLoginController {
private static final Logger logger = LoggerFactory.getLogger(CandidateLoginController.class);
private HttpSession httpSession;
#Autowired(required=true)
private IAuthenticateUserSvc authenticateService;
public final void setAuthenticateService(IAuthenticateUserSvc authenticateService) {
this.authenticateService = authenticateService;
}
/**
* #param null
* #return the name of the login view
*/
#RequestMapping(value = { "/", "/login" }, method = RequestMethod.GET)
protected ModelAndView displayLoginPage(#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "sessionexpired", required = false) String sessionExpired,
#RequestParam(value = "logout", required = false) String logout) {
ModelAndView mav = new ModelAndView("login");
logger.debug("Inside displayLoginPage method");
if(error!=null) {
mav.addObject("error", "Either username or password is incorrect");
}
else if(sessionExpired != null) {
mav.addObject("error", "Your session has expired. Kindly login again.");
}
else if (logout != null) {
mav.addObject("msg", "You've been logged out successfully.");
}
return mav;
}
#RequestMapping(value = "/registerDetails")
public ModelAndView registerCandidateDetails() {
System.out.println("candidate get method");
ModelAndView model = new ModelAndView();
model.setViewName("registerDetails");
return model;
}
}
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page session="true"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Candidate Selection Tool</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" />
<link rel="stylesheet" href="assets/css/normalize.css" />
<link rel="stylesheet" href="assets/css/style.css" />
</head>
<body onload='document.loginForm.userId.focus();'>
<div class="container">
<!-- start of main body -->
<div class="row page-header text-center">
<h1>Candidate Selection Tool</h1>
</div>
<div class="col-md-6">
<form name="loginForm" action="<c:url value='j_spring_security_check' />"
class="form-horizontal" method="post" role="login">
<fieldset class="col-md-9 scheduler-border">
<legend class="scheduler-border">Login</legend>
<c:if test="${not empty error}">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<p class="bg-danger text-center lead">${error}</p>
</div>
</div>
</c:if>
<c:if test="${not empty msg}">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<p class="bg-info text-center lead">${msg}</p>
</div>
</div>
</c:if>
<div class="form-group has-feedback">
<label for="cuid" class="col-md-3 control-label">User ID</label>
<div class="col-sm-9">
<input id="cuid" type="text"
placeholder="Please enter your user id" name="userId"
class="form-control" /> <i
class="form-control-feedback glyphicon glyphicon-user"></i>
</div>
</div>
<div class="form-group has-feedback">
<label for="password" class="col-md-3 control-label">Password</label>
<div class="col-sm-9">
<input id="password" type="password"
placeholder="Please enter your password" name="password"
class="form-control" /> <i
class="form-control-feedback glyphicon glyphicon-lock"></i>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-2">
<button type="submit" class="btn btn-success" name="Login">Login</button>
</div>
<div class="col-md-offset-2 col-md-4">
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</fieldset>
</form>
</div>
</div>
<!-- end of main body -->
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
Structure of web app:
────webapp
├───assets
│ ├───css
│ ├───fonts
│ ├───img
│ │ └───background
│ └───js
├───config
└───WEB-INF
└───pages
└───error
Now when I access this URL: http://localhost:8282/spring/login, I get HTTP Status 404 - /spring/WEB-INF/pages/index.jsp (The requested resource is not available.)
Why is it looking for index.jsp?
Whereas, when I access: http://localhost:8282/spring/candidate/login, I get No mapping found for HTTP request with URI [/spring/candidate/assets/css/normalize.css] in DispatcherServlet with name 'mvc-dispatcher' and even after entering correct credentials, it remains on the same URL, kind of loop.
Please help me identify the issue.

Try to change your servlet mapping form / to *
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>*</url-pattern>
</servlet-mapping>

Adding to #Paul answer for accessing the css can you try with below:
<mvc:resources mapping="/assets/css/**" location="/assets/css/" />

Related

Validation not happening for custom login page in Spring security

I am trying execute sample example for spring security using custom login page.The application is not throwing any error.From home.jsp, it is navigating into custom login page but even after entering correct user id and password it is going back to home.jsp instead of hello.jsp without showing any error.Requesting your help in identifying the error.
hello.jsp
<%# taglib prefix="c" uri="/WEB-INF/tld/c.tld" %>
<html>
<body>
<h3>message : ${message}</h3>
<h3>User name : ${username}</h3>
LogOut
</body>
</html>
home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>
<h3>Welcome to spring security</h3>
<b>Click here to logon</b>
</body>
</html>
login.jsp
<%# taglib prefix="c" uri="/WEB-INF/tld/c.tld"%>
<html>
<head>
<title>Login Page</title>
<style>
.errorblock {
color: #ff0000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
</head>
<body onload='document.f.j_username.focus();'>
<h3>Login with Username and Password (Custom Page)</h3>
<c:if test="${SPRING_SECURITY_LAST_EXCEPTION !=null}"><!-- ${not empty error} -->
<div class="errorblock">
Your login attempt was not successful, try again.<br /> Caused :
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
</div>
</c:if>
<form name='f' action="<c:url value='j_spring_security_check' />"
method='GET'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='j_username' value=''>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password' />
</td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"
value="submit" />
</td>
</tr>
<tr>
<td colspan='2'><input name="reset" type="reset" />
</td>
</tr>
</table>
</form>
</body>
</html>
web.xml
<?xml version="1.0"?>
<web-app xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" id="WebApp_ID">
<display-name>Spring MVC</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>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-dispatcher-servlet.xml,/WEB-INF/spring-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>
</web-app>
mvc-dispatcher-servlet.xml
<?xml version="1.0"?>
<beans xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans">
<context:component-scan base-package="test"/>
<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>
</beans>
LoginController.java
package test;
import java.security.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class LoginController {
#RequestMapping(value = "/welcome", method = RequestMethod.GET)
public String printWelcome(ModelMap model,Principal principal) {
System.out.println("*****Hello controller called***");
String name = principal.getName();
model.addAttribute("username", name);
model.addAttribute("message","spring security custom form example");
return "hello";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(ModelMap model) {
return "login";
}
#RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
public String loginerror(ModelMap model) {
model.addAttribute("error","true");
return "login";
}
#RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(ModelMap model) {
return "login";
}
#RequestMapping(value = "/*", method = RequestMethod.GET)
public String home(ModelMap model) {
return "home";
}
}
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-4.3.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.2.xsd">
<!-- <http auto-config="true">
<intercept-url pattern="/welcome*" access="hasRole('ROLE_USER')" />
<http-basic />
</http> -->
<!-- <http>
<intercept-url pattern="/welcome*" access="hasRole('ROLE_USER')"/>
<form-login/>
<logout logout-success-url="/home"/>
</http> -->
<http>
<intercept-url pattern="/welcome*" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login" default-target-url="/welcome" authentication-failure-url ="/loginfailed" />
<logout logout-success-url="/logout"/>
<csrf disabled="true"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="rahul" password="123" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
Try to add those parameters to your spring security form login to make sure your named requests parameters are correct.
<form-login login-page="/login" username-parameter="j_username"
password-parameter="j_password" default-target-url="/welcome"
authentication-failure-url ="/loginfailed" />
Also make sure to change your form:
<form name='loginForm'
action="<c:url value='j_spring_security_check' />" method='POST'>
Also your logout should be a POST, a GET is not supported for logout. Actually you don't need it. Just do something like:
<c:url value="/j_spring_security_logout" var="logoutUrl" />
<form action="${logoutUrl}" method="post" id="logoutForm">
</form>

Images/CSS/Styles in Tiles and Spring MVC in Included pages not working

Problem
I am developing an application using Spring 4.1.1 and Tiles 3.0.5. I could able to create Layout. When I add the Image tag directly in the layout.jsp, I could able to see the Images/CSS etc, but when I add same Image tag in the different JSP which is added as "attribute" to the Layout, then none of the resources is working.
"I can see error in console as
org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/abc/%3Cc:url%20value=%22/resources/images/slides/trial.jpg%22%20/%3E] in DispatcherServlet with name "abc".
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/applicationContext-resource.xml
/WEB-INF/spring/applicationContext-base.xml
/WEB-INF/spring/applicationContext-dao.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Application Context
<?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">
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" id="handlerMapping">
<beans:property name="alwaysUseFullPath" value="true"/>
</beans:bean>
<!-- 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/" />
<resources mapping="/styles/**" location="/resources/css" />
<resources mapping="/images/**" location="/resources/images"/>
<resources mapping="/js/**" location="/resources/js"/>
<resources mapping="/fonts/**" location="/resources/fonts"/>
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<beans:property name="definitions">
<beans:list>
<beans:value>/WEB-INF/tiles-defs/templates.xml</beans:value>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<beans:property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />
</beans:bean>
<context:component-scan base-package="com.online.abc" />
</beans:beans>
Tiles Definition
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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="/WEB-INF/views/layout/layout.jsp">
<put-attribute name="title" value="abc" />
<put-attribute name="header" value="/WEB-INF/views/layout/header.jsp" />
<put-attribute name="navigation" value="/WEB-INF/views/layout/navigation.jsp" />
<put-attribute name="slider" value="/WEB-INF/views/layout/slider.jsp"/>
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/views/layout/footer.jsp" />
</definition>
<definition extends="baseLayout" name="login">
<put-attribute name="title" value="SivaLabs : Login" />
<put-attribute name="navigation" value="" />
<put-attribute name="body" value="/WEB-INF/views/login.jsp" />
</definition>
<definition extends="baseLayout" name="home">
<put-attribute name="title" value="SivaLabs : Welcome" />
<put-attribute name="body" value="/WEB-INF/views/home.jsp" />
</definition>
</tiles-definitions>
Layout.jsp
<!DOCTYPE html>
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%# taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><tiles:insertAttribute name="title" ignore="true" /></title>
<link rel="stylesheet" type="text/css" href='<c:url value="/resources/css/styles.css" />' />
<script src='<c:url value="/resources/js/jquery/jquery-2.1.3.min.js" />'> </script>
<script src='<c:url value="/resources/js/unslider/unslider.js" />'> </script>
</head>
<body class="body">
<div class="headerContent">
<header class="mainHeader">
<tiles:insertAttribute name="header" />
</header>
</div>
<tiles:insertAttribute name="slider" />
<%-- <content>
<tiles:insertAttribute name="body" />
</content> --%>
<%-- <footer>
<tiles:insertAttribute name="footer" />
</footer> --%>
</body>
</html>
Slider.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<script type="text/javascript">
$(function() {
$('.banner').unslider();
});
</script>
<body>
<div class="banner">
<ul>
<li><img src='<c:url value="/resources/images/slides/visa.jpg" />'></li>
</ul>
</div>
</body>
</html>
If I use same code of slider.jsp in layout.jsp, it is working.
I found solution but have no clue what is the problem. Found the solution from this link
JavaScript with Spring MVC doesn't work

Spring 3 MVC and Tiles 2.2

I have configured a Spring MVC / Hibernate / Tiles application. All was working until I introduced the Tiles component. I believe I have it right but I keep getting "Cannot render a null template" exception
Here is my root-context.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"
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<context:component-scan base-package="com.acts542.mygunshop" />
<mvc:interceptors>
<bean class="com.acts542.mygunshop.controller.SecurityInterceptor" />
</mvc:interceptors>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>
<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles/tiles.xml</value>
</list>
</property>
</bean>
<bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mygunshop"/>
<property name="username" value="mygunshop"/>
<property name="password" value="sen32164"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan">
<array>
<value>com.acts542.mygunshop.model</value>
<value>com.acts542.mygunshop.dao</value>
<value>com.acts542.mygunshop.service</value>
<value>com.acts542.mygunshop.controller</value>
</array>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- <prop key="hibernate.hbm2ddl.auto">create</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" />
</beans>
Here is 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">
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 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>
<!-- 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></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>
Here is my tile.xml
<!DOCTYPE tiles-definitions PUBLIC
"-//ApacheSoftwareFoundation//DTDTilesConfiguration2.1//EN"
"http://tiles.apache.org/dtds/tiles-config_2_1.dtd">
<tiles-definitions>
<definition name="template" template="WEB-INF/tiles/mainLayout.jsp">
<put-attribute name="header" value="/WEB-INF/tiles/header.jsp" />
<put-attribute name="menu" value="/WEB-INF/tiles/menu.jsp" />
<put-attribute name="footer" value="/WEB-INF/tiles/footer.jsp" />
<put-attribute name = "content" value="/WEB-INF/views/Login.jsp" />
</definition>
<definition name = "Login">
<put-attribute name = "content" value="/WEB-INF/views/Login" />
</definition>
<definition name = "Home" extends="template">
<put-attribute name = "content" value="/WEB-INF/views/Home" />
</definition>
</tiles-definitions>
Here is my mainLayout.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>This is a test!</title>
</head>
<body>
<table border="1" style="border-collapse: collapse;" cellpadding="2" cellspacing="2" align="center" width="100%">
<tbody>
<tr>
<td width="20%" rowspan="3">
<tiles:insertAttribute name="menu" />
</td>
<td width="80%" height="20%">
<tiles:insertAttribute name="header" />
</td>
</tr>
<tr>
<td width=80% height="60%">
<tiles:insertAttribute name="content" />
</td>
</tr>
<tr>
<td height="20%">
<tiles:insertAttribute name="footer" />
</td>
</tr>
</tbody>
</table>
</body>
</html>
LoginController.java
package com.acts542.mygunshop.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.acts542.mygunshop.dto.BusinessMessage;
import com.acts542.mygunshop.dto.LoginDto;
import com.acts542.mygunshop.form.LoginForm;
import com.acts542.mygunshop.service.LoginService;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
#Controller
#RequestMapping({"/", "/Login"})
public class LoginController
{
private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
LoginService loginService;
#Autowired
public void setLoginService(LoginService loginService)
{
this.loginService = loginService;
}
#RequestMapping(method = RequestMethod.GET)
public String processGet(Map<String, LoginForm> model)
{
LoginForm loginForm = new LoginForm();
model.put("form", loginForm);
return "Login";
}
#RequestMapping(method = RequestMethod.POST)
public String processPost(#Valid #ModelAttribute("form") LoginForm form, BindingResult result, HttpSession session)
{
if (result.hasErrors())
{
return "Login";
}
LoginDto loginDto = new LoginDto();
loginDto.setUserName(form.getUserName());
loginDto.setPassword(form.getPassword());
loginDto = loginService.loginEmployee(loginDto);
if(null == loginDto)
{
result.addError(new ObjectError("form", "User Not Found"));
result.addError(new ObjectError("form", "Please Try Again"));
return "Login";
}
if(loginDto.getMessages().hasMessages())
{
result.addError(new ObjectError("form", loginDto.getMessages().getMessage()));
List<BusinessMessage> messages = loginDto.getMessages().getMessages();
if(null != messages)
{
Iterator<BusinessMessage> iterator = messages.iterator();
while(iterator.hasNext())
{
result.addError(new ObjectError("form", iterator.next().getMessage()));
}
}
return "Login";
}
session.setAttribute("LoggedOnEmployee", loginDto);
return "redirect:/Home";
}
}
Exception
SEVERE: Servlet.service() for servlet appServlet threw exception
org.apache.tiles.impl.InvalidTemplateException: Cannot render a null template
a t org.apache.tiles.renderer.impl.TemplateAttributeRenderer.write(TemplateAttributeRenderer.java:51)
at org.apache.tiles.renderer.impl.AbstractBaseAttributeRenderer.render(AbstractBaseAttributeRenderer.java:106)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:670)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:690)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:644)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:627)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:321)
at org.springframework.web.servlet.view.tiles2.TilesView.renderMergedOutputModel(TilesView.java:124)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:263)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:864)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1665)
at java.lang.Thread.run(Thread.java:662)
Tried everything - except what you guys might add. Again, everything seemed to be working and wired correctly. Had the Login render the login page Post the user / password in a form made a return trip tom to the DB and rendered the Home page. Once I plugged in Tiles, I can't the first page to render.
Is it tiles.xml or tile.xml ?
In tiles.xml are the Login and Home definitions supposed to extend the template definition?

error: no ContextLoaderListener registered

hi I have written code for login in spring mvc my code is following:
web.xml:-
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
Spring3Demo
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/forms/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
Dispatcher-servelet:-
<context:component-scan base-package="net.roseindia.controllers" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
<bean id="loginForm" class="net.roseindia.forms.LoginValidator"/>
<bean id="loginController" class="net.roseindia.controllers.LoginController">
<property name="sessionForm"><value>false</value></property>
<property name="commandName"><value>loginForm</value></property>
<property name="commandClass"><value>net.roseindia.forms.LoginForm</value></property>
<property name="formView"><value>index</value></property>
<property name="successView"><value>loginsuccess</value></property>
<property name="urlMap">
<map>
<entry key="index.jsp">
<ref bean="loginController"/>
</entry>
</map>
</property>
</bean>
<!-- Configure the multipart resolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
Index.jsp:- this is in web content folder out of webinf
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# 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>Spring 3, MVC Examples</title>
</head>
<body>
<h1>Spring 3, MVC Examples</h1>
<ul>
<li>Hello World</li>
</ul>
<form:form action="login.html" commandName="loginForm" >
<table>
<tr>
<td>User Name<FONT color="red"><form:errors path="userName" /></FONT></td> <td><form:input path="userName" /></td>
</tr>
<tr>
<td>Password<FONT color="red"><form:errors path="password" /></FONT></td><td><form:password path="password" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Login"/></td>
</tr>
</table>
</form:form>
</body>
</html>
and in src folder i have class net.roseindia.forms.LoginForm and net.roseindia.controllers.LoginController
I got the error java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?
on line 15 in index.jsp i. e. on form tag
plz suggest how to cofigure it.
Add the context param contextConfigLocation to your web.xml. Even if you don't need one try adding an empty applicationContext file.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>

Spring Web Flow 2 Setup, not rendering ${flowExecutionUrl} nor even starting

I am putting together a simple Spring MVC with Web Flow app and I cannot get it to render the flowExecutionUrl on a page so that I can navigate to the next state. Which I assume means the flow isn't starting(is there an explicit trigger?).
I'm assuming there is something wrong in my setup, although the logs suggest I am registering the flow.xml file correctly.
My spring config(mvc-dispatcher-servlet.xml) is:
<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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:webflow="http://www.springframework.org/schema/webflow-config"
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/tx
http://www.springframework.org/schema/tx/spring-tx-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/webflow-config
http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.3.xsd">
<context:component-scan base-package="com.intl.cigna.ecommerce.controller" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:annotation-driven/>
<!-- Forwards requests to the "/" resource to the "welcome" view -->
<mvc:view-controller path="/" view-name="welcome"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="com.intl.cigna"/>
<!-- Configures Handler Interceptors -->
<mvc:interceptors>
<!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<!-- Saves a locale change using a cookie -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
<!-- Application Message Bundle -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/messages" />
<property name="cacheSeconds" value="0" />
</bean>
<!-- Enables FlowHandler URL mapping -->
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter">
<property name="flowExecutor" ref="flowExecutor" />
</bean>
<webflow:flow-executor id="flowExecutor" />
<!--
Maps request paths to flows in the flowRegistry; e.g. a path of
/hotels/booking looks for a flow with id "hotels/booking"
-->
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
<property name="flowRegistry" ref="flowRegistry" />
<property name="order" value="0" />
</bean>
<webflow:flow-registry id="flowRegistry" flow-builder-services="flowBuilderServices">
<webflow:flow-location path="/WEB-INF/view/flow.xml" />
</webflow:flow-registry>
<webflow:flow-builder-services id="flowBuilderServices"
view-factory-creator="mvcViewFactoryCreator" />
<bean id="mvcViewFactoryCreator"
class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
<property name="viewResolvers" ref="viewResolver" />
</bean>
And my flow.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/webflow
http://www.springframework.org/schema/webflow/spring-webflow.xsd">
<view-state id="step1" view="step1">
<transition on="next" to="step2"/>
<transition on="cancel" to="cancel"/>
</view-state>
<view-state id="step2" view="step2">
<transition on="previous" to="step1"/>
<transition on="finish" to="success"/>
<transition on="cancel" to="cancel"/>
</view-state>
<end-state id="success" view="flows/success"/>
<end-state id="cancel" view="flows/cancel"/>
</flow>
I can successfully navigate to the views.
And my jsp is:
<html>
<head>
<title>spring mvc web flow</title>
<link rel="stylesheet" href="<c:url value="/resources/css/demo_page.css"/>" type="text/css"></link>
<link rel="stylesheet" href="<c:url value="/resources/css/demo_table.css"/>" type="text/css"></link>
</head>
<body id="dt_example">
<div id="container">
<div>
<p class="notice">This is step 1 of the web flow</p>
<form id="step1" action="${flowExecutionUrl}" method="POST">
<button id="cancel" type="submit" name="_eventId_cancel">Cancel</button>
<button id="next" type="submit" name="_eventId_next">Next >></button>
Next
<c:out value="${flowExecutionUrl}"/>
</form>
</div>
<%# include file="/WEB-INF/view/footer.jsp" %>
</div>
</body>
</html>
Ok, got it...
To start the flow, you need to use the flow id in the url. So in my case use the url 'http://localhost:8080/SpringMVC/flow' for the flow with the id of 'flow'.
I was assuming the flow starts when you point to the view.

Resources