简体   繁体   English

JSP Servlet 中的登录页面

[英]Login page in JSP Servlet

I am trying to implement a simple login page example in JSP and servlet.我正在尝试在 JSP 和 servlet 中实现一个简单的登录页面示例。 Following is my servlet code;以下是我的 servlet 代码;

package servlet;

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;

import model.UserBean;

/**
 * Servlet implementation class LoginController
 */
@WebServlet("/login")
public class LoginController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginController() {
        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)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doPost(request, response);

        System.out.println("in do post");

        String page = "";
        try {
            UserBean user = new UserBean();
            user.setUserName(request.getParameter("username"));
            user.setPassword(request.getParameter("password"));

            System.out.println(user.getUsername());
            System.out.println(user.getPassword());

            if (user.getUsername().equalsIgnoreCase("jsp") && user.getPassword().equalsIgnoreCase("1234")) {

//                  HttpSession session = request.getSession(true);
//                  session.setAttribute("currentSessionUser", user);
                page = "cashtransactions.jsp";

            } else {
                page = "invalidLogin.jsp"; // error page
            }
        } catch (Exception e) {
            System.out.println(e);
        }

        response.sendRedirect(page);
    }

}

and following is my JSP code;以下是我的 JSP 代码;

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Welcome to Bank</title>
<link rel="stylesheet"
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
    crossorigin="anonymous">
</head>
<body>

    <div class="container col-md-4 col-md-offset-3 align-middle"
        style="overflow: auto; margin-top: 100px;">
        <h2>Bank</h2>
        <form action="<%=request.getContextPath()%>/login" method="post">
            <div class="form-group">
                <label for="uname">User Name:</label> <input type="text"
                    class="form-control" id="username" placeholder="User Name"
                    name="username" required>
            </div>

            <div class="form-group">
                <label for="uname">Password:</label> <input type="password"
                    class="form-control" id="password" placeholder="Password"
                    name="password" required>
            </div>


            <button type="submit" value="Login" class="btn btn-primary">Submit</button>
        </form>
    </div>
</body>
</html>

I am getting the following error;我收到以下错误;

INFO: Server startup in 653 ms
in do post
jsp
1234
Aug 24, 2020 9:39:52 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [servlet.LoginController] in context with path [/BankApplication] threw exception
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
    at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:483)
    at servlet.LoginController.doPost(LoginController.java:74)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

I am able to retrieve the value from the username and password.我能够从用户名和密码中检索值。 I checked this link for reference but still no luck.我检查了这个链接以供参考,但仍然没有运气。 What am I missing here?我在这里缺少什么?

Appreciate the help!感谢帮助!

As the error tells you, you can not call sendRedirect() after the response has been committed.正如错误告诉您的那样, you can not call sendRedirect() after the response has been committed.
The right way of displaying a jsp page via a servlet is the following :通过 servlet 显示 jsp 页面的正确方法如下:

this.getServletContext().getRequestDispatcher("your_page_url").forward( request, response );

Also remove this part :也删除这部分:

super.doPost( request, response );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM