Reputation: 43
I want to access to Servlet class by any link with struct like this: http://localhost:8080/loginjsp/Reading/abc. "abc" can be change,it's up to you. So that I used Servlet Annotation
@WebServlet(urlPatterns = "/Reading/*").
But the trouble is I can't use RequestDispatcher foward. How can i do both of them?
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);
}
}
Upvotes: 1
Views: 473
Reputation: 183
I've tried it and you are right, there is a problem. The problem is that you are into an infinite loop, because your dispatch makes the servlet be called again. The forward urlPattern will match urlPatterns = "/Reading/*"
(you are using a wildcard). Replace the wildcard '*' with 'abc' in your urlPatterns and will work (I am assuming you put the 'test.jsp' in the /Reading directory)
Btw, consider using
getServletConfig().getServletContext().getRequestDispatcher("/absolute/path");
in similar situations.
Upvotes: 1