Login form in JSP

后端 未结 2 2197
醉酒成梦
醉酒成梦 2021-01-25 09:11

enter code hereHiya, so far I didn\'t use JSP at all and I find some online tutorials to be very complicated to learn from them, I need to make simple login form .. its not prob

相关标签:
2条回答
  • 2021-01-25 09:39

    Unlike PHP, you normally use JSP for presentation only. Despite the fact you can write Java code in a JSP file using scriptlets (the <% %> things with raw Java code inside), you should be using (either directly or indirectly) a servlet class to control requests and execute business logic. You can use taglibs in JSP to generate/control the output. A standard taglib is JSTL, with the JSTL 'core' being the most important. You can use EL (Expression Language) to access data which is available in page, request, session and application scopes.

    To start, create a JSP file which contains basically the following:

    <form action="${pageContext.request.contextPath}/login" method="post">
        <input type="text" name="username">
        <input type="password" name="password">
        <input type="submit">
    </form>
    

    Then create a servlet class which has the doPost() as below implemented:

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    User user = userDAO.find(username, password);
    
    if (user != null) {
        request.getSession().setAttribute("user", user); // Logged in!
        response.sendRedirect(request.getContextPath() + "/home"); // Redirect to some home page.
    } else {
        request.setAttribute("message", "Unknown login, try again."); // Print it in JSP as ${message}.
        request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Redisplay same JSP with error message.
    }
    

    Finally annotate the servlet class as below:

    @WebServlet("/login")
    

    Which means that you can invoke it by http://example.com/webapp/login as done in <form action>.

    See also:

    • Our servlets wiki page
    • How to avoid Java code in JSP files?
    • doGet and doPost in Servlets

    Good luck.

    0 讨论(0)
  • 2021-01-25 09:40

    It's a little more involved in Java using old school Servlets and JSP than in PHP. You need to create a servlet which can access the HttpRequest and HttpResponse objects and read out the parameters you sent with the JSP file to that Servlet using the GET or POST method. Furthermore you have to create web descriptor file called web.xml and deploy everything in a servlet container such as Tomcat.

    I would start googling for "hello world servlet", once you get the idea of it works it shouldn't be difficult anymore.

    0 讨论(0)
提交回复
热议问题