I know this has been asked many times before here, but after reading dozens of answers and solutions of other threads, I haven't been able to solve my issue.
I am currently working on a computer where I do not have administrative privileges, and my best guess is that the firewall blocks the server on localhost.
Here is my code:
GetTimeServlet.java
//I have tried overriding
public class GetTimeServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doPost (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
reader.close();
}
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setHeader("Access-Control-Allow-Origin", "*");
PrintWriter out = response.getWriter();
newtest.DbQueries dbq = new newtest.DbQueries();
out.print((int) Math.round(dbq.getSiteScore(sb.toString())));
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>exjobb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>GetTime</servlet-name>
<servlet-class>servlets.GetTimeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetTime</servlet-name>
<url-pattern>/get-current-time</url-pattern>
</servlet-mapping>
</web-app>
index.html
I have a button which runs the following function onClick="ajaxAsyncPostRequest('http://localhost:8080/ajaxdemo/get-current-time', $('#temp').val()):
function ajaxAsyncPostRequest(reqURL, temp)
{
temp = encodeURIComponent(temp);
var params = "site=" + temp + "&userrating=" + $("#slider").val() + "&usercomment=" + $("#comment-textarea").val()
+ "&chkbox1=" + $("#sq_checkbox1").val() + "&chkbox2=" + $("#sq_checkbox2").val();
//Creating a new XMLHttpRequest object
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest(); //for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //for IE6, IE5
}
//Create a asynchronous GET request
xmlhttp.open("POST", reqURL, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//When readyState is 4 then get the server output
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200)
{
gauge.refresh(xmlhttp.responseText);
//alert(xmlhttp.responseText);
}
else
{
//alert(xmlhttp.status);
}
}
};
xmlhttp.send(params);
}
The form-data is clearly sent in Post, and the server handles only Post requests. I'm not getting any errors or warnings either in Eclipse. What's going on here?
EDIT: I'm trying to do POST and not GET.
for HTTP GET method you should define doGet method in your servlet (GetTimeServlet.java);
Related
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 {
----------------------
---------------------------
}
This question already has answers here:
HTTP Status 404 - Servlet [ServletName] is not available
(4 answers)
Closed last year.
I'm trying to get a web page to send JSON data to a java servlet via a jQuery ajax POST.
I've already checked everything I could think of, but I still can't figure out why I keep getting a 404.
Even more confusing is that other calls to the same context path work correctly.
My web.xml
<web-app>
<servlet>
<servlet-name>Controller</servlet-name>
<servlet-class>com.vibridi.klyr.servlet.Controller</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>CustomerServlet</servlet-name>
<servlet-class>com.vibridi.klyr.servlet.CustomerServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>/klyr</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CustomerServlet</servlet-name>
<url-pattern>/klyr/customer/*</url-pattern>
</servlet-mapping>
My ajax call:
$.ajax({
url: "customer/save",
type: "POST",
data: JSON.stringify(o),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(obj) {
alert('Customer saved');
},
error: function(obj) {
alert('Error!');
}
});
My servlet:
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger("KLYR_LOGGER");
private CustomerManager manager;
public void init(ServletConfig sconfig) throws ServletException {
super.init(sconfig);
manager = new CustomerManager();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//stuff
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("application/json;charset=utf-8");
try {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null) {
sb.append(line);
}
manager.saveCustomer(sb.toString());
} catch(Exception e) {
logger.log(Level.SEVERE, "Data processing failure: " + e.getMessage());
out.write(Convertor.createBaseJSON(JSONType.E).toString());
out.close();
}
out.write(Convertor.createBaseJSON(JSONType.S).toString());
out.close();
}}
}
I can see from the Chrome's debugger tools that the call is properly directed to http://localhost:8080/klyr/customer/save but it 404's, whereas http://localhost:8080/klyr does not.
Thanks a lot!
EDIT:
I've tried to switch the servlet mappings over, i.e. /klyr (the working one) on CustomerServlet and /customer/save on Controller, but nothing happens, in fact when I call /klyr from the browser bar instead of seeing the response from CustomerServlet.doGet I still see the welcome page as if Controller.doGet fired. It looks like tomcat isn't reloading the web.xml file even if I restart it. Any ideas?
This is obvious because your CustomerServlet does not bind to $.ajax({url: "customer/save", ... so it won't work, your should change the below code :
<servlet-mapping>
<servlet-name>CustomerServlet</servlet-name>
<url-pattern>/klyr/customer/*</url-pattern>
</servlet-mapping>
to something like:
<servlet-mapping>
<servlet-name>CustomerServlet</servlet-name>
<url-pattern>/customer/save</url-pattern>
</servlet-mapping>
in order to solve the problem ~
I've eventually found the culprit, gonna post it here as a reference for other people.
Both servlets mapped in my web.xml are loaded on startup.
The first servlet attempted to read a config file from an incorrect path inside its init() method, but couldn't find it and threw an exception. The Catalina startup routine exited before it could load the second servlet, hence the 404 error.
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")
I have a Dynamic application in which I have a JSP file which is sending a string to a Servlet which is in another project which is a Web application Project. I am using Tomcat server in JSP project and the server is starting just fine but when I am trying to run the web application on local host I am getting HTTP ERROR 500
Problem accessing /jsptoservlettocloud. Reason: INTERNAL_SERVER_ERROR
This is my JSP FILE
<body>
<%
String str= "Shanx";
URL u = new
URL("http://localhost:8080/ServletToCloud/JSPToServletToCloudServlet");
HttpURLConnection huc = (HttpURLConnection)u.openConnection();
huc.setRequestMethod("GET");
huc.setDoOutput(true);
ObjectOutputStream objOut = new ObjectOutputStream(huc.getOutputStream());
objOut.writeObject(str);
objOut.flush();
objOut.close();
%>
</body>
This is my Servlet Class
public class JSPToServletToCloudServlet extends HttpServlet
{
String str;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
try
{
str= (String) ois.readObject();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
finally
{
ois.close();
}
System.out.println("Servlet received : " + str);
}
}
This is my 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>
In the url ServletToCloud is the name of the web application project and JSPToServletToCloudServlet is the name of the servlet. Is this url correct.
In your jsp you have http://localhost:8080/ServletToCloud/JSPToServletToCloudServlet but you have /jsptoservlettocloud in your web.xml
Your mapping is wrong.
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);