AJAX call is not reaching Servlet - java

I am trying to make a simple textbox which initiate a suggestive feedback based on the characters entered by the user. I am trying to fetch a JSON object from a Servlet but my AJAX call is somehow not reaching the servlet. On checking the status of AJAX request using this.status I am getting error code 404. Can anyone suggest me a solution:
[![enter image description here][1]][1]
Here's my servlet: FetchServ.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
Connection con;
ResultSet rs;
java.sql.PreparedStatement pst;
String ch = request.getParameter("q");
String data;
ArrayList<String> list = new ArrayList();
response.setContentType("application/JSON");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("drivers registered");
con = DriverManager.getConnection(con_url, userID, password);
System.out.println("connection created");
pst = con.prepareStatement("SELECT * FROM candidates where FirstName LIKE ?");
pst.setString(1, ch + "%");
rs = pst.executeQuery();
System.out.println("query executed");
while(rs.next())
{
data = rs.getString("FirstName");
list.add(data);
}
String json = new Gson().toJson(list);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
response.getWriter().append("Served at: ").append(request.getContextPath());
} catch (SQLException | ClassNotFoundException e) {
System.err.println(e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
the jsp code:
<script>
function suggest(str){
if(str.length == 0){
return;
}else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
document.getElementById("sugg").innerHTML = this.status;
if(this.readyState == 4 && this.status == 200){
//var res = JSON.parse(this.responseText);
document.getElementById("sugg").innerHTML = this.responseText;
}
};
try{
xmlhttp.open("GET", "com.test.java/FetchServ", true);
xmlhttp.send();
}catch(e)
{
alert("unable to connect ");
}
}
}
</script>
</head>
<body>
<form>
Search:<input type="text" onkeyup = "suggest(this.value)">
</form>
<p id = "sugg"></p>
</body>
</html>
and this is the result I am getting:
[![enter image description here][2]][2]
<display-name>ACtxtbox</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FetchServ</servlet-name>
<servlet-class>com.test.java/FetchServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FetchServ</servlet-name>
<url-pattern>/FetchServ</url-pattern>
</servlet-mapping>
</web-app>

your Web.xml entries are not proper, check the url which you are using in urlbar and the form submitted using xmlhttp.open("GET", "fetch", true); you can debugg the actual url passed as a request to the server by opening developer tools and navigating to the network tab it will look something like below.
also your <servlet-class>ACtxtbox/FetchServ</servlet-class> is not correct, it should be with package path like <servlet-class>sompackagepath.FetchServ</servlet-class>
EDIT
As per your images, I can see you have declare index.jsp which will be accesible by giving url: http://localhost:<port_number>/ACtxtbox/index.jsp.
Now you should note below points:
As you are calling servlet using ajax call where you have given
parameters as fetch in this line of code in you javascript
xmlhttp.open("GET", "fetch", true); hence it is now changing your
url to http://localhost:<port_number>/ACtxtbox/fetch
your web.xml entry should be like this
<servlet>
<servlet-name>FetchServ</servlet-name>
<servlet-class>com.rishal.test.FetchServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FetchServ</servlet-name>
<url-pattern>/fetch</url-pattern>
</servlet-mapping>
How come your url pattern is coming like
http://localhost:<port_number>/ACtxtbox/com.test.java/fetch ? is
it you have modified the web.xml entries. Please read the tutorials
and google about web application,jsp,servlets and ajax calls. you
should also note that you have to create your servlet class under
some package as i have given in the web.xml entry
com.rishal.test its package path and class is inside this package
path.
package com.rishal.test;
public class FetchServ extends HttpServlet {
----------------------
---------------------------
}

Related

JAVA - get response from system to the UI

I'm new to java and I have servlet which connect to some system and get data, while debug the code I see that I was able to connect and get the data, ( I dont get any error) . I use the following code :
try {
urlConnection.connect();
} catch (IOException e) {
String messagePrefix = "Connection error: ";
LOGGER.error(messagePrefix, e);
}
OutputStream clientOutStream = responseToClient.getOutputStream();
copyStream(backendInStream, clientOutStream);
responseToClient.setStatus(backendResponseCode);
int backendResponseCode = urlConnection.getResponseCode();
InputStream backendInStream = null;
try {
if (backendResponseCode < 400) {
backendInStream = urlConnection.getInputStream();
}
} catch (IOException e) {
String messagePrefix = "Input stream error: ";
LOGGER.error(messagePrefix, e);
}
Now I have this simple index.html and my question how should I print the data back to the browser ?
( I wasnt able to copy the html file as code :(
Any idea how to pass the response to the UI , I try to add response tag and put the variable as global without success...
Yes you can send the response using dispatcher or httpsession and use jsp to get the response in UI
in your back end simply use
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("backendresponse",backendresponse))
}
and in your jsp you can get and store that data in an arraylist as
<%
ArrayList<> list=(ArrayList<>)session.getAttribute("backendresponse");
%>
Now you can use this list to populate data in any tag using <%= %> as this is equivalent to a print statement as any expression say
<%for(int i=0;i<list.size();i++)
{%>
<%=list.get(i).getData() %>
<%}%>
will print the response in your browser
UPDATE
in your servlet you can get the parameters as
String url=request.getParameter("url")
Class obj=new Class(url)
session.setAttribute("obj",obj);
response.sendredirect("disp.jsp")
in your disp.jsp
<%
ArrayList<> list=(ArrayList<>)session.getAttribute("backendresponse");
%>
<html>
<head>
</head>
<body>
<%for(int i=0;i<list.size();i++)
{%>
<h1> <%=list.get(i).getData() %></h1>
<%}%>
</body>
</html>
You should have doGet method which has PrintWriter taking each line of the HTML:
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
.
.
.
}

Redirecting servlet to another html page

I have two html pages - one for login and one that takes in a persons details. The login page is the first page and when the database is checked for the username and password, the user is allowed to enter their details. The SQL code works perfectly, it is just a problem with the mapping I am having. I am using the Tomcat server by the way. Could anybody help or spot what i am doing wrong?
This is my java code for logging in and entering details
public class Details extends HttpServlet {
private Connection con;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
//return writer
PrintWriter out = res.getWriter();
String username = req.getParameter("username");
String password = request.getParameter("password");
out.close();
try {
login(username, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
res.sendRedirect("/redirect.html");
String name = request.getParameter("name");
String address = request.getParameter("address");
String age = request.getParameter("age");
out.println("<HTML><HEAD><TITLE>Personnel Details</TITLE></HEAD><BODY>");
out.println(name + address + age);
out.println("</BODY></HTML>");
System.out.println("Finished Processing");
}
out.close();
}
In my web.xml file I have:
<web-app>
<servlet>
<servlet-name>Details</servlet-name>
<servlet-class>Details</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Details</servlet-name>
<url-pattern>/Details</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>redirect</servlet-name>
<url-pattern>/redirect</url-pattern>
You may try this :
response.sendRedirect("redirect.html");
or
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "redirect.html");
Alternative way,
ServletContext sc = getServletContext();
sc.getRequestDispatcher("/redirect.html").forward(request, response);
Redirect to HTML
RequestDispatcher ds = request.getRequestDispatcher("index.html");
ds.include(request, response);
you can use
1.response.sendRedirect("redirect.html") or
2.String path= "/redirect";
RequestDispatcher dispatcher =servletContext().getRequestDispatcher(path);
dispatcher.forward(request,response);

HttpSession with Servlet + Java not working

i have the following pice of code 'anmelden.java':
#WebServlet("/anmelden")
public class anmelden extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String benutzer = request.getParameter("benutzer");
String passwort = request.getParameter("passwort");
try {
PrintWriter out = response.getWriter();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test","admin","*****");
PreparedStatement stmt = con.prepareStatement("SELECT benutzer,passwort,rolle FROM login WHERE benutzer = ? AND passwort = ?");
stmt.setString(1, benutzer);
stmt.setString(2, passwort);
ResultSet rs = stmt.executeQuery();
if(rs.next())
{
HttpSession session = request.getSession();
session.setAttribute("benutzer", rs.getString("benutzer"));
RequestDispatcher dis = request.getRequestDispatcher("mandant.jsp");
dis.forward(request, response);
out.print("1");
}
else
{
out.print("Benutzername und/oder Passwort falsch");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my jsp file 'login.jsp':
$("#anmelden").click(function(){
var benutzer = $("#benutzer").val();
var passwort = $("#passwort").val();
if(benutzer == "" || passwort == "")
{
return;
}
$.ajax({
url:"anmelden",
type:"POST",
data:"benutzer="+benutzer+"&passwort="+passwort
}).success(function(data){
var erfolg = data;
if(erfolg == "1")
{
window.location.href="http://localhost:8080/PSD/mandant.jsp";
}
else
{
$("#ok").text(erfolg);
}
});
});
As u can see i tries to set the name coming from my DB into my session Attribute.
I want to use the Attribute in my 'mandant.jsp' file.
But it dosen't work - all what happens is, that my 'login.jsp' file which makes the ajax call, print the code from 'mandant.jsp' into my div as text.
So it dosen't opend the next page as i want -.-
But if i comment out the HttpSession block then it works fine but then i can't use ,of course,the session Attribute.
So what's wrong or what must i change so that this code works?
Many thanks
This is because this part of the code:
RequestDispatcher dis = request.getRequestDispatcher("mandant.jsp");
dis.forward(request, response);
is generating the HTML from mandant.jsp file using the request object (along with HttpSession and ServletContext) to fulfill any Expression Language and writing this HTML into the response. Just remove these lines and you'll be ok.
You are mixing two types of communication here, from the JSP page you are making an ajax call but from the Servlet you are making a Dispatch redirect.
If you want the login page to be redirected after a a successful login then don't call the Servlet with an ajax call and better do a form submit.
If you rather want to only check credentials on the servlet and redirect from the client then keep the ajax call but avoid the request dispatcher in the servlet and return a success/error code instead. Then capture that code from the ajax response and redirect to a successful page if you want.

Getting null While Passing String from jsp to servlet

This is my Jsp File
<body>
<%
URL url = new
URL("http://localhost:8080/ServletToCloud/JSPToServletToCloudServlet");
URLConnection conn =url.openConnection();
conn.setDoOutput(true);
BufferedWriter bw= new BufferedWriter( new OutputStreamWriter(
conn.getOutputStream() ) );
bw.write("username= Shanx");
out.flush();
out.close();
%>
</body>
This is my servlet class
#SuppressWarnings("serial")
public class JSPToServletToCloudServlet extends HttpServlet
{
private final static String _USERNAME = "username";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
String username = request.getParameter(_USERNAME);
response.setContentType("text/html");
out.println("HelloWorld");
out.println("Hello " + username);
out.close();
}
This is the web.xml file
<servlet>
<servlet-name>JSPToServletToCloud</servlet-name>
<servlet-class>pack.exp.JSPToServletToCloudServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JSPToServletToCloud</servlet-name>
<url-pattern>/jsptoservlettocloud</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
My Jsp File is in Dynamic Web Application and is sending a string to Servlet which is in Web application Project. I am running the dynamic web application project on apache tomcat server and after the server is started I am running my web application projewct as web application and checking on local host and getting null.
Help me out guys.
you will have to put username name wither in session, because you are not set the username in request.
put user name in session and on server Side write :-
HttpSession session = request.getSession();
String username = session.getAttribute("username")

XmlHttpRequest status=0

I have this ajax call from a javascript file and I want to pass as a parameter the id of the user that I want to delete:
function eliminaUtente(id,nome){
if (confirm("Sei sicuro di voler eliminare l'utente "
+ nome
+ "?")) {
var xmlHttp2 = new XMLHttpRequest();
xmlHttp2.open("POST", "EliminaUtente", true);
xmlHttp2.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
var params2 = "id=" + id;
xmlHttp2.send(params2);
xmlHttp2.onreadystatechange = function() {
if (xmlHttp2.readyState == 4)
{
alert(xmlHttp2.status); <-----------this prints always 0!
if (xmlHttp2.status == 200) //
{
alert("utente eliminato!");
} else {
alert("An error occurred while communicating with server.");
}
}
};
}
}
in the correspondant Servlet called EliminaUtente i have this code:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String id = request.getParameter("id");
System.out.println(id);
String query = "delete from utente where idutente=" + id;
System.out.println(query);
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager
.getConnection("jdbc:mysql://localhost/Spinning?user=root");
PreparedStatement prest = con.prepareStatement(query);
prest.executeUpdate();
response.setContentType("text/plain");
PrintWriter ajaxWriter = response.getWriter();
ajaxWriter.print("ok");
ajaxWriter.flush();
ajaxWriter.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
response.setContentType("text/plain");
PrintWriter ajaxWriter = response.getWriter();
ajaxWriter.print("ko");
ajaxWriter.flush();
ajaxWriter.close();
}
}
}
I can't understand where is the problem...can you help me please? ;)
I try your code and change a little bit i want to explain what did i and what i learn from it.I read some source. First i read XMLHttpRequest object and onreadyState event.
I implement your example both PUT and GET action method.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.test.testServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
</web-app>
testServlet.java
package com.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class testServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
/*super.doPost(req, resp);*/
String strId = req.getParameter("id");
System.out.println(strId);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doGet(req, resp);
String strId = req.getParameter("id");
System.out.println(strId);
}
}
and main part NewFile.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<input type="button" value="Submit" onclick="eliminaUtente('1')" width="100%" />
</body>
<script language="javascript" type="text/javascript">
function eliminaUtente(id) {
var xmlHttp = new XMLHttpRequest();
var url = "test/NewFile.jsp?id=" + id;
xmlHttp.open("POST", url, true);
xmlHttp.send(url);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert("utente eliminato!");
} else {
alert("An error occurred while communicating with server.");
}
};
}
</script>
</html>
with this way i write the parameter 1(i hardcode it in jsp file method invoke) and write it to console, the first thing in here the difference your code and mine i remove the xmlHttp2.setRequestHeader("Content-type","application/x-www-form-urlencoded"); because if the method type is POST default encryption is this.
enctype = content-type [CI]
This attribute specifies the content type used to submit the form to the server (when the value of method is "post"). The default value for this attribute is "application/x-www-form-urlencoded". The value "multipart/form-data" should be used in combination with the INPUT element, type="file".
So no need to enctype default is OK for POST.
And this is open method signature open(method, url, async, user, password) here async is the parameter which means if it is false don't wait a response from server implement the other line when response is come it will run. If it is true wait until response is come. Actually i try bot of them and it is worked.
Lastly i try it with GET. If you want use it with GET you should add xmlHttp2.setRequestHeader("Content-type","application/x-www-form-urlencoded"); code for encryption and remove the url parameter from send() method.
function eliminaUtente(id) {
var xmlHttp = new XMLHttpRequest();
var url = "test/NewFile.jsp?id=" + id;
xmlHttp.open("GET", url, true);
xmlHttp2.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert("utente eliminato!");
} else {
alert("An error occurred while communicating with server.");
}
};
}
Note: I try this code in firefox, i create xmlHttpRequest object. For all browser(include IE6) sure you know use:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
typo?
alert(xmlHttp2.status); <-----------this prints always 0! Now has "2'
The problem was that I have to put false in this line:
xmlHttp2.open("POST", "EliminaUtente", FALSE);

Categories