更新:当<auth-constraint>
元素被完全删除时,代码可以正常工作。谁能解释为什么它在存在时不起作用?
我正在编写一些代码来练习在部署描述符中保护 servlet,并且在浏览器中得到以下信息:
HTTP Status 403 - Access to the requested resource has been denied
type Status report
message Access to the requested resource has been denied
description Access to the specified resource has been forbidden.
Apache Tomcat/7.0.42
关于我做错了什么有什么想法吗?我已经对以前的帖子进行了一些搜索,似乎 Tomcat 7 中的角色名称可能已经更新 - 我已经玩过这个,但到目前为止还没有成功。(下面的代码)。
web.xml
<?xml version="1.0" ?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>CheckedServlet</servlet-name>
<servlet-class>webcert.ch05.ex0502J.CheckedServlet</servlet-class>
<security-role-ref>
<role-name>MGR</role-name>
<role-link>manager</role-link>
</security-role-ref>
</servlet>
<servlet-mapping>
<servlet-name>CheckedServlet</servlet-name>
<url-pattern>/CheckedServlet</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>CheckedServletConstraint</web-resource-name>
<url-pattern>/CheckedServlet</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>*</role-name>
</auth-constraint>
</security-constraint>
<security-role>
<role-name>manager</role-name>
</security-role>
CheckedServlet.java
package webcert.ch05.ex0502J;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.security.*;
public class CheckedServlet extends HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head><title>CheckedServlet</title></head><body>");
String userMessage;
Principal user = request.getUserPrincipal();
if(user == null)
userMessage = "Access denied.";
else
userMessage = "Access granted.";
out.write("<br>" + userMessage + " Principal name is " + user +
"<br>If authorized, you should see some more text below:");
if(request.isUserInRole("manager"))
out.write("<br>Here's some super secret extra text since your " +
"role is manager.");
out.write("</body></html>");
out.flush();
out.close();
}
}