Search code examples
javaservletshref

Using <a href> to link to servlet


I have a anchor which i want it to be linked to a LogoutServlet so that it will destroy the sessions and redirect it back to a login page.

LogoutServlet.java

package pkg;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class LogoutServlet
 */
 public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public LogoutServlet() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    response.setHeader("Cache-Control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");

    request.getSession().invalidate();
     RequestDispatcher rd = request.getRequestDispatcher("Login.html");
        rd.forward(request, response);
}

}

tag

<a href="/Assignment/LogoutServlet" accesskey="1" title="">Logout</a>

Is this the right way to implement it?? I used this but it did not redirect me to Login.html .


Solution

  • That will hit the doGet method not the doPost method. An anchor link like that is a HTTP GET request.

    If you wish to make a POST request, you will need to submit a form to the servlet using method POST.

    Move your code to doGetinstead of doPost and try that.