Problem in request via ajax

0

I have a JSP login page on my system, but when trying to perform a request via ajax to authenticate me, the form does not seem to be sending correctly, as it is redirected to the login page itself.

Ajax Code:

$( document ).ready( function()
{
    $( '#submitLogin' ).click( function( e )
    {                        
        e.preventDefault();

        $.ajax
        ({
            type: 'POST',
            url: '/system/users?parameter=login',
            data: $( '#loginForm' ).serialize(),
            success: function( msg ) 
            {
                if ( $.trim( msg ) === "ERROR" )
                {
                    loginErrorAlert();

                    $( '#userLogin' ).val( "" );
                    $( '#userPassword' ).val( "" );

                    $( '#userLogin' ).focus();
                }
            }
        });
    });
});

DoPost Method:

protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
    String parameter = request.getParameter( "parameter" );

    if ( parameter.equals( "login" ) ) 
    {   
        try
        {
            if ( LoginController.getInstance().authenticateUser( request, response ) )
            {                   
                response.sendRedirect( "home.jsp" );
            }

            else
            {                    
                response.setContentType( "text/plain" );
                response.setCharacterEncoding( "UTF-8" );

                response.getWriter().println( "ERROR" );
            }
        }

        catch ( Exception e )
        {
            System.out.println( e.toString() );
        }
    }
}

web.xml:

<servlet>
    <servlet-name>Users</servlet-name>
    <servlet-class>servlet.Users</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>Users</servlet-name>
    <url-pattern>/users</url-pattern>
</servlet-mapping>
    
asked by anonymous 26.11.2017 / 02:05

1 answer

1

It has if checking if the message is equal to ERROR , but there is no action if it is different from that. You can put window.location.href='pagina que deseja' . You will not be able to redirect with this code.

 if ( LoginController.getInstance().authenticateUser( request, response ) )
 {                   
    response.sendRedirect( "home.jsp" );
  }

Instead make response.getWriter().println( "home.jsp" );

And no javascript:

 if ( $.trim( msg ) === "ERROR" )
 {
     loginErrorAlert();

     $( '#userLogin' ).val( "" );
     $( '#userPassword' ).val( "" );

     $( '#userLogin' ).focus();

 }elseif($.trim( msg ) === "home.jsp")
 {
     window.location.href= $.trim( msg );
 }

A better solution would be to use the http response codes, and if it did, return a 403 for example. And with that you would add a function error{ //código } , right after success in javascript

    
26.11.2017 / 16:31