简体   繁体   中英

Calling a servlet from Java code

I am currently trying to complete a login system using jsp and servlets.I have my register and login validation working.

I wish to link to a welcome page following login to display the user profile information. I had, just for testing purposes, a response.sendRedirect(welcome.jsp) which redirected following a successful login by the login servlet.

Now, to display the profile info on this welcome page I was going to use a servlet to gather the info from the database and render it to the the browser using a printwriter. How do I call this servlet successfully from the loginservlet to run the doPost() method? Or is there a better way of doing it?

Thank you for your time.

(For simplicity, I was just trying to get a basic webpage to appear first to make sure this was working I will have no problem with the database side of things once I get this going)

LOGIN SERVLET:

package logon;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public LoginServlet() {
    super();
}

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


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    try
    {
        System.out.println("In the Login Servlet");
        User user = new User();
        user.setEmail(request.getParameter("email"));
        user.setPassword(request.getParameter("password"));
        LoginDAO.login(user);
        if(user.isValid())
        {
            HttpSession session = request.getSession(true);
            session.setAttribute("currentSessionUser",user);
            session.setAttribute("currentSessionUserEmail", user.getEmail());
            response.sendRedirect("WelcomeServlet");

        }else
            response.sendRedirect("LoginFailure.html");
    } catch (Throwable exc)
    {
        System.out.println(exc);
    }

}

}

WELCOME SERVLET:

package logon;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public WelcomeServlet() {
    super();
}

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

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out=response.getWriter();
    out.print("<html>"+"<head>"+"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">");
    out.print("<title>Welcome</title>");
    out.print("</head>"+"<body>");
    out.print("Welcome to the welcome page!!!");
    out.print("</body>"+"</html>");

}
}

You can't redirect using POST, only using GET. Since you're just displaying HTML in WelcomeServlet move the code from doPost to doGet, or make the one call the other, which simply makes them both do the same thing.

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
 {
   doPost(request, response);
 }

Also, it would be better to use a JSP than to out.print a bunch of HTML inside a servlet. See the info page for servlets .

Plus, obviously your welcome page needs to read the attribute currentSessionUser from the session and make sure its not null to see if the user is really logged in or not. Otherwise if a user knows the address of the welcome page they can just bypass your login check as you have it now.

Your problem is that you have currently implemented your Servlet to respond to the wrong HTTP verb.

You'll notice that the servlet has as doPost and a doGet method. As you might expect these map onto HTTP GET and HTTP POST requests. Your current problem stems from the fact that you have implemented the doPost method in your WelcomeServlet therefore expecting a POST request, when it will actually be serving a GET request.

Speaking very crudely, you can think of GET requests as read operations and POST requests as write operations. So when you submit a form to save some data, this is typically handled a POST request. You are basically asking to write data to a database or session. When you load a web page, this is typically handled as a GET request. You are simply asking to read the data.

Again simplifying, but re-directs are typically GET requests. Therefore your Servlet will need to implement the doGet() method to respond to the browsers GET request after it is re-directed.

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