Redirecting Java EE servlet pages while transferring data to the controller

Having trouble with page redirection from Servlet despite hours of searching for a solution. Any help would be greatly appreciated. Here's the JavaScript code:

$("#login_form_submit").click(function(){
var form = $('#login_form');
    $.ajax({
            type: "Post",
            url: "AccountServlet",
            data: form.serialize(),
            dataType: "json",

            //if received a response from the server
            success: function( data, textStatus, jqXHR) {
                 if(data.success){
                    $("#ajaxResponse").html("");
                    console.log(data);

                    if (data.User.role == 1){
                        main.user = data.User; 
                        //window.location.href = "Student_home.jsp";
                    }
                 } 
                 //display error message
                 else {
                    $("#ajaxResponse").html("<div><b>Something goes wrong check your email or password</b></div>");

                 }
            },

            //If there was no response from the server
            error: function(jqXHR, textStatus, errorThrown){
                 $("#ajaxResponse").html("<div><b>Something goes wrong check your email or password</b></div>");
                 $("#ajaxResponse").html(jqXHR.responseText);
            },

            //capture the request before it was sent to server
            beforeSend: function(jqXHR, settings){
                //disable the button until we get the response
                $('#login_form_submit').attr("disabled", true);
            },

            //this is called after the response or error functions are finsihed
            //so that we can take some action
            complete: function(jqXHR, textStatus){
                //enable the button 
                $('#login_form_submit').attr("disabled", false);
            }

        });        

});

And here's the servlet code:

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

    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");


    String userName = request.getParameter("userName");
    String password = request.getParameter("password");
    DatabaseWrapper context = new DatabaseWrapper();
    User user = context.Check_login(userName, password);
    session.current_user = user;
    Gson gson = new Gson(); 
    JsonObject myObj = new JsonObject();

    if (user == null){
        myObj.addProperty("success", false);
        out.println(myObj.toString());
    }else if (user instanceof Student){
        JsonElement userObject = gson.toJsonTree((Student)user);
        myObj.addProperty("success", true);
        myObj.add("User", userObject);
        out.println(myObj.toString());

        out.close();
        //response.setStatus(HttpServletResponse.SC_FOUND); 
        response.sendRedirect("Student_home.jsp");
        return;
    }

I also tried using this piece of code:

RequestDispatcher dispatcher = request.getRequestDispatcher("/Student_home.jsp");
        dispatcher.forward(request, response);

but it didn't work. Any suggestions?

I prefer using only JavaScript for now, but I need to redirect from the servlet!

I attempted to use this line in JavaScript:

window.location.href = "Student_home.jsp";

Found the solution but couldn't post it as an answer. The issue lies in redirecting the Ajax call without preventing it. The workaround involves creating a form element in the jQuery success response and submitting it naturally:

function Redirect (servlet , method_type){
  var form = $(document.createElement('form'));
  $(form).attr("action", servlet);
  $(form).attr("method", method_type);
  $(form).css("display", "none");
  form.appendTo( document.body );
  $(form).submit();
}

Problem solved, thanks everyone!

Answer №1

Once you have called close(), there is no action that can be taken on the response.

When dealing with headers, it is crucial to note that they cannot be modified after the response has been committed. In situations involving redirection, refrain from writing anything to the response.

The same principle holds true for RequestDispatcher.forward(). Avoid making any modifications to the response prior to forwarding and ensure not to close() the response at any point.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the byte order of the incoming packet in a Java application?

I've been developing a UDP Java Server that is designed to receive UDP Datagram Packets containing status messages from a device. The packets include multibyte numbers like field LEN, which are sent in little-endian format. My query pertains to the f ...

Unable to properly load the Kendo Tree View based on the selected option from the combo box in the Kendo UI framework

I am encountering an issue where the Kendo treeview is not populating with different values based on a selection from the Kendo combo box. I have created a JSFiddle to showcase this problem. http://jsfiddle.net/UniqueID123/sample In the scenario provided ...

Multiple Ajax(Jquery method) Submissions with just one click and issue with Image not being sent to the server

Having trouble submitting form data to the server after client-side validation using jQuery. I've been working on this all day and could really use some help. I created a jQuery slider for my login form, where it slides to the next input field after v ...

Tips for Fixing the JSON Error in Firefox

My Response Header consists of: Access-Control-Allow-Meth... GET, POST Access-Control-Allow-Orig... * Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Connection Keep-Alive Content-Length 81 Content-Type text/html ...

The spyOn function was unable to locate an object to spy on for the start() method

I've been utilizing the angular-cli testing framework for my project. Within one of my components, I decided to include the 'ng2-slim-loading-bar' node module. submit(){ this._slimLoadingBarService.start(() => { }); //perfor ...

Launch a modal by clicking a button located in a separate component using Vue JS

I am dealing with 2 components: TestSearchTool and TestModal. My goal is to display the Modal when a button in the TestSearchTool component is clicked. These two components are siblings in the hierarchy, so I am struggling to pass values between them (even ...

Return a string to the client from an express post route

I'm attempting to return a dynamically generated string back to the client from an Express post route. Within the backend, I've set up a post route: router.post('/', async (req, res) => { try { // Here, I perform computations on ...

Arranging Maven test classes in a customized directory structure

Current Tools : Apache Maven 3 Challenge : Currently, I am facing an issue with a legacy project where Junit test classes do not adhere to the standard maven directory structure (src/test/java) They are structured as follows. src -- org -- ...

The functionality of the Ajax alert success message has experienced a failure

Issue with alert message not working in code. Using Firefox - unsure if browser is the issue. Assistance needed as I am new to this. Snippet of my code: $("#enquiry").on("click",function(){ $.ajax({ url: "<?php echo ...

What is the proper way to integrate jQuery validation into an AJAX form within an MVC application?

While working on my MVC application, I encountered an issue with the validation of an Ajax form using jQuery validation. The problem stemmed from the date fields being in a UK format instead of US (as intended since I am based in the UK), so I implemented ...

Generating data within an express route (with the use of socket.io-client)

Recently, I made the decision to refactor my code in order to separate the front and back end, which were previously combined into one service. However, I am now facing an issue where I need the web server to emit data to the data server after validation. ...

Subclass of JPanel failing to render complete shape

While working with my JPanel subclass and overriding the paintComponent(Graphics g), I encountered an issue. After calling g.drawRect(0, 0, 500, 75), only one side of the rectangle is being drawn when I run my program. The code in my main method includes ...

Is there a way to maintain the original style of an HTML element when printing it?

When attempting to print an HTML element using window.print();, the original style is not preserved. How can this issue be resolved? printInvoice() { var mywindow = window.open("", "PRINT"); mywindow.document.write("<html>"); mywindow.d ...

"Encountering a 'Handlebars is not a function' error while using express

Received code snippet from a website const express = require('express'); const app = express(); const port = 3000; //Load handlebars module const handlebars = require('express-handlebars'); //Set the app to use the handlebars engine app ...

Sending the handleSubmit() function to the child component does not alter the state of the parent component

I just started learning React and Javascript. Currently, I am working on a form where users can specify the details of a "Mob". Upon submitting the form, I anticipate that handleSubmit() (which is passed down from the parent component) will update the sta ...

Ways to resolve the error "Expected an assignment or function call but found an expression with no-unused-expressions"

Issue : Error in ./src/components/main.js Line 7: No function call or assignment found, only an expression is present (no-unused-expressions) Search for the specific keywords to get more information on each error. import React from 'react'; ...

Require a split dropdown feature that does not rely on bootstrap

After searching extensively for a split button dropdown field without relying on any bootstrap package, I came up empty-handed. It seems like such a specific feature is hard to find without external dependencies. https://i.sstatic.net/stoMz.png ...

Is there a way to access the Flask global in AngularJS?

I'm in the process of developing an internal web application using Flask that connects to various clusters. The majority of the URLs begin with /cluster/cluster_name, which is why I've implemented the following code in my blueprints: cluster = B ...

Utilizing a series of linked jQuery functions

Is there a more efficient way to write this code snippet? $('#element').html( $('#element').data('test') ); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="el ...

Is there a record in Hibernate HQL?

I am currently fetching the latest 21 records using the following code snippet: String hql = "SELECT c from Model c WHERE c.status = true ORDER BY c.addedOn DESC"; modelList = session.createQuery(hql).setMaxResults(21) .get ...