1

Given this doGet implementation:

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

    if (request.getParameterMap().isEmpty()) {

        // DAO initialized in init() method
        Collection<User> users = resource.getUsers();

        if (users != null){

            HttpSession session = request.getSession();
            session.setAttribute("users", users);

        }

        request.getRequestDispatcher("/WEB-INF/users/index.jsp").forward(request, response);

    }

    else {

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

        // DAO initialized in init() method
        User user = resource.getUser(name);

        if (user == null){
            request.setAttribute("message", "Unknown user: " + name);
            request.getRequestDispatcher("/WEB-INF/errors/404.jsp").forward(request, response);
        }

        else {

            HttpSession session = request.getSession();
            session.setAttribute("user", user);

            request.getRequestDispatcher("/WEB-INF/users/show.jsp").forward(request, response);

        }

    }

}

Questions:

  1. Is request.getParameterMap().isEmpty() the preferred way to test for the presence of parameters?
  2. Is there a way to infer the views' location (/WEB-INF/users/) from the either the Servlet's context or an annotation?
craig
  • 25,664
  • 27
  • 119
  • 205

1 Answers1

0

Is request.getParameterMap().isEmpty() the preferred way to test for the presence of parameters?

Yes, it is. But this is not the right solution for your particular case. Your code will fail if the enduser supplied an arbitrary parameter with other name than name, causing the parameter map to be not empty and thus enter the block which expects the name parameter. You should really explicitly check the request parameter name itself.

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

if (name == null) {
    Collection<User> users = resource.getUsers();
    // ...
}
else {
    User user = resource.getUser(name);
    // ...
}

Is there a way to infer the views' location (/WEB-INF/users/) from the either the Servlet's context or an annotation?

Use a MVC framework (recommended) or homebrew one (not recommended, unless 100% internal/private/hobby and thus for pure learning purposes).

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555