1. Create FirstServlet class
  2. Configure FirstServlet & Security information in web.xml
  3. Deploy & Run the application

Create FirstServlet class

package com.java2learn.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FirstServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();

		String name=request.getRemoteUser();
		out.println("<h1>Hi "+name+"</h1>");
		if(request.isUserInRole("java")){
			out.println("This is Java HOME Page");
		}else{
			out.println("This is others HOME Page");
		}
		
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

Configure FirstServlet & Security information in 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>WebSecurity</display-name>

	<servlet>
		<description></description>
		<display-name>FirstServlet</display-name>
		<servlet-name>FirstServlet</servlet-name>
		<servlet-class>com.java2learn.servlet.FirstServlet</servlet-class>
		<security-role-ref>
			<role-name>java</role-name>
			<role-link>javaRole</role-link>
		</security-role-ref>
	</servlet>
	<servlet-mapping>
		<servlet-name>FirstServlet</servlet-name>
		<url-pattern>/test</url-pattern>
	</servlet-mapping>

	<security-constraint>
		<web-resource-collection>
			<web-resource-name>FirstServlet</web-resource-name>
			<description></description>
			<url-pattern>/test</url-pattern>
			
			<http-method>GET</http-method>
		</web-resource-collection>

		<auth-constraint>
			<role-name>javaRole</role-name>
			
		</auth-constraint>
	</security-constraint>

	<login-config>
		<auth-method>BASIC</auth-method>
		
	</login-config>

	<security-role>
		<role-name>javaRole</role-name>
	</security-role>

</web-app>

Deploy & Run the application

Accessing FirstServlet with /test url.
Output1

Output2

Final Package Structure:
packageStructure

Download Project: WebSecurity