gpt4 book ai didi

java - Catch-all Servlet 防止资源加载

转载 作者:行者123 更新时间:2023-12-01 14:11:47 25 4
gpt4 key购买 nike

我正在使用一个catch all servlet:

@WebServlet(name="RequestHandler", urlPatterns="/*")
public class RequestHandler extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
new SeedPlanter(request, response).sow();
}

}

处理所有请求。请注意 urlPattern /*。这样做的原因是因为它加载了各种内容,例如模板、处理对象等。servlet 基本上只是一个位于处理所有 html 渲染的自定义框架前面的外观。

问题是我无法再直接访问资源。

例如,如果我想加载 web-inf 目录之外的 html 文件 (localhost:8080/myapp/test.html),则会出现 404 错误。事实上,即使当我尝试在页面上加载图像(localhost:8080/myapp/images/test.png)时,它也会给出 404 资源未找到。删除 servlet 显然会破坏整个应用程序,但它确实允许我加载这些资源,因此我确信是 servlet 导致了问题。

如何才能像我一样使用 servlet,同时又能够加载这些资源?

最佳答案

我最终使用了一个单独的 servlet 来监听我的图像、css、js 文件夹(您可以在此处添加任意数量的 urlPatterns)。

@WebServlet(name="CommonRequestHandler", urlPatterns={"/images/*", "/css/*"})
public class CommonRequestHandler extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext();
String path = request.getRequestURI().substring(request.getContextPath().length()+1, request.getRequestURI().length());
String fileName = context.getRealPath(path);

//Get MIME type
String mimeType = context.getMimeType(fileName);
if(mimeType == null) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}

//Set content type
response.setContentType(mimeType);

//Set content size
File file = new File(fileName);
response.setContentLength((int) file.length());

//Open file and output streams
FileInputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();

//Copy file content to output stream
byte[] buf = new byte[1024];
int count = 0;
while((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.close();
}
}

代码只是查找文件并将字节返回给浏览器。

引用:http://java-espresso.blogspot.com/2011/09/webxml-problem-and-solution-for-url.html

关于java - Catch-all Servlet 防止资源加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18481263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com