Servlet的NullPointerException

时间:2012-11-04 16:40:07

标签: java servlets nullpointerexception requestdispatcher

我使用其URL地址呼叫Servlet。这是我正在输入的网址

http://localhost:7001/ryan/olympics?action=selectCatalog&id=1

这肯定是Servlet的URL;如果我改变地址我

page not found

这是Servlet的代码。

public class Servlet extends javax.servlet.http.HttpServlet
        implements javax.servlet.Servlet {

private static final long serialVersionUID = 1L;

public Servlet() {
    super();
}

public void init(ServletConfig config) throws ServletException {
    System.out.println("*** initializing controller servlet.");
    super.init(config);
}

protected void doPost(HttpServletRequest request,
  HttpServletResponse response) throws ServletException, IOException {


String action = request.getParameter("action");



if (action.equals("selectCatalog")) {
      String categoryId = request.getParameter("id");

      ProductModelDAO dao4 = new ProductModelDAOImpl("jpac");
      if (categoryId != null && !categoryId.trim().equals("")) {
          CategoryDAO dao1 = new CategoryDAOImpl("jpac");

    try {
        Category category = dao1.getCategoryName(categoryId);
        request.setAttribute("category", category);
        } catch (Exception e) {
        e.printStackTrace();
        }
    }

    try {
        @SuppressWarnings("unchecked")
        List<Product> products = dao4
            .getProductsByCategory(categoryId);
        request.setAttribute("products", products);
    } catch (Exception e) {
        e.printStackTrace();
    }

    url = "SelectCatalog.jsp";

 RequestDispatcher requestDispatcher =
  getServletContext().getRequestDispatcher(url);
requestDispatcher.forward(request, response);

我得到NullPointerException指向RequestDispatcher的行。有什么帮助吗?

3 个答案:

答案 0 :(得分:3)

尝试将"SelectCatalog.jsp"更改为"/SelectCatalog.jsp",因为据我了解,您想使用absolute path

答案 1 :(得分:0)

如果您想使用相对路径,则必须使用:

request.getRequestDispatcher(url);

取代:

getServletContext().getRequestDispatcher(url);

答案 2 :(得分:0)

的request.getParameter( “动作”);

代码是用doPost方法编写的。您是否从调用servlet的doPost方法调用此servlet? doPost方法不会使用URL参数。