Spring Security With Servlet and JSP Example

[Updated: Jul 7, 2017, Created: Jul 5, 2017]

In this example, we will see how to use Spring security in a Java Servlet and JSP application. We will use Spring web security to do in-memory authentication. As this web application will run in a servlet container, JSP and Servlet can be used as usual. We will not use Spring MVC in this example.

Maven dependencies



Java Config class

public class AppConfig extends WebSecurityConfigurerAdapter {

  public void configure(AuthenticationManagerBuilder builder)
          throws Exception {

Initializing Java Config

public class AppSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
  public AppSecurityInitializer() {

A JSP page


<h2>Welcome to App</h2>
 <a href="/example">Go to Example Servlet</a>

A Servlet

@WebServlet(name = "exampleServlet", urlPatterns = {"/example"})
public class ExampleServlet extends HttpServlet {
  protected void doGet(HttpServletRequest req,
                       HttpServletResponse resp) throws ServletException, IOException {

      PrintWriter writer = resp.getWriter();
      String servletName = getServletConfig().getServletName();
      writer.println("handling request, servlet name: " + servletName);
      writer.println("user: "+req.getUserPrincipal().getName());
      writer.println( "<br/><a href=\"/index.jsp\">Main Page</a>");

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war


Accessing any resource for the first time will show Spring authentication form:

After submitting user name and password as we set up in our AppConfig class:

Clicking on the 'Go to Example Servlet' link:

Example Project

Dependencies and Technologies Used:

  • spring-security-web 4.2.3.RELEASE: spring-security-web.
  • spring-security-config 4.2.3.RELEASE: spring-security-config.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Spring Security With Servlet And Jsp Select All Download
  • spring-security-and-servlet-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp

See Also