简体   繁体   中英

How to manipulate jsp hyperlinks in doGet method inside a Servlet?

I'm new in the Java world. I am trying to develop an ACME Demo using a simple CSV file as a database to validate user names and passwords. I wonder if it is possible to make some hyperlinks on the index.jsp page, which will take you to other jsp pages of the same website if you click them. As far as I know hyperlinks will invoke the doGet method inside the servle, where -in my case- you gonna be redirected to those secure jsp if your credentials are valid of course. So it has worked for just one hyperlink and I would like to make things more dynamic no matter how many links are there??!!

jsp

 <a href ="<%=request.getContextPath()%>/LoginNow.do"> Content1</a>
  <!-- Here I would like to add more links -->

Servlet

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

    //response.sendRedirect("login.jsp");

     HttpSession session= request.getSession(true);

    if ((session.getAttribute("userSession") != null) && (session.getAttribute("userSession").equals(session.getId())))
    {
      response.sendRedirect("content1.jsp");
      // How can my doGet method manage multiple links here?

    }
    else
    {
      response.sendRedirect("login.jsp");
    }
  }

You should use a servlet filter .

A filter is a component that will be invoked for all the requests to a given url-mapping, and/or for all the requests to a given servlet.

The filter can then check if the user is logged in. If he's loged in, it asks the container to proceed, ie invoke the target servlet as if there was no filter. If he's not logged in, the filter can return an error, or redirect to a login page, or do whatever it wants.

See http://www.oracle.com/technetwork/java/filters-137243.html for an introduction and examples of servlet filters.

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