I have created a basic servlet to handle logins on my web app.
currently its in the form;
index.jsp -> loginServlet -> admin.jsp
Requests are sent over the mapping /login
the problem i have is if you try and access the /login without sending post/get it gives a NullPointerException.
How can you handle request sent directly? or is there a better way to handle this?
Stack trace:
java.lang.NullPointerException
loginServlet.doGet(loginServlet.java:39)
javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
HttpSession session = request.getSession(true);
String task = request.getParameter("task");
if(task.equals("logout")) {
session.removeAttribute("username");
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
}
How is that ever possible?
I guess there’s some misconception or bad design going on. Here are some hints to put you on the right track:
Put
login.jspin/WEB-INFfolder.Rewrite
doGet()so that it forwards to that JSP.Keep the login handling job in
doPost(). Make sure that it never throws anRuntimeException. Those kind of exceptions are basically developer’s faults. Always check user input onnulland never trust user input.This way the login page will be opened when you call that servlet by a GET request (e.g. directly entering its URL in address bar, following a bookmark, etc and the login handling job will be done when you submit a
<form method="post">inside that JSP.As a bonus, you get nicer URLs.
See also: