我想通过任何带结构的链接访问Servlet类,如下所示:http://localhost:8080/loginjsp/Reading/abc。 “abc”可以改变,取决于你。 所以我使用了Servlet Annotation
@WebServlet(urlPatterns =“/ Reading / *”)。
但麻烦的是我不能使用RequestDispatcher。 我怎么能做到这两个?
Reading.Java
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ReadingTestServlet
*/
@WebServlet(
urlPatterns = "/Reading/*",
initParams =
{
@WebInitParam(name = "saveDir", value = "D:/FileUpload"),
@WebInitParam(name = "allowedTypes", value = "jpg,jpeg,gif,png")
}
)
public class ReadingTestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
RequestDispatcher rd=request.getRequestDispatcher("test.jsp");
rd.forward(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
答案 0 :(得分:1)
我已经尝试过了,你是对的,有一个问题。问题是你进入一个无限循环,因为你的调度使servlet再次被调用。转发urlPattern将匹配urlPatterns = "/Reading/*"
(您正在使用通配符)。在你的urlPatterns中用'abc'替换通配符'*'并且可以工作(我假设你把'test.jsp'放在/ Reading目录中)
顺便说一句,请考虑使用
getServletConfig().getServletContext().getRequestDispatcher("/absolute/path");
在类似的情况下。