I can’t send the simplest request to the servlet using jQuery. But at the same time, if I send through the form, then everything works with a bang.
Below is the index.html from which I want to send the username. login.js, in which I form the request itself, SerletStore.java the servlet itself. And the structure of the whole project.
login.js
The only more or less working url = “http: // localhost: 8080 / testservlet / post “, and they “/ testservlet / post”, “testservlet / post”, “/ post,” “post” cause a 404 error.
function addNewVoting () {
var xhr = new XMLHttpRequest ();
var body = 'name =' + encodeURIComponent ("name") +
'& amp; surname =' + encodeURIComponent ("surname");
xhr.open ("POST", 'http: // localhost: 8080 / testservlet / post', true)
xhr.setRequestHeader ('Content-Type', 'application / x-www-form-urlencoded')
xhr.send (body);
};
function addNewVoting1 () {
var user = {
"firstName": "vlad"
}
var JSONString = JSON.stringify (user);
var url = "http: // localhost: 8080 / testservlet / post";
$ .ajax ({
url: url,
method: "post",
data: JSONString,
contentType: "application / json",
error: function (message) {
var JSONObject = JSON.parse (message);
console.log (JSONObject);
},
success: function (data) {
var JSONObject = JSON.parse (data);
console.log (JSONObject);
},
headers: {
"Accept": "application / json",
"Accept-Language": "en",
"Cache-Control": "max-age = 3600"
}
});
};
When the second function is called, it outputs this:
index.html
& lt;! DOCTYPE html & gt;
& lt; html & gt;
& lt; head & gt;
& lt; meta charset = "UTF-8" & gt;
& lt; title & gt; Login Form & lt; / title & gt;
& lt; link rel = "stylesheet" href = "css / login.css" & gt;
& lt; link rel = "stylesheet" href = "http://fonts.googleapis.com/css?family=Open+Sans:400,700" & gt;
& lt; script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" & gt; & lt; / script & gt;
& lt; script src = "/ js / login.css" & gt;
& lt; / script & gt;
& lt; / head & gt;
& lt; body & gt;
& lt; div id = "login" & gt;
& lt; form id = "form" name = "form-login" & gt; & lt;! - action = "store" method = "POST" & gt; - & gt;
& lt; span class = "fontawesome-user" & gt; & lt; / span & gt;
& lt; input type = "text" id = "user" name = "username" placeholder = "Username" & gt;
& lt; span class = "fontawesome-lock" & gt; & lt; / span & gt;
& lt; input type = "password" id = "pass" name = "password" placeholder = "Password" & gt;
& lt; input type = "input" id = "login-submit" value = "Login" & gt;
& lt; / form & gt;
& lt; input style = "margin-left: 30px; margin-top: 10px" type = "button" onclick = "addNewVoting ()" value = "TAKE" / & gt;
& lt; / div & gt;
& lt; / body & gt;
& lt; / html & gt;
ServletStore.java
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet (name = "post", urlPatterns = "/ post")
public class Servlet extends HttpServlet {
@Override
protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter ();
writer.print ("Hello");
}
@Override
protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost (req, resp);
}
}
Project Structure :
Another screenshot might help:
I also experimented with contentType, and either I did it wrong, or nothing works either. Please help !!!
Answer 1, authority 100%
In the doPost ()
method of your servlet, you only call the doPost ()
of the abstract parent class HttpServlet, which means that your servlet does not actually have a post request handler. But it is the post request that you send from the script. That is why you get a 405 “Method not supported” error.
Besides, I see that you have already messed up a lot in the script. Decide how you want to send data from the script to the servlet. A simpler option is in the form of query parameters. Then the script will look like this:
var userObj = {
"userName": "vlad"
}
var url = "http: // localhost: 8080 / test / post";
$ .ajax ({
url: url,
method: "post",
data: userObj,
error: function (message) {
console.log (message);
},
success: function (data) {
console.log (data);
}
});
And the doPost ()
method of the servlet is like this:
@ Override
protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userName = req.getParameter ("userName");
if (userName == null || "" .equals (userName.trim ())) {
userName = "Anonymous";
}
String greetings = "Hello" + userName;
resp.setContentType ("text / plain");
resp.getWriter (). write (greetings);
}
If sent as JSON data, then the script will be like this:
var userObj = {
"userName": "vlad"
}
var userJson = JSON.stringify (userObj);
var url = "http: // localhost: 8080 / test / post";
$ .ajax ({
url: url,
method: "post",
data: userJson,
contentType: "application / json",
error: function (message) {
console.log (message);
},
success: function (data) {
console.log (data);
}
});
And the code of the doPost ()
method will become much more complicated and require dependencies to work org.json.json :
@ Override
protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userName = "Anonymous";
StringBuffer sb = new StringBuffer ();
String line = null;
BufferedReader reader = req.getReader ();
while ((line = reader.readLine ())! = null)
sb.append (line);
try {
JSONObject jsonObject = new JSONObject (sb.toString ());
userName = jsonObject.getString ("userName");
} catch (JSONException e) {
// throw new IOException ("Error parsing JSON request string");
}
String greetings = "Hello" + userName;
resp.setContentType ("text / plain");
resp.getWriter (). write (greetings);
}