登录页面在JSP Servlet中

huangapple go评论65阅读模式
英文:

Login page in JSP 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);
    }
}
<%@ 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>

您遇到的错误是 java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed。此错误发生在响应已经提交后尝试调用 sendRedirect() 函数时。可能的原因是您在处理请求时在某些情况下多次进行了响应操作,导致先前的响应已经完成。

为了解决这个问题,您可以移除 super.doPost(request, response); 这行代码,因为在这个方法中调用了父类的 doPost() 方法,这可能会干扰到您的响应流程。只保留您自己的业务逻辑即可。

同时,确保您没有在其他地方也进行了重定向操作,以防止多次提交响应。

英文:

I am trying to implement a simple login page example in JSP and servlet. Following is my servlet code;

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(&quot;/login&quot;)
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(&quot;in do post&quot;);
String page = &quot;&quot;;
try {
UserBean user = new UserBean();
user.setUserName(request.getParameter(&quot;username&quot;));
user.setPassword(request.getParameter(&quot;password&quot;));
System.out.println(user.getUsername());
System.out.println(user.getPassword());
if (user.getUsername().equalsIgnoreCase(&quot;jsp&quot;) &amp;&amp; user.getPassword().equalsIgnoreCase(&quot;1234&quot;)) {
//					HttpSession session = request.getSession(true);
//					session.setAttribute(&quot;currentSessionUser&quot;, user);
page = &quot;cashtransactions.jsp&quot;;
} else {
page = &quot;invalidLogin.jsp&quot;; // error page
}
} catch (Exception e) {
System.out.println(e);
}
response.sendRedirect(page);
}
}

and following is my JSP code;

&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot;
pageEncoding=&quot;ISO-8859-1&quot;%&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset=&quot;ISO-8859-1&quot;&gt;
&lt;title&gt;Welcome to Bank&lt;/title&gt;
&lt;link rel=&quot;stylesheet&quot;
href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css&quot;
integrity=&quot;sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T&quot;
crossorigin=&quot;anonymous&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div class=&quot;container col-md-4 col-md-offset-3 align-middle&quot;
style=&quot;overflow: auto; margin-top: 100px;&quot;&gt;
&lt;h2&gt;Bank&lt;/h2&gt;
&lt;form action=&quot;&lt;%=request.getContextPath()%&gt;/login&quot; method=&quot;post&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label for=&quot;uname&quot;&gt;User Name:&lt;/label&gt; &lt;input type=&quot;text&quot;
class=&quot;form-control&quot; id=&quot;username&quot; placeholder=&quot;User Name&quot;
name=&quot;username&quot; required&gt;
&lt;/div&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label for=&quot;uname&quot;&gt;Password:&lt;/label&gt; &lt;input type=&quot;password&quot;
class=&quot;form-control&quot; id=&quot;password&quot; placeholder=&quot;Password&quot;
name=&quot;password&quot; required&gt;
&lt;/div&gt;
&lt;button type=&quot;submit&quot; value=&quot;Login&quot; class=&quot;btn btn-primary&quot;&gt;Submit&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;

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!

答案1

得分: 1

根据错误信息,在响应已提交后,无法调用sendRedirect()
通过Servlet显示JSP页面的正确方法如下:

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

还要删除以下部分:

super.doPost(request, response);
英文:

As the error tells you, 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 :

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

Also remove this part :

super.doPost( request, response );

huangapple
  • 本文由 发表于 2020年8月25日 10:09:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63571086.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定