Easy learning with example program codes

spring security method level example

Spring security

Spring security is a flexible and powerful authentication and authorization framework to create secure J2EE-based Enterprise Applications.

Authentication: It is a process or action of verifying the identity of a user or process i.e. who are you?

Authorization: It is a process of checking the authority of a user to perform actions in the application i.e. what are you allowed to do?

Method Security

Spring security also provide the feature of method security i.e. it provides the support for applying access rules to Java method executions. To allow method security, we have to enable method security. Normally, we do it on top level or module level configuration for our app. For a secure method, caller have to go through with the security check first. If caller satisfy the check, method will execute otherwise caller will get AccessDeniedException.

public class TestService {
  public String secureMethod() {
    return "Hello Method Security";

Spring method security example

Directory Structure

Spring security

pom.xml file

<project xmlns="" 
  <name>SpringSecurityld Maven Webapp</name>
    <!-- Spring dependencies -->
	<!-- Spring Security -->
	<!-- jstl for jsp page -->
	<!-- Servlet API -->

package com.codesjava.config;
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.ComponentScan;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.web.servlet.config.annotation.EnableWebMvc;  
import org.springframework.web.servlet.view.InternalResourceViewResolver;  
import org.springframework.web.servlet.view.JstlView;  
@ComponentScan({ "com.codesjava.controller.*" })  
public class AppConfig {  
    public InternalResourceViewResolver viewResolver() {  
        InternalResourceViewResolver viewResolver  
                          = new InternalResourceViewResolver();  
        return viewResolver;  

Spring security configuration file. It will contains the security configurations. It creates a springSecurityFilterChain which is a servlet filter.

package com.codesjava.config;
import org.springframework.context.annotation.*;   
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    public UserDetailsService userDetailsService() {  
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();  
        return manager;  
	protected void configure(HttpSecurity http) throws Exception {
	      .rememberMeParameter("remember") //Name of checkbox at login page  
	      .rememberMeCookieName("rememberlogin") //Cookie name
	      .tokenValiditySeconds(300) //Remember login credentials for number of seconds 
	      .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));    		

Now we have to create a class which extends AbstractSecurityWebApplicationInitializer, it will load the springSecurityFilterChain automatically.

package com.codesjava.config.core;
public class SpringSecurityInitializer  extends AbstractSecurityWebApplicationInitializer{

It is initializer class which will load everything.

package com.codesjava.config.core;
import com.codesjava.config.SecurityConfig;
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { SecurityConfig.class };
	protected Class<?>[] getServletConfigClasses() {
		// TODO Auto-generated method stub
		return null;
	protected String[] getServletMappings() {
		return new String[] { "/" };

package com.codesjava.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
public class LoginController {
    @RequestMapping(value="/", method=RequestMethod.GET)    
    public String index() {    	            
        return "index";    
    @RequestMapping(value="/login", method=RequestMethod.GET)    
    public String login() {    	            
        return "login";    
    @RequestMapping(value="/admin", method=RequestMethod.GET)    
    public String admin() {    	            
        return "admin";    
    //User with ADMIN role can access this method.  
    @RequestMapping(value="/delete", method=RequestMethod.GET)   
    public String delete() {    
        return "Record Deleted.";    

index.jsp file

<%@taglib prefix="c" uri=""%>
<%@page session="true"%>
	<h2>Spring MVC + Spring Security</h2>	
	<a href="admin">Login here</a>	

login.jsp file

<%@ taglib prefix="c" uri="" %>  
<c:url value="/login" var="loginUrl"/>  
<form action="${loginUrl}" method="post">         
    <c:if test="${param.error != null}">          
            Invalid username and password.  
    <c:if test="${param.logout != null}">         
            You have been logged out.  
        <label for="username">Username</label>  
        <input type="text" id="username" name="username"/>      
        <label for="password">Password</label>  
        <input type="password" id="password" name="password"/>      
        <label for="remember"> Remember me</label>  
        <input type="checkbox" name="remember" />  
    <input type="hidden"                          
    <button type="submit" class="btn">Login</button>  

admin.jsp file

<%@taglib prefix="c" uri=""%>
<%@page session="true"%>
	<h2>Spring MVC + Spring Security</h2>	
	<h3>Admin login successfully.</h3>	
	<a href="delete"">Delete Record</a>  
	<a href="logout">Logout</a>

Run the application on server.
We add spring security on admin page, so when we hit http://localhost:8080/SpringSecurity05/. Browser will open index page.
Spring security

Click on Login here link. Custom login page will open. Enter credentials, check the Remember me check box and click on login
Spring security

Successfully login
Spring security

Click on Delete Record link
Spring security

Note : User with ADMIN role only can delete the record because we implement method level security.

Spring Tutorial

Spring framework.
Spring framework architecture.
Spring ioc container.
Spring bean.
Spring bean scopes.
Spring bean life cycle.
Spring callback methods.
Spring hello world.
Spring bean definition inheritance.
Spring bean definition template.
Spring dependency injection.
Spring constructor based injection.
Constructor injection type ambiguities.
Setter based dependency injection.
Spring dependency injection collections.
Spring autowire
Spring autowire by name
Spring autowire by type
Spring autowire by constructor
Spring JDBC tutorial
Spring JDBC Prepared Statement
Spring ResultSetExtractor
Spring RowMapper
Spring aop tutorial.
Spring AOP AspectJ Xml.
Spring AOP AspectJ Annotation.
Spring MVC tutorial.
Spring mvc framework.
Spring mvc configuration file.
Spring mvc hello world.
Spring MVC multiple controller.
Spring MVC login.
Spring mvc form handling.
Spring mvc exception handling.
Spring spel tutorial.
Spring spel hello world.
Spring spel operators.
Spring spel ternary operator.
Spring spel standardevaluationcontext.
Spring spel bean reference.
Spring spel method invocation.
Spring spel list, map.
Spring spel regex.
Maven Eclipse Spring
Spring boot overview
Spring boot architecture diagram
Spring boot components
Spring boot starter parent
Spring boot web app configuration
Run spring boot application
Spring boot change port
Spring boot change context path
Spring boot log sql statements
Spring boot hello world
Spring boot JSP
Spring boot thymeleaf
Spring boot with mysql
Spring security overview
Spring security architecture
Spring security maven dependency
Spring security xml
Spring security annotation
Spring security custom login xml
Spring security custom login annotation
Spring security form login
Spring security remember me
Spring security method level
Sign Up/ Sign In
Ask a Question

Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at


We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on

Copyright © 2018 CodesJava Protection Status SiteMap Reference: Java Wiki