我在Tomcat中有一个webapp,其主JSP文件包含页面中心的另一个JSP文件.我想直接拒绝访问该文件,并且只允许直接访问主索引页面.
此外,我不希望用户能够直接从我的webapp获取图像.
我如何用Tomcat拒绝这些请求?我希望所有请求都转发到我的主页面.
从页面阻止访问包含文件.
添加web.xml:
<security-constraint>
<web-resource-collection>
<web-resource-name>Include files</web-resource-name>
<description>No direct access to include files.</description>
<url-pattern>/inc/*</url-pattern>
<http-method>POST</http-method>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<description>No direct browser access to include files.</description>
<role-name>NobodyHasThisRole</role-name>
</auth-constraint>
</security-constraint>
Run Code Online (Sandbox Code Playgroud)
一种方法是实施Filter
例如:
package package;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FilterImplementation implements Filter
{
public void init(FilterConfig filterConfig) throws ServletException {...}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
// if you detect an illegal request, throw an exception or return without calling chain.doFilter.
chain.doFilter(request, response);
}
public void destroy() {...}
}
Run Code Online (Sandbox Code Playgroud)
将以下内容添加到 web.xml:
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>package.FilterImplementation</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Run Code Online (Sandbox Code Playgroud)
编辑
您需要了解的有关正在请求哪个页面的所有信息都在request参数中。然而,参数类型ServletRequest几乎总是 an,HttpServletRequest因此您可以执行以下操作:
if (request instanceof HttpServletRequest)
{
HttpServletRequest hrequest = (HttpServletRequest) request;
String uri = hrequest.getRequestURI(); // you should be able to just use this
String uri = hrequest.getRequestURL(); // otherwise there are more in-depth fields
}
Run Code Online (Sandbox Code Playgroud)