根据 Servlet 3.0 规范 - “@ServletSecurity 注释不适用于使用 Servletcontext 接口的 addServlet(string, Servlet) 方法创建的 ServletRegistration 的 url 模式,除非 servlet 是由 ServletContext 的 createServlet 方法构造的。”
然而,在尝试使用它时,ServletSecurity 注释正在应用于我在 ServletContextListener.contextInitialized() 方法中添加的所有 servlet。
监听代码:
public void contextInitialized(ServletContextEvent e) {
System.out.println(" ContextInitialized -- start");
ServletContext ctx = e.getServletContext();
try {
ServletRegistration.Dynamic sr2 = ctx.addServlet("myServlet2", "com.example.web.MyServlet1");
sr2.addMapping("/myServlet2");
System.out.println("param2 added status : " + sr2.setInitParameter("param2", "value2"));
sr2.setLoadOnStartup(3);
Class<MyServlet1> myServletClass = (Class<MyServlet1>) Class.forName("com.example.web.MyServlet1");
ServletRegistration.Dynamic sr3 = ctx.addServlet("myServlet3", myServletClass);
sr3.addMapping("/myServlet3");
sr3.setLoadOnStartup(2);
System.out.println("param3 added status : " + sr3.setInitParameter("param3", "value3"));
MyServlet1 myServlet4 = ctx.createServlet(myServletClass);
ServletRegistration.Dynamic sr4 = ctx.addServlet("myServlet4", myServlet4);
sr4.addMapping("/myServlet4");
sr4.setLoadOnStartup(1);
System.out.println("param4 added status : " + sr4.setInitParameter("param4", "value4"));
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
}catch(ServletException ex) {
ex.printStackTrace();
}
System.out.println(" ContextInitialized -- finish");
}
servlet 中的注释:
@ServletSecurity (
httpMethodConstraints = {
@HttpMethodConstraint(
value="GET",
rolesAllowed = {"sme"},
transportGuarantee = ServletSecurity.TransportGuarantee.NONE// CONFIDENTIAL
),
@HttpMethodConstraint(
value="POST",
rolesAllowed = {"ssme"},
transportGuarantee = ServletSecurity.TransportGuarantee.NONE//CONFIDENTIAL
)
}
)
它要求对所有人进行身份验证。
任何见解都会有所帮助。
谢谢-Vineet