Spring security login form example

Learn to add Spring security login form to any spring web applications using detailed information discussed in spring security tutorial.

Table of Contents

1. Background information
2. Spring security maven dependencies
3. Configure DelegatingFilterProxy in web.xml
4. Add security configuration in application-security.xml
5. Update the controller
6. Add related JSP views
7. Test the application

Read More : Spring security 5 login form example [Updated for Spring 5]

1. Background information

We learned to integrate between Spring 3 and hibernate in linked post. That application was simple web application which presents a view where user can add/edit employees.

Lets secure that application. The scope of this tutorial is to:

  • Only authorized user should be able to access edit employee screen.
  • Unauthorized users should be presented with login screen.
  • Successful credentials should forward to edit employee screen.
  • Unsuccessful credentials should forward to access denied screen.
  • There should be a link for logout of the application.

2. Spring security maven dependencies

Lets start with very first step i.e. update the project dependencies. It will add following four sub-modules in demo for following reasons:

  1. spring-security-core : It contains core authentication and access-control classes and interfaces.
  2. spring-security-web : It contains filters and related web-security infrastructure code. It also enable URL based security which we are going to use in this demo.
  3. spring-security-config : It contains the security namespace parsing code. You need it if you are using the Spring Security XML file for configuration.
  4. spring-security-taglibs : It provides basic support for accessing security information and applying security constraints in JSPs.
<properties>
    <org.springframework.version>3.0.5.RELEASE</org.springframework.version>
</properties>

<!-- Spring Security -->
<dependency>
	<groupid>org.springframework.security</groupid>
	<artifactid>spring-security-core</artifactid>
	<version>${org.springframework.version}</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>
<dependency>
	<groupid>org.springframework.security</groupid>
	<artifactid>spring-security-web</artifactid>
	<version>${org.springframework.version}</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>
<dependency>
	<groupid>org.springframework.security</groupid>
	<artifactid>spring-security-config</artifactid>
	<version>${org.springframework.version}</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>
<dependency>
	<groupid>org.springframework.security</groupid>
	<artifactid>spring-security-taglibs</artifactid>
	<version>${org.springframework.version}</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>

Now use “mvn compile” command to update the dependencies in project.

3. Configure DelegatingFilterProxy in web.xml

Spring Security’s web infrastructure is based entirely on standard servlet filters. These filters are defined in web.xml file or they will be ignored by the servlet container.

In Spring Security, the filter classes are also Spring beans defined in the application context and thus able to take advantage of Spring’s rich dependency-injection facilities and lifecycle interfaces. Spring’s DelegatingFilterProxy provides the link between web.xml and the application context.

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

If you are not using any explicit filter definitions and wants spring to configure basic infrastructure for you, then use filter name as ‘springSecurityFilterChain‘ as in above example. Note that you should not use this bean name yourself. Once you’ve added this to your web.xml, you’re ready to start editing your spring security configuration file. Web security services are configured using the element.

Also do not forget to put security configuration file in context config location setting.

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    	/WEB-INF/employee-servlet.xml
    	/WEB-INF/application-security.xml
    </param-value>
</context-param>

A complete web.xml file will look like this:

<?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 https://www.oracle.com/java/technologies/;
    id="WebApp_ID" version="2.5">
    
  <display-name>Archetype Created Web Application</display-name>
  	<welcome-file-list>
  		<welcome-file>/WEB-INF/index.jsp</welcome-file>
  	</welcome-file-list>
  	
  	<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>
    <servlet>
        <servlet-name>employee</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>employee</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
	    <param-name>contextConfigLocation</param-name>
	    <param-value>
	    	/WEB-INF/employee-servlet.xml
	    	/WEB-INF/application-security.xml
	    </param-value>
	</context-param>
    <listener>
	    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

4. Configure login logout security

As we learned in last section that using filter name as springSecurityFilterChain can help you configure the basic infrastructure using element. Lets see how it is configured first? I have written a basic configuration for this demo:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:beans="http://www.springframework.org/schema/beans" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/security/
	http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">

	<http auto-config="true"  use-expressions="true">
		<intercept-url pattern="/login" access="permitAll" />
		<intercept-url pattern="/logout" access="permitAll" />
		<intercept-url pattern="/accessdenied" access="permitAll" />
		<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
		<form-login login-page="/login" default-target-url="/list" authentication-failure-url="/accessdenied" />
		<logout logout-success-url="/logout" />
	</http>

	<authentication-manager alias="authenticationManager">
		<authentication-provider>
			<user-service>
				<user name="lokesh" password="password" authorities="ROLE_USER" />
			</user-service>
		</authentication-provider>
	</authentication-manager>

</beans:beans>

Lets see what this configuration actually mean.

  • http : Include configuration related url level security. This element is the parent for all web-related namespace functionality.
  • auto-config : Includes some basic services. It is shorthand for –
    <http>
        <form-login />
        <http-basic />
        <logout />
    </http>
    
  • use-expressions : It is here to use expressions to secure individual URLs. These expressions can be e.g. hasRole([role]), hasAnyRole([role1,role2]), permitAll, denyAll etc.
  • intercept-url : This will match the requested url pattern from request and will decide what action to take based on access value.
  • form-login: This will come into picture when user will try to access any secured URL. A login page mapped to “login-page” attribute will be served for authentication check. It is spring security login-processing-url.

    If not provided, spring will provide an inbuilt login page to user. It also contains attribute for default target if login success, or login failure due to invalid user/password match.

  • logout: This will help to find the next view if logout is called in application.

I am using XML based user service i.e. I will not go to database for password validation rather I have stored username/password combination in configuration file itself. To use this king of setup, authentication-manager is setup with inline in-built user details service. In more real time applications, this is going to be some user service fetching data from remote database.

5. Spring controller

I will reuse the controller and will add additional mappings and handler methods in controller. These additional URLs are /login, /logout and /accessdenied. The updated controller having all method handlers looks like this:

package com.howtodoinjava.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.howtodoinjava.entity.EmployeeEntity;
import com.howtodoinjava.service.EmployeeManager;

@Controller
public class EditEmployeeController {

	@Autowired
	private EmployeeManager employeeManager;

	public void setEmployeeManager(EmployeeManager employeeManager) {
		this.employeeManager = employeeManager;
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(ModelMap model) {
		return "login";
	}

	@RequestMapping(value = "/accessdenied", method = RequestMethod.GET)
	public String loginerror(ModelMap model) {
		model.addAttribute("error", "true");
		return "denied";
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(ModelMap model) {
		return "logout";
	}

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String defaultPage(ModelMap map) {
		return "redirect:/list";
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String listEmployees(ModelMap map) {

		map.addAttribute("employee", new EmployeeEntity());
		map.addAttribute("employeeList", employeeManager.getAllEmployees());

		return "editEmployeeList";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addEmployee(
			@ModelAttribute(value = "employee") EmployeeEntity employee,
			BindingResult result) {
		employeeManager.addEmployee(employee);
		return "redirect:/list";
	}

	@RequestMapping("/delete/{employeeId}")
	public String deleteEmplyee(@PathVariable("employeeId") Integer employeeId) {
		employeeManager.deleteEmployee(employeeId);
		return "redirect:/list";
	}
}

6. Spring views

We have now configured our application with security configuration and controller handlers. Its time to write the views which are essentially JSP files. Most important addition in jsp files is login.jsp file.

This file have the form which contains text boxes for username and password field. Lets see how it is written:

6.1. login.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>

<html>
	<body>
		<h1 id="banner">Login to Security Demo</h1>  
		<form name="f" action="<c:url value='j_spring_security_check'/>"
					method="POST">
			<table>
				<tr>
					<td>Username:</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">&nbsp;</td>
				</tr>
				<tr>
					<td colspan='2'><input name="submit" type="submit">&nbsp;<input name="reset" type="reset"></td>
				</tr>
			</table>
		</form>
	</body>
</html>

By default, spring auto generates and configures a UsernamePasswordAuthenticationFilter bean. This filter, by default, responds to the URL /j_spring_security_check when processing a login POST from your web-form. For username field it uses ‘j_username‘ and for password field it uses ‘j_password‘.

On submitting this form, UsernamePasswordAuthenticationFilter will match the username and password as configured in authentication-provider settings in application-security.xml.

6.2. logout.jsp

< % session.invalidate(); %>
You are now logged out!!

<a href="//howtodoinjava.com/spring/spring-security/login-form-based-spring-3-security-example/">go back</a>

This view simply invalidate the session and provide a link to go back to login page.

6.3. denied.jsp

This jsp file will come in user screen when user will try to authenticate with invalid user name and password combinations. It will show the corresponding message as configured in message.properties in your classpath.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
	<body>
	
		<h1 id="banner">Unauthorized Access !!</h1>
	
		<hr />
	
		<c:if test="${not empty error}">
			<div style="color:red">
				Your fake login attempt was bursted, dare again !!<br /> 
				Caused : ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
			</div>
		</c:if>
	
		<p class="message">Access denied!</p>
		<a href="//howtodoinjava.com/spring/spring-security/login-form-based-spring-3-security-example/">Go back to login page</a> 
	</body>
</html>

7. Spring security login form demo

Its time to test the application. Simply deploy the application in any server e.g. in my case i am using Tomcat 7.0. Now, do following steps:

7.1. Type the URL in browser “http://localhost:8080/Spring3HibernateIntegration”

It will bring the login screen as besides /login, /logoutand /accessdenied all other URLs are protected URLs.

default-login-screen-spring-security-6277828
Default login screen

7.2. Try to authenticate with username ‘demo’ and password ‘1234’

unauthorized-access-spring-security-2536085
Unauthorized access for invalid username and password

It will given access denied error because username and password is invalid.

7.3. Try to authenticate with username ‘lokesh’ and password ‘password’

employee-management-screen-3868244
Edit employee screen on successful authentication

It will given employee management screen because username and password is correct.

7.4. Click on logout link

logout-spring-security-3810610
Logout message

User will be logged out and login screen will appear.

I hope this spring mvc login example has been able to put some light on basic spring security mechanism using xml configurations. If you any question on this Spring security login form example, drop me a comment.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

73 thoughts on “Spring security login form example”

  1. Thanks for this awesome step by step I was wondering how to get past in vaild CSRF token
    Invalid CSRF Token ‘null’ was found on the request parameter ‘_csrf’ or header ‘X-CSRF-TOKEN’.

  2. Can you suggest me how to connect database table for login access with username & password

    
    &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
    &lt;beans:beans xmlns=&quot;http://www.springframework.org/schema/security&quot;
    	xmlns:beans=&quot;http://www.springframework.org/schema/beans&quot; 
    	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
    	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    	http://www.springframework.org/schema/security/
    	http://www.springframework.org/schema/security/spring-security-3.0.3.xsd&quot;&gt;
    
    	&lt;http auto-config=&quot;true&quot;  use-expressions=&quot;true&quot;&gt;
    		&lt;intercept-url pattern=&quot;/login&quot; access=&quot;permitAll&quot; /&gt;
    		&lt;intercept-url pattern=&quot;/logout&quot; access=&quot;permitAll&quot; /&gt;
    		&lt;intercept-url pattern=&quot;/accessdenied&quot; access=&quot;permitAll&quot; /&gt;
    		&lt;intercept-url pattern=&quot;/**&quot; access=&quot;hasRole('ROLE_USER')&quot; /&gt;
    		&lt;form-login login-page=&quot;/login&quot; default-target-url=&quot;/list&quot; authentication-failure-url=&quot;/accessdenied&quot; /&gt;
    		&lt;logout logout-success-url=&quot;/logout&quot; /&gt;
    	&lt;/http&gt;
    
    	&lt;authentication-manager alias=&quot;authenticationManager&quot;&gt;
    		&lt;authentication-provider&gt;
    			&lt;user-service&gt;
    				&lt;user name=&quot;lokesh&quot; password=&quot;password&quot; authorities=&quot;ROLE_USER&quot; /&gt;
    			&lt;/user-service&gt;
    		&lt;/authentication-provider&gt;
    	&lt;/authentication-manager&gt;
    
    &lt;/beans:beans&gt;
    
    
  3. Hi Lokesh,
    Fine explanation. Great work. I want to know what is the use of ${sessionScope[“SPRING_SECURITY_LAST_EXCEPTION”].message} in denied.jsp page.

  4. Hi Lokesh ,
    Thank you for the nice article explained beautifully with such an ease.
    waiting for “SpringBoot” ,kindly write on it,asap.
    thank you.

  5. what is the Difference between Spring Security and Spring AOP .we can also provide security through AOP . which one is Reliable

  6. HI LOKESH,

    I WANT TO KNOW HOW TO USE INPUT VALIDATION IN THE FORM FIELDS IN JSP WITH THE HELP OF SPRING SECURITY FRAMEWORK.

  7. Hi Lokesh,

    After entering the credentials user name:”lokesh” password:”password” and submit.

    I am getting following error,I am using Jboss 6.4 server.

    JBWEB000065: HTTP Status 500 – Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection

    JBWEB000309: type JBWEB000066: Exception report

    JBWEB000068: message Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection

    JBWEB000069: description JBWEB000145: The server encountered an internal error that prevented it from fulfilling this request.

    JBWEB000070: exception

    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:169)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    JBWEB000071: root cause

    org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection
    org.springframework.orm.hibernate3.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:596)
    org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
    org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:335)
    org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105)

    Kindly let me know what is the issue.

    Thanks & Regards,
    Praveen

  8. HTTP Status 404 – /Spring3HibernateIntegration/

    ——————————————————————————–

    type Status report

    message /Spring3HibernateIntegration/

    description The requested resource is not available.

    ——————————————————————————–

    Apache Tomcat/7.0.55

    i am getting this error. Can you help me out?

  9. Could you please let me know how we can developed password reset functionality in this example? Your fast inputs are appreciated.

  10. Hi Lokesh, Thanks for the tutorials.
    I am facing one issue though. As soon as I try to login via the custom login page, I always get redirected back to the same login page regardless of entering the correct or incorrect login for the following configuration:

    I am using spring 3.2 and have included Spring security 3.2.6 Release jars in the classpath.

    However when I try to use inbuilt login page, it seems to be working fine in case of valid and invalid credentials for the following configuration:

    Can you please suggest what might be wrong.

    Following is my complete web.xml

    <!–

    –>

  11. HI Lokes Thanks for your Example.

    My question is when user add the employee button it will call the /add method of controller.Is this restricted by sequrity filter
    or not.How to get which user is call the /add url.

    please explain it.
    Thanks in advance.

  12. Hi Lokesh,
    Though I’ve created Employee table in DB, I’m getting following error. Could you please guide?

    org.hibernate.MappingException: Unknown entity: from employee
    at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:693)
    at org.hibernate.impl.SessionImpl.getOuterJoinLoadable(SessionImpl.java:1731)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1697)
    at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
    at com.spring.security.dao.EmployeeDaoImpl.getAllEmployees(EmployeeDaoImpl.java:28)
    at com.spring.security.service.EmployeeManagerImpl.getAllEmployees(EmployeeManagerImpl.java:27)

  13. Hello – I’m getting the following error. Could anyone please guide me?

    com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table ‘test.employee’ doesn’t exist

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.Util.getInstance(Util.java:381)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2643)

    • Have you created “test” database with Employee table in it? Error is suggesting that you have not. Please verify.

      In this application, you don’t need db access. Please share the modifications you did.

    • CREATE TABLE `employee` (
      `ID` INT(5) NOT NULL AUTO_INCREMENT,
      `FIRSTNAME` VARCHAR(50) NULL DEFAULT NULL,
      `LASTNAME` VARCHAR(50) NULL DEFAULT NULL,
      `EMAIL` VARCHAR(50) NULL DEFAULT NULL,
      `TELEPHONE` VARCHAR(50) NULL DEFAULT NULL,
      PRIMARY KEY (`ID`)
      )
      COLLATE=’latin1_swedish_ci’
      ENGINE=InnoDB
      ;

  14. I am getting below error.Please do the needful at earliest

    Can not find the tag library descriptor for “http://www.springframework.org/tags”
    Can not find the tag library descriptor for “http://java.sun.com/jsp/jstl/core”

    • Gaurav – Please try to update project by doing “Maven Update”. Also please check JSTL maven dependency is present or not?

  15. Well, I thank you for your sample website, but 90% of the spring websites out there use css, images, and js folders. Since the security namespace affects their access it becomes tricky to resolve. But I figured out what to do. In application-security.xml I had to add these 3 lines:

    <intercept-url pattern="/css/**" filters="none"/>
    <intercept-url pattern="/images/**" filters="none"/>
    <intercept-url pattern="/js/**" filters="none"/>
    

    So I don’t say you Must put them, but it would be helpful if it was put.

    -Gene

  16. Hi, I downloaded and ran this sample app successfully. However, after I added the security part into my existing “non-secure” Spring MVC project it screwed up with access to CSS and Images paths, so I can’t see CSS and Images on my pages. Here is my configuration for them:

    And this is from my existing login.jsp:

    ….
    So some conflict happened with the context, I guess. Do you know how to fix it? Thank you.

  17. i am getting the below error on hitting the login key

    HTTP Status 500 – Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection

  18. Hi Lokesh,

    I am getting this error below. Do we need to setup the local db before running the project.

    “HTTP Status 500 – Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection”

    Regards
    Manu

  19. spring security login and registration with database source code …please send me sir…Lokesh Gupta.

  20. Thank you very much for the useful example. I have one question. Is there any possible to add the user in user_service at run time? if yes, how could we?

  21. I have a requirement to secure REST services with basic authentication and the web pages, when accessed by browser via Form based authentication.I am trying to combine both of them with Spring-Security-3.2..I read the docs and am trying to follow it , but am not able to configure the spring-context.xml properly..While deploying I get the following errors, Can anyone give me an example of the spring-context.xml.

    Caused By: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: No AuthenticationEntry Point could be established. Please make sure you have a login mechanism configured through the namespace (such as form-login) or s pecify a custom AuthenticationEntryPoint with the ‘entry-point-ref’ attribute Offending resource: class path resource [/security-context.xml] at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68) at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85) at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:72) at org.springframework.security.config.http.AuthenticationConfigBuilder.selectEntryPoint(AuthenticationConfigBuilder.java: 520) at org.springframework.security.config.http.AuthenticationConfigBuilder.createExceptionTranslationFilter(AuthenticationCon figBuilder.java:416) Truncated. see log file for complete stacktrace >

    Your help is very much appreciated

    • I do not have a handy example at this time and will plan to build one such in future. But, in my understanding, this should be done inside SecurityInterceptor. There you should try to find out whether client is java client or NBI (non-browser interface) client. Decision can be based on some parameters or simply request headers. Once client type is determined, handle it accordingly (e.g. for browser based check existing session etc).

  22. Good tutorial, however how to add user management, roles and passwords with a web interface. please if have a reference. thank you.

  23. thank u very much lokesh…….. provided lots of information regarding logine with spring security…. thankq

  24. Thanks for the tutorial! Is this tutorial Spring 4.0 compliant? Will any changes have to be made to use Spring 4.0.

  25. Hi Lokesh

    Nice post.
    I have an existing web application build on Primefaces, EJB and without Spring. Will I be able to integrate spring security 3.2 to this existing application ?

    Thanks
    Jay

  26. Hi sir,i wrote similar kind of security-context.xml file,iam getting the following error:

    cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘http’.

    all 4 jars(core,web,context,taglibs) are added to project sir.

    Thanks
    Venkata Sriram

  27. Thanks for the tutorial. However i have a couple of queries. First one, on startup how is it getting redirected to the login page? Secondly,on page submission how does these ‘j_spring_security_logout’ or ‘j_spring_security_check’ work??

    • I mentioned it already: By default, spring auto generates and configures a UsernamePasswordAuthenticationFilter bean. This filter, by default, responds to the URL /j_spring_security_check when processing a login POST from your web-form. For username field it uses ‘j_username‘ and for password field it uses ‘j_password‘.

  28. I am getting the following error on adding springSecurityFilterChain (DelegatingFilterProxy) in web.xml

    SEVERE: Exception starting filter springSecurityFilterChain
    org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘springSecurityFilterChain’ is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:529)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1095)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:277)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1097)
    at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:326)
    at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:236)
    at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:194)
    at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:281)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:262)
    at org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:107)
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4746)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5399)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

    Dec 08, 2013 1:16:08 PM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Error filterStart
    Dec 08, 2013 1:16:08 PM org.apache.catalina.core.StandardContext startInternal

  29. Great tutorial and it works perfect. However my doubt is won’t spring security support special characters in username? I need to use my email as username but it throws error…!!

  30. org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [java.empcontroller.EditEmployeeController] for bean with name ‘editEmployeeController’ defined in file [D:karthikaSpring Workspace.metadata.pluginsorg.eclipse.wst.server.coretmp0wtpwebappsSpringSecurityWebApplnWEB-INFclassesjavaempcontrollerEditEmployeeController.class]; nested exception is java.lang.ClassNotFoundException: java.empcontroller.EditEmployeeController

    • Exception is self explanatory. Class not found. Look into your classes folder if it is generated. By the way, having package name starting with “java”— I will not recommend this. This is used for JDK supplied classes. Compiler will not prevent you, but you really should not use this.

Comments are closed.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.