Issue
Im trying to get values from my request but it return null. What is the problem?
This is my form:
<form class="register-form">
<input class="name" type="text" placeholder="name"/>
<input class="password" type="password" placeholder="password"/>
<button id="register">create</button>
</form>
My post method:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
String name = req.getParameter("name");
if (Objects.isNull(projectService.getByName(name))) {
logger.info("Registration new project " + name); //NAME == NULL ???
String password = req.getParameter("password");
int budget = Integer.parseInt(req.getParameter("budget"));
...
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write("Success");
}
And JS part:
$(document).ready(function () {
$("button#register").click(function () {
var name = $("form.register-form input.name").val();
var password = $("form.register-form input.password").val();
if (name == '' || password == '') {
alert("Please fill all fields...!!!!!!");
} else {
var projectRegistration = {
projectName: name,
projectPassword: password
};
$.post("registration", projectRegistration, function (data) {
if (data === 'Success') {
$("form")[0].reset();
}
});
}
});
});
Im using Tomcat ver 8.5.56
Solution
At JS code you are building an object projectRegistration which is passed to post request. This object has keys projectName and projectPassword which should be used inside the servlet:
String name = req.getParameter("projectName");
Hope it helps.
Answered By - Carlos Bazilio