Spring Controller not called from HTML form Submit - spring

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 />.

Related

spring ModelAndView sending data to jsp but on webpage showing null

Hii Guys am new in spring and am learning spring mvc while I am facing this problem when I am sending data from the controller the jsp page shows object values as null. output and code attached please help me...
HomeController.java class
package springmvc.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller // Declaring this class is controller
public class HomeController
{
#RequestMapping("/home") // when we want to fire this method
public String home( Model model)
{
System.out.println("----------hello this home url -------");
model.addAttribute("name","Swapnil Rajendra Take");
model.addAttribute("Id","101");
List <String> friend = new ArrayList<String>();
friend.add("Swapnil");
friend.add("pooja ");
friend.add("abhijit");
friend.add("Onkar");
friend.add("shradhha");
friend.add("rohit");
model.addAttribute("f",friend);
return "index";
}
#RequestMapping("/about")
public String about()
{
System.out.println("this is about page ");
return "about";
}
#RequestMapping("Carier")
public String carrier() {
return "Carier";
}
/// Sending data with model and view
#RequestMapping("/help")
public ModelAndView help() { // we have return model and view object
System.out.println("This is help page ");
ModelAndView modelAndView=new ModelAndView(); // Creating model and view object.
// setting the data
modelAndView.addObject("name","Swapnil");
modelAndView.addObject("rollnumber", 1234 );
// Setting the view
modelAndView.setViewName("help");
return modelAndView;
}
}
help.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
import="java.util.*"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML>
<HTML>
<head>
<meta charset="ISO-8859-1">
<title>help</title>
</head>
<body>
<h1> Hiieee This is help page ...</h1>
<%
String name= (String ) request.getAttribute("name");
Integer rollnumber= (Integer ) request.getAttribute("rollnumber");
%>
<h1> Hello My name is <%=name %></h1>
<h1> My ROllnumber is <%=rollnumber %></h1>
</body>
</html>
spring-servlet.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!-- NameSpace -->
<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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
<context:component-scan base-package="springmvc.controller"/> <!-- For Activating annotations
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
name="viewResolver">
<!-- Configuring view Resolver -->
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
web.xml file
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- Configure dispatcher servlet -->
<servlet>
<!-- Servlet declaration -->
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<!-- Servlet Mapping -->
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Folder Strucher
Output

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 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

validation form using Spring 3

i'm creating validation form on Spring 3, My problem is, that i saw a lot of examples with validation form. I even created one. but my form passing "result.hasErrors()" method, even when there are errors.
My code is:
Controller:
package com.esb.sso;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.servlet.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.validation.BindingResult;
import java.util.Map;
import javax.validation.Valid;
import com.esb.sso.form.LoginForm;
import javax.servlet.http.HttpServletRequest;
/**
* Handles requests for the application home page.
*/
#Controller
#RequestMapping(value = "/")
public class HomeController {
LoginForm loginForm = new LoginForm();
model.put("loginForm", loginForm);
return "home";
}
#RequestMapping(method = RequestMethod.POST)
public String validation(#Valid LoginForm loginForm, BindingResult result,
Map model) throws IOException {
logger.info("Login POST var");
logger.info(loginForm.getLogin());
logger.info(loginForm.getPassword());
if (result.hasErrors()) {
logger.info("error");
return "home";
}
model.put("loginForm", loginForm);
return "logged";
}
}
Validator:
package com.esb.sso.form;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class LoginForm {
#NotNull(message = "notNull")
#Size(min=1, max=50, message="mote charters")
private String login;
#NotNull(message = "notNull")
#Size(min=1, max=50, message="mote charters")
private String password;
public void setLogin(String login){
this.login = login;
}
public String getLogin(){
return login;
}
public void setPassword(String password){
this.password = password;
}
public String getPassword(){
return password;
}
}
View:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Home</title>
</head>
<body>
Autoryzacja!!!
<form:form action="" commandName="loginForm">
<table>
<tr>
<td>User Name:<FONT color="red"><form:errors path="login" /></FONT></td>
</tr>
<tr>
<td><form:input path="login" /></td>
</tr>
<tr>
<td>Password:<FONT color="red"><form:errors path="password" /></FONT></td>
</tr>
<tr>
<td><form:password path="password" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
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>
servlet-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-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">
<!-- 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/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.esb.sso" />
<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="/WEB-INF/messages" />
</beans:bean>
</beans:beans>
and messages.properties:
NotNull.loginForm.login=must not be blank.
NotNull.loginForm.password=must not be blank.
Size.loginForm.login=Login size must be between 1 and 50 charters.
Size.loginForm.password=Password size must be between 1 and 50 charters.
I don't know where is the problem
Coul'd enybody help me ?
Assuming copy paste error in HomeController-get method of the "/" mapping method.
To answer your question - You must specify the LoginForm object as model attribute in order to bind validations on it with BindingResult. Below is the correct code
public String validation((#ModelAttribute("loginForm") #Valid LoginForm loginForm, BindingResult result,
Map model) throws IOException {
For reference see the documentation

Resources