【问题标题】:POST response HTML page showed in Debugger but not in Browser using JAVAEEPOST 响应 HTML 页面显示在调试器中,但不在使用 JAVAEE 的浏览器中
【发布时间】:2018-11-07 11:57:17
【问题描述】:

所以问题来了 我有一个向 servlet 发送 Post 请求的连接表单。 在进行一些测试(密码、用户的电子邮件验证)之后,此 servlet 将请求转发到不同的页面。 唯一的问题是我在查看我的POSTrequest 时得到了正确的页面作为响应,但该页面没有显示在我的网络浏览器中。怎么会?

这是我的代码。

登录 servlet

package AHSServlets;

import java.io.IOException;

import objMetier.signInForm;
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 AHSbeans.User;

@WebServlet(
    name = "signInServ",
    urlPatterns = {"/"}
)
public class signInServ extends HttpServlet{
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        this.getServletContext().getRequestDispatcher("/signIn.jsp").forward(request, response);;
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        signInForm connect = new signInForm();
        User user = connect.validateSignIn(request);
        HttpSession session = request.getSession();
        if (user != null) {
            request.setAttribute("connect", connect);
            session.setAttribute("sessionUser", user);
            this.getServletContext().getRequestDispatcher("/restrict_client/client.jsp").forward(request, response);
        }
        else
        {
         request.setAttribute("connect", connect);
         this.getServletContext().getRequestDispatcher("/signIn.jsp").forward(request, response);
        }
    }
}

signIn.jsp

<%@ page pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js" integrity="sha256-QRJz3b0/ZZC4ilKmBRRjY0MgnVhQ+RR1tpWLYaRRjSo=" crossorigin="anonymous"></script>
    </head>
    <body ng-App="AHS" ng-controller="myCtrl">
        <form ng-submit="submitForm()">
            <div>
                <input type="text" ng-model="userObj.mail" placeholder="email"/>
            </div>
            <div>
                <input type="password" ng-model="userObj.password" placeholder="password">
            </div>
            <div>
                <button type="submit">Connect</button>
            </div>
        </form>
        <div>
            <span>${connect.error}</span>
        </div>
        <script type="text/javascript">
            var app = angular.module("AHS", []);
            app.controller("myCtrl", function ($scope, $http, $httpParamSerializerJQLike){
                $scope.userObj = {
                        mail: "",
                        password: "",
                }
                $scope.submitForm = function() {
                      $http({
                         method : 'POST',
                         url : '/', // use relative
                         data: $httpParamSerializerJQLike($scope.userObj),
                         headers: {
                           'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
                         }
                      });
                    };
            });
        </script>
    </body>
</html>

登录类

package objMetier;
import javax.servlet.http.HttpServletRequest;

import AHSbeans.User;

public class signInForm {
    private String EMAIL_FIELD = "email";
    private String PASSWORD_FIELD = "password";
    private String error = "Default";

    public String getError()
    {
        return (this.error);
    }
    public User validateSignIn(HttpServletRequest request){
        if(request.getParameter("password").isEmpty())
        {
            this.error = "wrong password";
            return (null);
        }
        User user = new User();
        user.setEmail("test@hotmail.com");
        this.error = "connected";
        return (user);
    }
}

正如您在signIn.jsp 中看到的那样,我有${connect.error} 应该向我显示错误消息。我重复一遍,但我可以看到使用调试器显示此消息,但在我的 Web 浏览器上看不到。所以在POST 之后会发生什么,它停留在网页路径上,我只在响应中得到 HTML。

编辑

这是截图

非常感谢任何帮助。

【问题讨论】:

  • connect.error 不会向您显示任何内容。除非您专门设置属性并将其转发给您的 jsp。在你的角度部分,你没有对响应做任何事情。
  • 换句话说你误解了这里的过程。您正在发出 ajax 请求,但您没有向 servlet 中的响应写入任何内容。 (也不是你在 js 中处理响应)——如果你使用的是 ajax,你不能只是 setAttribute 并期望它看起来像这样。
  • @JonathanLaliberte 很好,我可以在我的调试器中看到所需的结果,connect.error 填充得很好。 this.getServletContext().getRequestDispatcher("/signIn.jsp").forward(request, response); 在这里更新我浏览器上的视图。但它没有显示。它使用来自表单的简单postrequest。我在做什么错你能解释一下。非常感谢提前
  • 是的,就像我说的,你想发出 ajax 请求对吗?好吧,这不是你做他们的方式。我将在下面发布一个示例。
  • 我不带角度给你看可以吗?

标签: java angularjs google-app-engine servlets


【解决方案1】:

好的,所以我不熟悉 angular,但只是查看 ajax 的 w3,您需要处理这样的响应:

将 id 添加到您的 span 元素(从中删除 ${connect.error}):

 <span id="somediv"></span>

添加一个then成功:

   <script type="text/javascript">
        var app = angular.module("AHS", []);
        app.controller("myCtrl", function ($scope, $http, $httpParamSerializerJQLike){
            $scope.userObj = {
                    mail: "",
                    password: "",
            }
            $scope.submitForm = function() {
                  $http({
                     method : 'POST',
                     url : '/', // use relative
                     data: $httpParamSerializerJQLike($scope.userObj),
                     headers: {
                       'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
                     }
                  }).then(function mySuccess(response) {
                      //handle response here
                      console.log(response.data);
                      document.getElementById("somediv").innerHTML = response.data;
                  });
                };
        });
    </script>

然后为您的 servlet:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    signInForm connect = new signInForm();
    User user = connect.validateSignIn(request);
    HttpSession session = request.getSession();

    if (user != null) {
       // request.setAttribute("connect", connect); //what the hell is connect supposed to be here? 
        session.setAttribute("sessionUser", user);
       // this.getServletContext().getRequestDispatcher("/restrict_client/client.jsp").forward(request, response); //you do not do this in ajax requests.
    }else{
    //request.setAttribute("connect", connect);
     //this.getServletContext().getRequestDispatcher("/signIn.jsp").forward(request, response);
    }
    response.setContentType("text/plain");  // Set content type 
    response.setCharacterEncoding("UTF-8"); 
    response.getWriter().write("hello world");       // Write response body.

}

编辑:

这里的答案非常适合学习 ajax 和 servlet:

How to use Servlets and Ajax?

【讨论】:

  • 我不想用你的连接变量代替“hello world”,因为我不确定它是一个字符串。
  • @Jonahtan Laliberte 谢谢我明白了,但是 this.getServletContext().getRequestDispatcher("/signIn.jsp").forward(request, response); 为什么不能使用我的 post 方法?
  • 只有在不使用 ajax 时才使用 requestDispatcher 转发。
  • 如果您使用 ajax,您只需写入响应即可。 (不转发)
  • 介意在聊天室里聊一聊(在我的帖子评论),会很快提前谢谢?
猜你喜欢
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 2014-06-09
  • 1970-01-01
  • 2014-11-13
  • 2014-06-15
  • 1970-01-01
  • 2021-12-11
相关资源
最近更新 更多