验证后,我可以访问并调用HomeServlet
该方法。new Logic().doSomething()
考虑到我的用户只有角色,不应该抛出异常TutorialUser
吗?
我RolesAllowed
在方法上使用了注释,值为ADMIN
.
HomeServlet.java
:
public class HomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + new Logic().doSomething() + "</h1>"); <!-- String gets printed -->
out.println("<h1>" + request.getRemoteUser() + "</h1>"); <!-- user -->
out.println("<h1>" + request.isUserInRole("CUSTOMER") + "</h1>"); <!-- false -->
out.println("<h1>" + request.isUserInRole("ADMIN") + "</h1>"); <!-- false -->
out.println("<h1>" + request.isUserInRole("TutorialUser") + "</h1>"); <!-- true -->
}
}
Logic.java
,其中包含一个只允许由具有角色的用户执行的方法ADMIN
public class Logic {
@RolesAllowed("ADMIN")
public String doSomething() {
return "You have access!";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>HomeServlet</servlet-name>
<servlet-class>javaeetutorial.hello1_formauth.HomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HomeServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<security-constraint>
<display-name>Constraint1</display-name>
<web-resource-collection>
<web-resource-name>wrcoll</web-resource-name>
<description/>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<description/>
<role-name>TutorialUser</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>file</realm-name>
</login-config>
<security-role>
<description/>
<role-name>TutorialUser</role-name>
</security-role>
</web-app>