enable realm in Tomcat 7 server.xml

Posted on November 4, 2012. Filed under: java/j2EE |

Let’s follow tomcat 7 document and create a realm that protects a web application named test-app


The following is an example configuration in Tomcat 7 with MemoryRealm as the default realm. Assuming you have enabled SSL in Tomcat 7 server.xml.

Open <tomcat_home>/conf/server.xml and uncomment or add the following line.

<Realm className=”org.apache.catalina.realm.MemoryRealm” />

Open <tomcat_home>/conf/tomcat-users.xml to set the role and user/password.

— tomcat-users.xml —

<?xml version=”1.0″ encoding=”UTF-8″?>


<role rolename=”appadmin”/>

<user username=”testapp” password=”test” roles=”appadmin”/>


Open <project_home>/test-app/WebContent/WEB-INF/web.xml and add the

<security-constraint> and <login-config>:

— web.xml —

<web-app version=”3.0″



xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd”&gt;















The protected web-resource is:

— HelloWorld.java —

package testPackage;

import java.io.*;

import javax.servlet.*;

import javax.servlet.annotation.*;

import javax.servlet.http.*;


public class HelloWorld extends HttpServlet {


public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println(“Hello World Secure J2EE/Java Lab”);



Now open browser, visit the following link,


A popup window will asking for user/password, only if you input the testapp/test as user/pass, you will be able to access the web resource. Canceling will result in status 401 error.


Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: