Nearby lessons
24 of 34Servlet - Programmatic Security
- 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.
Programmatic Security
Returns the authenticated user name(login name)
If the user has not been authenticated then this method returns null.
Programmatic Security
Returns java.security.Principal object which contains user name.
Returns null if the user has not been authenticated.
Eg:
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.
Programmatic Security
where admin is logical role name and durgaadmin is original role name.
Demo Program for programmatic Security
web.xml:
Demo Program for programmatic Security
FirstServlet.java
OCWCD
Question Bank
- Key ideas of Servlet - Programmatic Security explained simply
- Ready-to-use code examples
- Exam-style questions at the end