通过Ajax POST调用servlet时,RequestDispatcher.forward()不转发

时间:2019-04-16 07:12:36

标签: javascript java html ajax servlets

我有一个登录页面,我在其中通过firebase对用户进行身份验证并将请求发送到servlet。当我使用正确的身份验证按下submit按钮时,firebase身份验证有效,调用servlet,但是在浏览器中看到错误。

首先,这是我的JavaScript代码

function toggleSignIn() {
    if (firebase.auth().currentUser) {
        alert('existing user');
        firebase.auth().signOut();
    } else {
        var email = document.getElementById('email').value;
        var password = document.getElementById('password').value;

        if (email.length < 4) {
            alert('Please enter an email address.');
            return;
        }

        if (password.length < 4) {
            alert('Please enter a password.');
            return;
        }

        firebase.auth().signInWithEmailAndPassword(email, password).then(function (firebaseUser) {
            var email = firebase.auth().currentUser.email;
            const options = {
                method: 'POST',
                url: 'LoginValidator',
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: `email=${email}`
            }
            url = 'LoginValidator'
            fetch(url, options)
                .then(response = > response.json())
                .then(data = > console.log(data))
                .catch(e = > console.error(e))
        }).catch(function (error) {
            var errorCode = error.code;
            var errorMessage = error.message;
            if (errorCode === 'auth/wrong-password') {
                alert('Wrong password.');
            } else {
                alert(errorMessage);
            }
            console.log(error);
            document.getElementById('quickstart-sign-in').disabled = false;
        });
    }
    document.getElementById('quickstart-sign-in').disabled = true;
}

HTML

<div id="login-box" class="col-md-12">

    <div class="form-group">
        <input type="text" name="email" id="email" class="form-control login-input" placeholder="username">
    </div>
    <div class="form-group">
        <input class="form-control login-input" type="password" placeholder="Password" id="password" name="password">
        <i id="open" class="fa fa-eye fa-2x"></i>
        <i id="closed" class="fa fa-eye-slash fa-2x"></i>
    </div>
    <div class="form-group">
        <input type="submit" id="quickstart-sign-in" name="quickstart-sign-in"
               class="form-control btn btn-info btn-md login-bt" value="Login" onclick="toggleSignIn()">
    </div>
    <div class="form-group text-center forgot">
        <a href="#">Forgot username</a> / <a href="#">password?</a>
    </div>

</div>

下面是我的servlet

LoginValidator.java

public class LoginValidator extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        String email = request.getParameter("email");
        System.out.println("Printing email: "+email);

        try {

            System.out.println("inside try");

            User user = new User();
            UserRight userRight = new UserRight();

            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.registerTypeAdapter(Date.class, new DateTypeDeserializer());
            Gson gson = gsonBuilder.create();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BaseURLs.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();

            //Get user
            RestEndPointsInterface endPoint = retrofit.create(RestEndPointsInterface.class);
            Call<User> call = endPoint.getUserByEmail(email);
            user = call.execute().body();

            System.out.println(user.getName());

            //Get user rights
            Call<UserRight> userRightCall = endPoint.getUserRightByID(user.getUserRights().getIduserRight());
            userRight = userRightCall.execute().body();

            System.out.println(userRight.getUserRight());

            if(userRight.getUserRight().equals("admin"))
            {
                response.getWriter().write("{url:LoadSellPendingApprovals}");
            }
            else
            {
                response.getWriter().write("{url:index.html}");
            }


        } catch (Exception e) {
            e.printStackTrace();
        } 
    }

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

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

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

LoginValidator调用 LoadSellPendingApprovals ,下面是其代码

public class LoadSellPendingApprovals extends HttpServlet {


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        List<ProductSellAdvertisement> categoryList = new ArrayList<ProductSellAdvertisement>();

        try {

            System.out.println("INSIDE LoadSellPendingApprovals");

            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.registerTypeAdapter(Date.class, new DateTypeDeserializer());
            Gson gson = gsonBuilder.create();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BaseURLs.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();

            RestEndPointsInterface endPoint = retrofit.create(RestEndPointsInterface.class);
            Call<List<ProductSellAdvertisement>> call = endPoint.getAllPendingApprovals();
            categoryList = call.execute().body();

            for (int i = 0; i < categoryList.size(); i++) {
                System.out.println(categoryList.get(i).getProduct().getProductName());
            }

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally {
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/product-sell-pending-approvals.jsp");
            request.setAttribute("approvalList", categoryList);
            requestDispatcher.forward(request, response);
        }
    }


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

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


    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

这是我得到的错误

SyntaxError: Unexpected token < in JSON at position 0
    at (index):71

enter image description here

我的javascript代码中指向的行是-.then(response => response.json())

预期的行为是这样

  1. 用户输入凭据
  2. 使用firebase javascript api验证凭据
  3. 如果凭据正确无误,请将其发送到LoginValidator servlet,它将进一步检查用户的真实性。
  4. 然后LoginValidator将请求发送到LoadSellPendingApprovals,它将在其中执行以下代码

    RequestDispatcher requestDispatcher = request.getRequestDispatcher(“ / WEB-INF / jsp / product-sell-pending-approvals.jsp”);             request.setAttribute(“ approvalList”,categoryList);             requestDispatcher.forward(请求,响应);

除了我得到的错误之外,我也从未转发到JSP页面。我该如何解决这个问题?

我来自Java和移动背景,对Javascript技术没有太多了解。因此,感谢您提供详细的明确答案。

1 个答案:

答案 0 :(得分:0)

您的错误表明结果“ body”不包含JSON,但包含HTML:

  

意外的令牌

JSON看起来像这样:

{ key: value }

HTML看起来像这样:

<html>....</html>

由于错误状态,第一个<(位置0)是“意外令牌”。曾经阅读过的人体都期待着{

一个可能的原因是您正在发送的请求被重定向到登录页面,因此您获得HTML而不是预期的JSON。否则,您会得到一个错误页面,您正尝试将其传递给JSON解析器。

不幸的是,由于缺少这些信息,很难说清。您应该调试代码并检查得到的响应。