The requested resource (/Struts1Lab4/) is not available - struts-1

HTTP Status 404 - /Struts1Lab4/
type Status report
message /Struts1Lab4/
description The requested resource (/Struts1Lab4/) is not available.
Apache Tomcat/7.0.28
I am getting this error while running on tomcat. I have added all required jar file. all other Lab working fine but when i am using Validation Framework Validation,getting this error. please help me.
This is my validation file- myform-validations.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts onfiguration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<form-validation>
<formset>
<form name="loginForm">
<field property="username" depends="required,minlength,maxlength">
<arg0 key="un.login" resource="true"/>
<arg1 key="${var:minlength}" resource="false"/>
<arg2 key="${var:maxlength}" resource="false"/>
<var>
<var-name>minlength</var-name>
<var-value>5</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<varvalue>10</varvalue>
</var>
</field>
<field property="password" depends="required,minLimit,maxLimit">
<arg0 key="password" resource="false"/>
<arg1 name="minLimit" key="var:minlength" resource="false"/>
<arg1 name="maxLimit" key="var:maxlength" resource="false"/>
<var>
<var-name>minlength</var-name>
<var-value>6</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<var-value>12</var-value>
</var>
</field>
</form>
</formset>
</form-validation>
This is my config file- struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<form-beans>
<form-bean name="loginForm" type="com.jlc.struts.LoginForm"></form-bean>
</form-beans>
<action-mappings>
<action path="/loginSubmit" name="loginForm" type="com.jlc.struts.LoginAction" scope="session" input="/login.jsp">
<forward name="success" path="/home.jsp"/>
<forward name="failed" path="/login.jsp"/>
</action>
</action-mappings>
<message-resources parameter="com.jlc.struts.messages"/>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/myform-validations.xml,/WEB-INF/validator-rules.xml"/>
</plug-in>
</struts-config>
This is 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>Struts1Lab4</display-name>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
This is login.jsp
<html:errors property="login.Invalid"/>
<html:form action="/loginSubmit">
<table>
<tr><td>Username</td>
<td><html:text property="username"/></td>
<td><html:errors property="username"/></td></tr>
<tr><td>Password</td>
<td><html:password property="password"/></td>
<td><html:errors property="password"/></td></tr>
<tr><td><html:submit value="Login Now"/></td></tr>
</table>
</html:form>
This is LoginForm.java
package com.jlc.struts;
import org.apache.struts.validator.ValidatorForm;
public class LoginForm extends ValidatorForm{
private static final long serialVersionUID = 1L;
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

The validation config file doesn't use the Struts config DTD, instead:
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
Use the actual version for your version of Struts 1, of course.
Unrelated, but please indent your XML, JSP, Java, etc. It's ridiculous to try reading it without it.

Related

No mapping found for HTTP request with URI [/Project_Tracker/] in DispatcherServlet with name 'spring'

I am a beginner and trying to run simple code and I encounter the warning No mapping found for HTTP request with URI [/Project_Tracker/] in DispatcherServlet with name 'spring
Any help would be great! Thanks!!!
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>Project Tracker</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet- class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-dispatcher.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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.projecttrack" />
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
AnnotationController.java
package com.projecttracker.controllers;
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 AnnotationController {
#RequestMapping(value="/LoginPage.html", method=RequestMethod.GET)
public ModelAndView getLoginRequest(){
ModelAndView model=new ModelAndView("LoginPage");
model.addObject("projectTitle","Project Track");
return model;
}
#RequestMapping(value="/LoginSuccess.html", method=RequestMethod.POST)
public ModelAndView getLoginResponse(#RequestParam("userName") String name,
#RequestParam("passWord") String password){
UserInfo userinfo1=new UserInfo();
userinfo1.setuserName(name);
userinfo1.setpassWord(password);
ModelAndView model=new ModelAndView("LoginSuccess");
model.addObject("userinfo1",userinfo1);
return model;
}
}
UserInfo.java (POJO class)
package com.projecttracker.controllers;
public class UserInfo {
private String userName;
private String passWord;
public String getuserName(){
return userName;
}
public void setuserName(String name){
userName=name;
}
public String getpassWord(){
return passWord;
}
public void setpassWord(String password){
passWord=password;
}
}
LoginPage.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>
<h2>${projectTitle}</h2>
<body>
<form action="/ProjectTrack/LoginSuccess.html" method="post">
<fieldset>
<h3>Sign In</h3>
User name:
<input type="text" name="userName"><br><br>
Password:
<input type="text" name="passWord"><br><br>
<input type="submit" value="Login"><br><br>
</fieldset>
</form>
</body>
</html>
LoginSuccess.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>Project Track</title>
</head>
<body>
<br>
${userinfo1.userName}<br>
${userinfo1.passWord}<br>
</body>
</html>
You can add / to
#RequestMapping(value="/LoginPage.html", method=RequestMethod.GET) like:
#RequestMapping(value= {"/", "/LoginPage.html"), method=RequestMethod.GET)
Or you can create a index page or welcome page in root path. What you met is just there is not a controller method which is mapped to /.

Spring Controller not called from HTML form Submit

I am trying to call a simple spring controller on the submit action of my HTML Form.
But the spring controller is not getting called. I searched allot but did not understood the missing point. can any one please help on this.
Below 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">
<welcome-file-list>
<welcome-file>index.jsf</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>
and my spring-servlet.xml is as below.
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd" xmlns:context="http://www.springframework.org/schema/context">
<mvc:annotation-driven />
<context:component-scan base-package="com.src.main"></context:component-scan>
<context:annotation-config/>
<mvc:resources location="/page/css/" mapping="/page/css/**"/>
<mvc:resources location="/page/content/" mapping="/page/content/**"/>
<!-- <mvc:resources location="/jsp/js/" mapping="/jsp/js/**"/>-->
<bean id="loginBean" class="com.src.main.LoginBean" scope="request">
<aop:scoped-proxy/>
</bean>
<bean id="userLogin" class="com.src.main.UserLogin" scope="session">
<aop:scoped-proxy/>
</bean>
<bean id="handleApplicationInitProcessor" class="com.src.main.process.HandleApplicationInitProcessor">
<property name="userLogin" ref="userLogin"></property>
<property name="loginBean" ref="loginBean"></property>
</bean>
</beans>
and my jsp is as below:
<%# page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<f:subview id="user_login_subview">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'userLogin.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form id="login_form" method="post" action="/processLogin">
<div id="login_div">
<h3 id="login_text" class="borderText">LOGIN</h3>
<div id="user_name_div">
<h:outputText id="loging_label" value="Username :" />
<h:inputText id="login_field" size="30" value="#{loginBean.userName}" tabindex="1" styleClass="textBox"></h:inputText>
</div>
<div id="password_div">
<h:outputText id="password_label" value="Password :" />
<h:inputText id="password_field" size="30" value="#{loginBean.password}" tabindex="2" styleClass="textBox"></h:inputText>
</div>
<div id="remember_me_div">
<h:selectBooleanCheckbox id="remember_me_checkbox" value="#{loginBean.rememberMe}" tabindex="3" styleClass="checkbox"/>
<h:outputText id="remember_me_label" value="Remember me" />
</div>
<div id="action_buttons_div">
<input type="submit" id="submit_button" value="submit" class="button"/>
<input type="reset" id="reset_button" value="reset" class="button"/>
</div>
</div>
</form>
</body>
</html>
</f:subview>
and Controller UserLogin.java is as below,
package com.src.main;
public class UserLogin {
private String userName;
private String password;
public UserLogin(){
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And my Controller name is :
package com.src.main.process;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.src.main.LoginBean;
import com.src.main.UserLogin;
#Controller
public class HandleApplicationInitProcessor {
private UserLogin userLogin;
private LoginBean loginBean;
public HandleApplicationInitProcessor() {
}
#RequestMapping(value = "/processLogin", method = RequestMethod.POST)
public String process(){
this.getUserLogin().setUserName(this.getLoginBean().getUserName());
this.getUserLogin().setPassword(this.getLoginBean().getPassword());
System.err.println("UserName : "+this.getUserLogin().getUserName());
System.err.println("Password : "+this.getUserLogin().getPassword());
return "Hello World !";
}
public UserLogin getUserLogin() {
return userLogin;
}
public void setUserLogin(UserLogin userLogin) {
this.userLogin = userLogin;
}
public LoginBean getLoginBean() {
return loginBean;
}
public void setLoginBean(LoginBean loginBean) {
this.loginBean = loginBean;
}
}
Initially i was trying with the JSF form submit tag but due to this issue i tried with simple HTML form submission but still the same problem.
I do not get any error on my console as well.
I think you should do below changes in your code
1.Declare DispatcherServlet in web.xml file,like below. For Ex:-
<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>*.htm</url-pattern>
</servlet-mapping>
2.Remove below lines from your spring configuration file.
<bean id="handleApplicationInitProcessor" class="com.src.main.process.HandleApplicationInitProcessor">
<property name="userLogin" ref="userLogin"></property>
<property name="loginBean" ref="loginBean"></property>
</bean>
3.Just place #Autowired before where you are declaring it(Controller class).like below
#Autowired
private UserLogin userLogin;
#Autowired
private LoginBean loginBean;
4.Remove <context:annotation-config/> as you are using <mvc:annotation-driven />.

java.lang.ClassCastException: while typecasting the command object in onSubmit method

I am beginner in spring3 so i am creating a simple login application. In my loginController i am getting "java.lang.ClassCastException: org.springframework.web.bind.support.SimpleSessionStatus cannot be cast to com.forms.LoginForm" on the following line
LoginForm login = (LoginForm)command;
For the reference code is as follows:
LoginController.java:-
package com.beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.Dao.LoginDaoUtil;
import com.forms.LoginForm;
#SuppressWarnings("deprecation")
#Controller
public class LoginController extends SimpleFormController {
public LoginController() {
setCommandClass(LoginForm.class);
}
#RequestMapping("/LoginAction")
protected ModelAndView onSubmit(Object command) {
try {
LoginForm login = (LoginForm) command;
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"SpringBlogger-servlet.xml");
LoginDaoUtil daoUtil = ctx.getBean("LoginDaoUtil",
LoginDaoUtil.class);
boolean isUserValid = daoUtil.isValidUser(login.getUsername(),
login.getPassword());
if (isUserValid)
return new ModelAndView("success").addObject("name",
login.getUsername());
else
return new ModelAndView("login", "loginForm", new LoginForm());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new ModelAndView("login", "loginForm", new LoginForm());
}
}
}
login.jsp:-
<%# 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>Insert title here</title>
</head>
<body>
<h1>${message}</h1>
<form:form action="LoginAction" method="post" commandName="loginForm">
Username:<form:input path="username"/>
<font color="red"><form:errors path="username"/></font><br/><br/>
Password:<form:password path="password"/>
<font color="red"><form:errors path="password"/></font><br/><br/>
<input type="submit" value="submit">
</form:form>
</body>
</html>
LoginForm.java:-
package com.forms;
public class LoginForm {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
HomeController.java:-
package com.beans;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.forms.LoginForm;
#Controller
public class HomeController {
#RequestMapping({"/","/home"})
public String showHomePage(ModelMap map){
map.addAttribute("message", "Welcome to Spring Blogger");
map.addAttribute("loginForm", new LoginForm());
return "login";
}
}
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" version="3.0">
<display-name>SpringBlogger</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>SpringBlogger</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringBlogger</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringBlogger-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"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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">
<mvc:annotation-driven/>
<context:component-scan base-package="com.beans" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost/springblogger"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
Please help.
Thanks,
Manish
You cannot use Object type to bind your form, use its type instead decoreated with #ModelAttribute1
#RequestMapping("/LoginAction")
public ModelAndView onSubmit(#ModelAttribute("loginForm") LoginForm command) {
Also I saw you're trying to create a new application context inside the controller which seem unecessary, use dependency injection / autowiring instead to your controller class

Spring custom JSF login page, always "Bad credentials"

I'm trying to get a JSF login page to work with Spring security. I've looked around for numerous examples but none works. Every time I try to log in using the JSF page I get a "Bad credentials" warning in my server log.
Spring-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.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true">
<intercept-url pattern="/Login.xhtml*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/**/*.css*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/**/*.js*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN" />
<form-login login-page="/Login.xhtml" default-target-url="/Secure.xhtml"
authentication-failure-url="/Login.xhtml" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" authorities="ROLE_ADMIN" password="admin"/>
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.example" />
<context:annotation-config />
<tx:annotation-driven />
<import resource="classpath:spring/security/Spring-Security.xml" />
</beans>
Login.xhtml
<!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">
<h:head></h:head>
<body>
<h:form>
<h:outputLabel value="username" for="j_username"
style="float:left" />
<h:inputText id="j_username" style="float:left" />
<h:outputLabel value="password" for="j_password"
style="float:left; clear:both" />
<h:inputSecret id="j_password" style="float:left" />
<h:commandButton value="login"
actionListener="#{loginBean.login}" style="float:left;clear:both" />
</h:form>
<h:messages style="float:left;clear:both" />
</body>
</html>
LoginBean
#Named
#Scope("request")
public class LoginBean
{
public void login() throws ServletException, IOException
{
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.dispatch("/j_spring_security_check");
facesContext.responseComplete();
}
}
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>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<filter>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
When I use a non-JSF page as Login.xhtml it works flawlessly.
Page that does work:
<!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">
<h:head></h:head>
<body>
<form action="j_spring_security_check" method="post">
<table>
<tr>
<td>User:</td>
<td><input type="text" name="j_username" /></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>
</table>
</form>
</body>
</html>
Any help is appreciated.
This is an old problem. By default the FilterSecurityInterceptor will only execute once-per-request and doesn't do security re-checking unless there is change in the url but with JSP/JSF forwards the page is rendered as a response to the current request and the url in the browser contains the address of the previous page.
Before Spring Security 3.0 this was bypassed doing a GET request something like this:
String encodedURL = externalcontext.encodeResourceURL(externalcontext.getRequestContextPath() + "/j_spring_security_check?j_username=" + username + "&j_password=" + password);
externalcontext.redirect(encodedURL);
But from Spring Security 3.0, by default it supports POST only.
So one way, probably the easiest to use is a simple HTML form. Otherwise you need to manually authenticate the request by getting the AuthenticationManager.
I guess the whole story originated from this post on Spring forums.
And the best working example can be found on the ICEFaces wiki
Here is the relevant LoginController class from the tutorial.zip
/**
* This class handles all login attempts except html forms that directly
* post to the /j_spring_security_check method.
*
* #author Ben Simpson
*/
#ManagedBean(name = "loginController")
#RequestScoped
public class LoginController implements Serializable {
private static final long serialVersionUID = 1L;
/**
* This action logs the user in and returns to the secure area.
*
* #return String path to secure area
*/
public String loginUsingSpringAuthenticationManager() {
//get backing bean for simple redirect form
LoginFormBackingBean loginFormBean =
(LoginFormBackingBean) FacesUtils.getBackingBean("loginFormBean");
//authentication manager located in Spring config: /WEB-INF/authenticationContext-security.xml
AuthenticationManager authenticationManager =
(AuthenticationManager) getSpringBean("authenticationManager");
//simple token holder
Authentication authenticationRequestToken = createAuthenticationToken(loginFormBean);
//authentication action
try {
Authentication authenticationResponseToken =
authenticationManager.authenticate(authenticationRequestToken);
SecurityContextHolder.getContext().setAuthentication(authenticationResponseToken);
//ok, test if authenticated, if yes reroute
if (authenticationResponseToken.isAuthenticated()) {
//lookup authentication success url, or find redirect parameter from login bean
return "/secure/examples";
}
} catch (BadCredentialsException badCredentialsException) {
FacesMessage facesMessage =
new FacesMessage("Login Failed: please check your username/password and try again.");
FacesContext.getCurrentInstance().addMessage(null,facesMessage);
} catch (LockedException lockedException) {
FacesMessage facesMessage =
new FacesMessage("Account Locked: please contact your administrator.");
FacesContext.getCurrentInstance().addMessage(null,facesMessage);
} catch (DisabledException disabledException) {
FacesMessage facesMessage =
new FacesMessage("Account Disabled: please contact your administrator.");
FacesContext.getCurrentInstance().addMessage(null,facesMessage);
}
return null;
}
private Authentication createAuthenticationToken(LoginFormBackingBean loginFormBean) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
new UsernamePasswordAuthenticationToken(
loginFormBean.getUserName(),
loginFormBean.getPassword()
);
return usernamePasswordAuthenticationToken;
}
private Object getSpringBean(String name){
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(
(ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext());
return ctx.getBean(name);
}
}
OPTION 3 : I haven't personally tried but even this should work:
By setting once-per-request attribute to false in your http element in applicationContext thus forcing security rechecking. But I don't recommend it.
<http auto-config="true" use-expressions="true" once-per-request="false">
The answer to the question left me a little wanting.
So to get this working with a minimal amount of code in the controller (I wanted to avoid manually authenticating), I used a combination of a JSF (primefaces) form and a simple form.
I ended up with a view like this:
<h:form id="login-form" prependId="false">
<p:focus for="userName" />
<p:fieldset id="login-fs" legend="User Authentication">
<h:panelGrid id="login-grid" columns="3">
<p:outputLabel for="userName" value="User Name" />
<p:inputText id="userName" value="#{loginView.userName}" required="true" />
<p:message for="userName" />
<p:outputLabel for="password" value="Password" />
<p:inputText type="password" id="password" value="#{loginView.password}" required="true" />
<p:message for="password" />
</h:panelGrid>
<br />
<p:commandButton value="Submit" icon="ui-icon-check" process="#form" update="login-grid" actionListener="#{loginView.login}" />
</p:fieldset>
</h:form>
<form id="hidden-form" action="#{request.contextPath}/j_spring_security_check" method="post">
<h:inputHidden id="j_username" />
<h:inputHidden id="j_password" />
</form>
<script type="text/javascript">
function mysubmit() {
$('#j_username').val($('#userName').val());
$('#j_password').val($('#password').val());
$('#hidden-form').submit();
}
</script>
And the backing bean could do the typical jsf lifecycle, after which it would send javascript back to transfer values from the successfully validated JSF form to the hidden one and submit the hidden form:
#ManagedBean
public class LoginView {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void login() {
RequestContext.getCurrentInstance().execute("mysubmit()");
}
}
You could do anything else you want on the server-side before the submit actually happens, if you need to.
Someone correct me if i'm wrong, but I think you are specifying your backing bean incorrectly.
The correct JSF way to specify your backing bean scope is like this:
#ManagedBean
#RequestScoped
public class LoginBean
{
public void login() throws ServletException, IOException
{
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.dispatch("/j_spring_security_check");
facesContext.responseComplete();
}
}
Change your h:commandButton to use an action method instead of an actionListener:
<h:commandButton value="login"
action="#{loginBean.login}" style="float:left;clear:both" />
See also: Differences between action and actionListener

No WebApplicationContext found: no ContextLoaderListener registered?

I'm trying to create a simple Spring 3 application and have the following files. Please tell me the reason for this error
Below is my 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" version="3.0">
<display-name>Spring2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Below is my index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!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>
Index Page<br/>
<form:form commandName="loginBean" method="POST" action="login">
<form:input path="userName" id="userName"/><br/>
<form:input path="password" id="password"/><br/>
<input type="submit" value="submit"/>
</form:form>
Go to Registration Page
</body>
</html>
Below is my 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean name="/login" class="com.infy.controller.LoginController"/>
</beans>
This is the LoginController.java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class LoginController {
#RequestMapping(value="/login", method=RequestMethod.POST)
public ModelAndView loginAction(#ModelAttribute("loginBean")LoginBean bean){
return new ModelAndView("success", "success", "Successful Login");
}
}
And finally my LoginBean
public class LoginBean {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
You need to understand the difference between Web application context and root application context .
In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which
inherits all the beans already defined in the root WebApplicationContext. These inherited
beans defined can be overridden in the servlet-specific scope, and new scope-specific
beans can be defined local to a given servlet instance.
The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .
Read the spring reference here for spring mvc .
And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener,
then see -> https://stackoverflow.com/a/40694787/3004747

Resources