Nearby lessons

24 of 34

Servlet - Programmatic Security

📌 What You Will Learn
  • Understand Programmatic Security
  • Understand Demo Program for programmatic Security
  • See complete working code examples

Programmatic Security is an essential part of the Java Servlet technology. This lesson explains Programmatic Security, Demo Program for programmatic Security and FirstServlet.java with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid.

Programmatic Security

Sometimes declarative security is not enough, compulsory we should go for programmatic

security.

Based on the user role, we have to provide the corresponding response. If the user is admin then

admin related response and if the user is manager then manager related response we have to

provide.

For this type of requirement compulsory we should go for Programmatic Security.

We can implement programmatic security by using the following methods of HttpServletRequest.

Programmatic Security

If the authenticated user belongs to the specified role then this method returns "true"

If the authenticated user not belongs to the specified role or if the user not authenticated then

this method returns false.

Example02
Loading editor…

Programmatic Security

Returns the authenticated user name(login name)

If the user has not been authenticated then this method returns null.

Example03
Loading editor…

Programmatic Security

Returns java.security.Principal object which contains user name.

Returns null if the user has not been authenticated.

Eg:

Example04
Loading editor…

Programmatic Security

The main problem in this approach is we are hard coding the role names in the servlet.

If there is any change in the role-name, modifying servlet code is costly and creates maintanence

problems.

To overcome this problem we have to use <security-role-ref> tag. By using this tag we can map

hard coded role names with original role name.

Example05
Loading editor…

Programmatic Security

where admin is logical role name and durgaadmin is original role name.

Example06
Loading editor…

Demo Program for programmatic Security

web.xml:

Demo Program for programmatic Security

Example08
Loading editor…

FirstServlet.java

OCWCD

Question Bank

Example09
Loading editor…
📝 Key Takeaways
  • Key ideas of Servlet - Programmatic Security explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.