Issue
I want to add permissions to servlet methods in declarative way, for example:
// servlet
@Perms("admin", "finance")
public void doPost(servletRequest req, servletResponse res) {
...
}
// web filter
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
List<String> allowedRoles = ... // somehow get values from @Perms
}
May be there is some other ways to do it without annotations, it is just example of idea what I want to do.
Or more abstract example:
@WebServlet("/someaddress")
// servlet
@What("have a nice day")
public void doPost(servletRequest req, servletResponse res) {
...
}
@WebFilter("/*")
// web filter
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
String msg = ... // somehow get values from @What
}
Solution
Here is solution
- declare annotation
@Retention(RetentionPolicy.RUNTIME)
public @interface What {
String[] value();
}
- override
init
method in servlet (I think it will be usefull to declare another class that all servlet will be inherit with thatinit
)
@Override
public void init() throws ServletException {
ServletContext ctx = this.getServletContext();
final Class[] sFormalArgs = {HttpServletRequest.class,HttpServletResponse.class};
try {
Method m = this.getClass().getDeclaredMethod("doGet", sFormalArgs); // do the same with other methods
What a = m.getAnnotation(What.class);
String[] value = a.value();
ctx.setAttribute("someStuff", value);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
- add annotation to method
@What({"admin", "finance"})
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
{
....
}
- get it in web filter
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain
) {
HttpServletRequest req = (HttpServletRequest) servletRequest;
ServletContext ctx = req.getServletContext();
Object o = ctx.getAttribute("someStuff");
}
do not forget to handle errors and multithreding issues
Answered By - Егор Лебедев
Answer Checked By - David Goodson (JavaFixing Volunteer)