Hey Guys,
I am using Ajax with JSP.What I am trying to do is when the user enters a name and clicks on the button it goes to a jsp page.
On the jsp page it is checked whether the name is present in the database or not. If it is present then the table is shown with the name and the corresponding password.
Till this it is working fine but when the name is not found in the database i want to redirect to another page. I don't know how to do this.
Please give some code.

Dani AI

Generated

— when an Ajax request hits a JSP, a server-side redirect (for example response.sendRedirect(...)) will not navigate the browser window. The XHR/fetch call may follow a 3xx and return the final response body to your script, but it will not change window.location. Also, as pointed out, do not return plaintext passwords; use a reset flow or masked output for testing only.

A simple, reliable pattern: have the JSP return a small JSON result that indicates whether the lookup succeeded and, if not, include a redirect URL. The client-side code checks that JSON and either updates the DOM or performs window.location.href = ....

Example client-side (fetch):

fetch('/lookup.jsp?name=' + encodeURIComponent(name))
  .then(res => res.json())
  .then(data => {
    if (data.found) {
      // populate result area
    } else if (data.redirect) {
      window.location.href = data.redirect;
    } else {
      // show "not found" message
    }
  });

Example server-side (JSP sketch):

<%
  String name = request.getParameter("name");
  boolean found = /* perform DB lookup safely */;
  response.setContentType("application/json");
  if (found) {
    out.print("{\"found\":true}");
  } else {
    out.print("{\"found\":false,\"redirect\":\"/notfound.jsp\"}");
  }
%>

Troubleshooting: check the Network tab to see the raw response and status code; ensure Content-Type: application/json; handle CORS if cross-origin; and always escape or build JSON safely (use a library rather than concatenation in production).

Recommended Answers

All 5 Replies

Anuj576,

You want to display a name and the corresponding password? :confused:

In a secure system, passwords are typically stored in an irreversably encrypted form and never displayed to anyone, not even a top level administrator.

If I understand correctly :
a) It sounds like you are inviting password theft.
b) You neither want nor need AJAX.

Airshow

It's just test pgm and for my personal use. Please provide the logic.

Start here.

You might also like to explore Apache Struts, which offers a different approach (and best of luck with it). It is probably OTT for your needs but worth knowing about.

Airshow

The link is not working.

Sorry, my mistake - it was meant to be this.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.