0

So here is the problem I have a connection form sending a Post request to servlet. this servlet forwards the request to different pages after doing some tests (password, email verification of user). Only problem is I get the correct page as a response when looking at my POSTrequest but the page doesn't display in my web browser. How come?

Here's my code.

sign in 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>

signIn class

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);
    }
}

As you can see in the signIn.jsp I have ${connect.error} supposed to show me the error message. I repeat myself but I can see this message displayed using debugger but not on my web browser. So what happens is after POST it stays on the web page path and I get the HTML only in the response.

EDIT

here is a screenshot

view on debugger Any help is greatly appreciated.

JSmith
  • 4,519
  • 4
  • 29
  • 45
  • connect.error isn't going to show you anything. Unless you specifically set the attribute and forward it to your jsp. In your angular section, you're not doing anything with the response. – Jonathan Laliberte Nov 07 '18 at 14:27
  • in other words you're misunderstanding the process here. You're making an ajax request, but you're not writing anything to the response in your servlet. (nor are you handling the response in the js) - if you are using ajax, you can't just setAttribute and expect it to appear like this. – Jonathan Laliberte Nov 07 '18 at 14:28
  • @JonathanLaliberte well I can see the desire result in my debugger with the `connect.error` being well populated. and `this.getServletContext().getRequestDispatcher("/signIn.jsp").forward(request, response);` is here to update the view on my browser. But it's not showing. It worked with a simple `post`request from form. What am I oing wrong can you explain me. Many thanks in advance – JSmith Nov 07 '18 at 14:32
  • yes, like i said, you want to make an ajax request right? Well that's not how you do them. I'll post an example below. – Jonathan Laliberte Nov 07 '18 at 14:33
  • is it alright if i show you it without angular? – Jonathan Laliberte Nov 07 '18 at 14:34
  • @JonathanLaliberte well if you coul answer me what I'm doing wrong I will try translate with angularjs and upvote it of course if it works I will mark it as answered. I really appreciate your help I'm stuck. – JSmith Nov 07 '18 at 14:37
  • @JonathanLaliberte I've just added a screenshot. – JSmith Nov 07 '18 at 14:49
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/183243/discussion-between-jsmith-and-jonathan-laliberte). – JSmith Nov 07 '18 at 14:54

1 Answers1

2

ok so i'm not familiar with angular but just looking at the w3 for the ajax, you need to handle the response something like this:

add id to your span element (remove ${connect.error} from it):

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

add a then success:

   <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>

then for your 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.

}

EDIT:

The answer here is great for learning about ajax and servlets:

How to use Servlets and Ajax?

Jonathan Laliberte
  • 2,672
  • 4
  • 19
  • 44