简体   繁体   中英

NullPointerException with Servlet

I am calling a Servlet using its URL address. This is the URL I am typing

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

This is the Servlet's URL for sure; if I change the address I get

page not found

This is the code for the 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);

I get the NullPointerException pointing to the RequestDispatcher 's line. Any help?

尝试将"SelectCatalog.jsp"更改为"/SelectCatalog.jsp" ,因为据我所知,您希望使用absolute path

If you want to use a relative path you have to use:

request.getRequestDispatcher(url);

in place of:

getServletContext().getRequestDispatcher(url);

request.getParameter("action");

code is written in doPost method. Are you invoking this servlet from doPost method of calling servlet? URL parameters will not be used by doPost method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM