Sending an ajax post request to a servlet
I can't send the simplest request to the servlet using jQuery in any way. But at the same time, if I send it through the form, then everything works with a bang. I quote below index.html, from which I want to send the user's login. login.js, in which I form the request itself, SerletStore.java is the servlet itself. And the structure of the entire project.
Login.js The only more or less working url = " http://localhost:8080/testservlet/post", and they "/testservlet/post", "testservlet/post"," /post, "" post " cause error 404.
function addNewVoting() {
var xhr = new XMLHttpRequest();
var body = 'name=' + encodeURIComponent("name") +
'&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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Form</title>
<link rel="stylesheet" href="css/login.css">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400,700">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="/js/login.css">
</script>
</head>
<body>
<div id="login">
<form id="form" name="form-login"><!-- action="store" method="POST"> -->
<span class="fontawesome-user"></span>
<input type="text" id="user" name="username" placeholder="Имя пользователя">
<span class="fontawesome-lock"></span>
<input type="password" id="pass" name="password" placeholder="Пароль">
<input type="input" id="login-submit" value="Вход">
</form>
<input style="margin-left: 30px; margin-top: 10px" type="button" onclick="addNewVoting()" value="TAKE" />
</div>
</body>
</html>
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:
Maybe another screenshot like this will help:
I also experimented with ContentType, and either I didn't do it correctly, or nothing works either. Please help me!!!
1 answers
In the doPost()
method of your servlet, you only call doPost()
of the abstract parent class HttpServlet, meaning that your servlet doesn't actually have a post request handler. But it is the post request that you send from the script. Therefore, you get the error 405 "The method is not supported".
In addition, I see that you have already shortened the excess in the script. Decide how you want to send data from the script to the servlet. A simpler option is in the form of request parameters. Then the script will be 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 you send it as JSON data, 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 method doPost()
will become significantly more complex and require the dependency 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);
}