I'm new to Struts2 framework and I found a problem when I try to edit an object.
The code of my modification action:
#Action(value = "modifyServer", results = {
#Result(name = "success", location = Location.MAIN_PAGE),
#Result(name = "error", location = Location.LOGIN_PAGE) })
public String modifyServer() {
em = DbConnexion.getEntityManager().createEntityManager();
String id=request.getParameter(sssid);
logger.info("id serveur = "+request.getParameter("id"));
try {
em.getTransaction().begin();
Simserver server = em.find(Simserver.class, id);
server.setSssServer(request.getParameter("sssServer"));
server.setSssIp(request.getParameter("sssIp"));
server.setSssPort(request.getParameter("sssPort"));
em.getTransaction().commit();
System.out.println("modification done !!!");
em.close();
return SUCCESS;
} catch (Exception e) {
return ERROR;
}
}
The JSP:
<form class="form-horizontal" action="modifyServer" role="form"
name="form_message" method="get">
<div id="elmsg"></div>
<div class="panel panel-info">
<div class="panel-heading expand" id="second-level">
<h6 class="panel-title">Modification du Serveur</h6>
</div>
<div class="panel-body">
<div class="form-group">
<label class="col-sm-2 control-label"> Id du Serveur : <span
class="mandatory">*</span></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sssId"
disabled="disabled" id="sssId"
value="<s:property value="#request.curentserver.sssId" />">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"> Nom du Serveur : <span
class="mandatory">*</span></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sssServer"
id="sssServer"
value="<s:property value="#request.curentserver.sssServer" />">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"> Adresse IP : <span
class="mandatory">*</span></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sssIp" id="sssIp"
value="<s:property value="#request.curentserver.sssIp" />" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"> Port : <span
class="mandatory">*</span></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sssPort" id="sssPort"
value="<s:property value="#request.curentserver.sssPort" />" />
</div>
</div>
<div class="form-actions text-right">
<button type="submit" value="Envoyer" class="btn btn-success"
>Modifier le serveur</button>
<a role="button" href="gestionServeurList" class="btn btn-danger">Retour
à la list des serveurs</a>
</div>
When I execute my action the request.getParameter returns null.
I think the issue is in the parameter!
There are issues with code:
In Java code you are trying to print a request parameter with name as "id" instead of "sssId".
Also you are trying to use a variable called "sssid" that is no where defined in your question.
String id=request.getParameter(sssid);
logger.info("id serveur = "+request.getParameter("id"));
In JSP the sssId element is disabled, when you submit a form the disabled elements are ignored.
<input type="text" class="form-control"
name="sssId" disabled="disabled" id="sssId"
value="<s:property value="#request.curentserver.sssId" />">
So to get its value, create a hidden element in your jsp and on form submission update the hidden element with the required value using JavaScript.
<input type="hidden" name="sssId" value=""/>
In Javascript it will be like:
document.getElementById("sssId").value = 123; // Give value here
document.getElementById("myForm").submit(); // Give an Id to your form, say "myForm"
Finally the Action code looks like this :
public class MyAction extends ActionSupport implements ServletRequestAware {
#Action(value = "modifyServer", results = {
#Result(name = "success", location = Location.MAIN_PAGE),
#Result(name = "error", location = Location.LOGIN_PAGE) })
public String modifyServer() {
String id = request.getParameter("sssId");
System.out.println("id serveur = " + id);
return null;
}
private HttpServletRequest request;
#Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
}
If the input element has disabled="disabled" attribute it won't include as parameter when your form is submitted. Also rename the input element name that correspond to a parameter name. Struts2 getter/setter can be used to populate the action bean.
public void setSssId(String id){
this.id = id;
}
I'd suggest checking value of sssId being passed to the action through javascript.
<button onclick='javascript:submitMyForm();' type="button" value="Envoyer" class="btn btn-success"
>Modifier le serveur</button>
write the following javascript
function submitMyForm(){
var sssIdElement = document.getElementById("sssId");
document.form_message.action = "modifyServer.action?sssId="+sssIdElement;
document.form_message.submit();
}
Related
I'm trying to implement a login form in a Spring boot application. It has an email and a password field. The email field failed to get user input, here is the form:
<form th:action="#{/login}" method="get" th:object="${loginForm}" style="max-width: 600px; margin: 0 auto;">
<div class="m-3">
<div class="form-group row">
<label class="col-4 col-form-label">E-mail: </label>
<div class="col-8">
<input type="text" th:field="*{email}" name="q" class="form-control" required />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Password: </label>
<div class="col-8">
<input type="password" th:field="*{password}" class="form-control" required/>
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Log in</button>
</div>
</div>
</form>
Here is the controller:
#GetMapping("login")
public ModelAndView login(Model model, #RequestParam(name = "q", required = false) Optional<String> email) {
Optional<UserDto> aUser;
System.out.println(email);
if (email.isPresent()) {
aUser = userService.getAUserByEmail(email.get());
model.addAttribute("user", aUser);
var mv = new ModelAndView("user/user-list", model.asMap());
return mv;
} else {
model.addAttribute("loginForm", new LoginForm());
return new ModelAndView("/login/login-form", model.asMap());
}
}
I thought the #RequestParam(name = "q") and name="q" in html would do the job, but I always get Optional.empty for email. Any idea what's wrong here?
UPDATE:
From the answers I changed controller to this:
#GetMapping("login")
public ModelAndView login(Model model, LoginForm loginForm) {
Optional<UserDto> aUser;
if (loginForm.getEmail() != null) {
aUser = userService.getAUserByEmail(loginForm.getEmail());
model.addAttribute("user", aUser);
var mv = new ModelAndView("user/user-list", model.asMap());
return mv;
} else {
model.addAttribute("loginForm", new LoginForm());
return new ModelAndView("/login/login-form", model.asMap());
}
}
login-form.html to this:
<form th:action="#{/login}" method="get" th:object="${loginForm}" style="max-width: 600px; margin: 0 auto;">
<div class="m-3">
<div class="form-group row">
<label class="col-4 col-form-label">E-mail: </label>
<div class="col-8">
<input type="text" th:field="*{email}" class="form-control" required />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Password: </label>
<div class="col-8">
<input type="password" th:field="*{password}" class="form-control" required/>
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Log in</button>
</div>
</div>
</form>
I also have LoginForm.java like this
#Data
#AllArgsConstructor
#NoArgsConstructor
public class LoginForm {
private String email;
private String password;
}
but still not getting user email field input?
The way you have set up your form, it's mapping the value of your email input field to the property email (that's what th:field="*{email}" means) of an object called loginForm (that's what th:object="${loginForm}" means). Neither of these seem to be used or even exist in your login() method. You need to either change what you use in your controller to match what you have in your Thymeleaf template, or change your Thymeleaf template to actually reference what you are using in your controller.
The problem in your code is located under th:object="${loginForm}"
With this you inform spring to bind the data sent from the form into an object named loginForm.
So Spring actually expects the controller to be
#GetMapping("login")
public ModelAndView login(Model model, LoginForm loginForm) {
....
and inside LoginForm a field named email will contain the value sent from the form, as you have declared with <input type="text" th:field="*{email}" .... >
If you don't want the data to be bound into an object from Spring Mvc then
remove the th:object="${loginForm}"
use the
<input type="text" th:name="q" class="form-control" required />
and then the controller will receive the sent value as a query parameter
#GetMapping("login")
public ModelAndView login(Model model, #RequestParam(name =
"q", required = false) Optional<String> email) {
I can't seem to figure out why I keep getting a 400 bad request. Before I got 400 bad request, the form had "id" instead of "name". When the form had "id" I got 200 but didn't update my database. Now, I get the error and nothing seems to be working.
Here's my controller:
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(MemberVO vo, Model model) {
System.out.println(vo);
logger.info("regist post...");
logger.info(vo.toString());
try {
mservice.insertMember(vo);
} catch (Exception e) {
e.printStackTrace();
}
return "/register_success";
}
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public void registrationGet(MemberVO vo, Model model) {
}
Here's my form:
<form role = "form" method ="post">
<div class="form-group">
<input type="email" class="form-control" name = "username" placeholder="Email" required/>
<span><i class="fa fa-envelope"></i></span>
</div>
<div class="form-group">
<input type="password" class="form-control" name = "password" placeholder="Password" required/>
<span><i class="fa fa-lock"></i></span>
</div>
<div class="form-group">
<input type="text" class="form-control" name = "firstname" placeholder="firstname" required/>
<span><i class="fa fa-user"></i></span>
</div>
<div class="form-group">
<input type="text" class="form-control" name = "lastname" placeholder="lastname" required/>
<span><i class="fa fa-user"></i></span>
</div>
<div class="form-group">
<input type="text" class="form-control" name = "phonenum" placeholder="Phone Number" required/>
<span><i class="fa fa-user"></i></span>
</div>
<div class="form-group">
<input type="text" class="form-control" name = "birthday" placeholder="Birthday, ex) 1986-06-08" required/>
<span><i class="fa fa-user"></i></span>
</div>
<div class="form-group">
<input type="text" class="form-control" name = "destination" placeholder="where would you like to go?" required/>
<span><i class="fa fa-user"></i></span>
</div>
<button type = "submit" class="btn btn-orange btn-block">Sign Up</button>
</form>
We can not tell you the exact problem as you have not attached your modal class MemberVO but you can check below.
1.There is no action attribute in your form.
2.Ensure that all the fields present in Modal class should also be present in the form with the same name.
I am trying to send an AJAX call with jquery to a spring web mvc application. I have a modal which contains a form:
<div id="editTileModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog modal-lg">
<form id="frmEditTileModal" modelAttribute="editTile" class="floating-labels " action="/DESSOApplicationPortalAdmin/rest/tile/002" method="POST">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myLargeModalLabel">Edit Tile</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6" >
<div class="form-group m-b-40 margin-top-20">
<input type="text" class="form-control" id="editTileId" name="id" required><span class="highlight"></span> <span class="bar"></span>
<label for="editTileId">Id</label>
</div>
<div class="form-group m-b-40">
<input type="text" class="form-control" id="editTileDescription" name="description" required><span class="highlight"></span> <span class="bar"></span>
<label for="editTileDescription">Description</label>
</div>
<div class="form-group m-b-40">
<input type="text" class="form-control" id="editTileRole" name="role" required><span class="highlight"></span> <span class="bar"></span>
<label for="editTileRole">Role</label>
</div>
</div>
<div class="col-md-6" >
<div class="form-group m-b-40 margin-top-20">
<input type="text" class="form-control" id="editTileTarget" name="target" required><span class="highlight"></span> <span class="bar"></span>
<label for="editTileTarget">Target</label>
</div>
<div class="form-group m-b-40">
<input type="text" class="form-control" id="editTileIndex" name="index" required><span class="highlight"></span> <span class="bar"></span>
<label for="editTileIndex">Index</label>
</div>
<div class="form-group m-b-40">
<input type="text" class="form-control" id="editTileTileimagename" name="tileImageName" required><span class="highlight"></span> <span class="bar"></span>
<label for="editTileTileimagename">Tile Image Name</label>
</div>
</div>
<div class="col-md-12">
<div class="form-group m-b-40">
<input type="text" class="form-control" id="editTileUrl" name="url" required><span class="highlight"></span> <span class="bar"></span>
<label for="editTileUrl">Url</label>
</div>
</div>
<div class="col-md-12">
<div class="form-group m-b-40 form-check">
<label class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">Disable Tile</span>
</label>
</div>
</div>
<div class="row>">
<div class="col-sm-6 col-md-6 col-xs-12">
<div class="white-box">
<h3 class="box-title">Tile Image Normal</h3>
<label for="img-tile-normal">You can add a default value</label>
<input type="file" id="img-tile-normal" class="dropify" data-default-file="resources/vendor/plugins/bower_components/dropify/src/images/test-image-1.jpg" />
</div>
</div>
<div class="col-sm-6 col-md-6 col-xs-12">
<div class="white-box">
<h3 class="box-title">Tile Image on Hover</h3>
<label for="img-tile-on-hover">You can add a default value</label>
<input type="file" id="img-tile-on-hover" class="dropify" data-default-file="resources/vendor/plugins/bower_components/dropify/src/images/test-image-1.jpg" />
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
<button id="btnSaveEditTile" type="submit" class="btn btn-danger waves-effect waves-light">Save changes</button>
</div>
</div>
</form>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
This is the jQuery
$('#frmEditTileModal').submit(function (e) {
e.preventDefault();
alert("save edit start!");
var editSuccesFunc = function () {
alert('Success Edit!');
};
var editErrorFunc = function () {
alert('Error Edit!');
};
var tileId = $('#editTileId').val();
alert("data to send: " + $('#editTileId').val());
var formData = new FormData();
formData.append("id", $('#editTileId').val());
formData.append("description", $('#editTileDescription').val());
formData.append("role", $('#editTileRole').val());
$.ajax({
type: "POST",
url: "/DESSOApplicationPortalAdmin/rest/tile/" + tileId,
data: $('#frmEditTileModal').serialize(),
contentType: "application/json",
dataType: "json",
success: editSuccesFunc,
error: editErrorFunc
});
});
and this is the java controller:
#RestController
#RequestMapping(value = "rest/tile")
public class TileRestController {
#Autowired
TileService tileService;
#RequestMapping(value = "/{tileId}", method = RequestMethod.GET)
public Tile getProductById(#PathVariable(value = "tileId") String tileId) {
System.out.println("------------->" + this.getClass().getSimpleName() + ": getProductById called. Searching for Tile Id " + tileId);
return tileService.getTileById(tileId);
}
#RequestMapping(value = "/{tileId}", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
#ResponseBody
public Tile update( #ModelAttribute("editTile") Tile tile, #PathVariable(value = "tileId") String tileId) {
Tile updatedTile = new Tile();
//updatedTile.setId("099");
//updatedTile.setDescription("ExampleTile");
System.out.println("------------->" + this.getClass().getSimpleName() + " update method: print object fields: "+tile.toString());
return updatedTile;
//return tileService.updateTile(tile);
}
}
When I try a doing a normal submit (no ajax or jquery) the controller correctly reads the field to the object.
However when, I try doing the same as an ajax call, it correctly sends the data but the controllers does not map it to an object via modelAttribute("editTile"). Here is a print of the class:
------------->TileRestController update method: print object fields: Tile{ tileImageName=null, description=null, role=null, url=null, target=null, index=0, id=null, disabled=false}
Am I missing something?
EDIT:
I tried a suggestion made in the answers, but it did not seem to work. Here is what I did:
I change the code of the update method in order to use the #RequestBody annotation
#RequestMapping(value = "/{tileId}", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
#ResponseBody
public Tile update( #RequestBody Tile tile, #PathVariable(value = "tileId") String tileId) {
Tile updatedTile = new Tile();
//updatedTile.setId("099");
//updatedTile.setDescription("ExampleTile");
System.out.println("------------->" + this.getClass().getSimpleName() + " update method: print object fields: "+tile.toString());
return updatedTile;
//return tileService.updateTile(tile);
}
plus, I changed my content type as well for the ajax call:
$.ajax({
type: "POST",
url: "/DESSOApplicationPortalAdmin/rest/tile/" + tileId,
data: $('#frmEditTileModal').serialize(),
contentType: "application/www-form-url-encoded",
dataType: "json",
success: editSuccesFunc,
error: editErrorFunc
});
however, now I get an ajax error, it it does not even make the call:
You seem to be Posting a JSON (content-type: application/json) from ajax.
Try using #RequestBody instead of #ModelAttribute for the Tile.
A FORM post normally gets post'ed as content-type: application/www-form-url-encoded.
I'm working on java web app, which uses Spring Boot, Hibernate and thymeleaf. At the moment I'm trying to implement registration process for my application and I'm stuck on a problem with my entity class.
Part of User #Entity clas
#Column(name = "aktywny")
private boolean enabled;
#Column(name = "token")
private String confirmationToken;
public boolean getEnabled() {
return enabled;
}
public void setEnabled(boolean value) {
this.enabled = value;
}
Request method
#RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView processRegistrationForm(Model model, ModelAndView modelAndView, #Valid User user, BindingResult bindingResult, #RequestParam Map requestParams, RedirectAttributes redir, HttpServletRequest httpServletRequest){
//Lookup user in db by email
User userExist = userService.findByEmail(user.getEmail());
System.out.println(userExist);
if( userExist != null){
model.addAttribute("alreadyRegisteredMessage", "Użytkownik o podanym adresie e-mail już istnieje");
bindingResult.reject("email");
}
if(bindingResult.hasErrors()){
modelAndView.setViewName("home");
}else {
//set disabled until confirmation link clicked
user.setEnabled(false);
//generate string token
user.setConfirmationToken(UUID.randomUUID().toString());
Zxcvbn passwordCheck = new Zxcvbn();
Strength strength = passwordCheck.measure(requestParams.get("password").toString());
if(strength.getScore() < 3) {
bindingResult.reject("password");
redir.addFlashAttribute("errorMessage", "Twoje hasło jest zbyt słabe, wybierz silniejsze");
modelAndView.setViewName("redirect: confirm?token=" + requestParams.get("token"));
System.out.println(requestParams.get("token"));
// Set new password
user.setPassword(bCryptPasswordEncoder.encode(requestParams.get("password").toString()));
}
userService.saveUser(user);
String appUrl = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName();
SimpleMailMessage registrationEmail = new SimpleMailMessage();
registrationEmail.setTo(user.getEmail());
registrationEmail.setSubject("Potwierdzenie rejestracji");
registrationEmail.setText("Aby dokończyć rejestrację, kliknij w poniższy link: "
+ appUrl + "/confirm?token=" + user.getConfirmationToken());
registrationEmail.setFrom("hotelwaltertorun#gmail.com");
emailService.sendEmail(registrationEmail);
if (user == null) { // No token found in DB
modelAndView.addObject("invalidToken", "Oops! This is an invalid confirmation link.");
} else { // Token found
modelAndView.addObject("confirmationToken", user.getConfirmationToken());
}
model.addAttribute("confirmationMessage", "E-mail potwierdzający został wysłany na adres " + user.getEmail());
modelAndView.setViewName("home");
}
return modelAndView;
}
HTML form code
<form th:autocomplete="on" id="register_form" class="form-horizontal" action="#"
th:action="#{/register}" th:object="${user}" method="post" role="form"
data-toggle="validator">
<input type="hidden" name="token" th:value="${confirmationToken}">
<div class="col-md-6 form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" th:field="*{firstname}"
placeholder="Imię" class="form-control" required/>
</div>
</div>
<div class="col-md-6 form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" th:field="*{lastname}"
placeholder="Nazwisko" class="form-control" required/> </div>
</div>
<div class="col-md-6 form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" th:field="*{username}"
placeholder="Login" class="form-control" required/>
</div>
</div>
<div class="col-md-6 form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input name="password" type="password" id="password"
placeholder="Hasło" class="form-control" required />
</div>
</div>
<div class="col-md-6 form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input type="password" class="form-control" id="signup-password-confirm" placeholder="Potwierdź hasło" name="ConfirmPassword" data-fv-notempty="true"
data-fv-notempty-message="Please confirm password"
data-fv-identical="true"
data-fv-identical-field="password"
data-fv-identical-message="Both passwords must be identical" />
</div>
</div>
<div class="col-md-6 form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input type="email" th:field="*{email}"
placeholder="Adres e-mail" class="form-control"
data-error="This email address is invalid" required />
</div>
</div>
<div class="col-md-6 form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span>
<input type="tel" th:field="*{phone}"
placeholder="Telefon" class="form-control"
data-error="This email address is invalid" required />
</div>
</div>
<div class="col-md-6 form-group">
<button id="register" class="btn btn-success" name="register" style="width:100%;">Zarejestruj <span class="glyphicon glyphicon-send"></span></button>
</div>
</form>
and error description from browser
There was an unexpected error (type=Internal Server Error, status=500).
org.hibernate.PropertyAccessException: Null value was assigned to a property [class com.kaceper.model.User.enabled] of primitive type setter of com.kaceper.model.User.enabled
Thanks for help
Thymeleaf is trying to execute something like this:
user.setEnabled(null)
Which causes a NullPointerException since enabled is a primitive type and can only be true or false.
Change the enabled field to Boolean instead of boolean and update the getter and setter accordingly.
When I use jQuery's $.ajax() or $.post() method to send form information to server, the 'data' string is added to the end of the url. Why the POST request becomes a GET request? The form code shown below
<form role="form" class="form-horizontal">
<div class="box-body">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" required>
</div>
</div>
<div class="form-group">
<label for="hospital" class="col-sm-2 control-label">Hospital</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="hospital" name="hospital" required>
</div>
</div>
<div class="form-group">
<label for="url" class="col-sm-2 control-label">URL</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="url" name="url" required>
</div>
</div>
<div class="form-group">
<label for="version" class="col-sm-2 control-label">Version</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="version" name="version" required>
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<textarea class="form-control" id="description" name="description" rows="3" required></textarea>
</div>
</div>
</div>
<div class="box-footer text-center">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-primary" id="submitBtn">Submit</button>
</div>
</form>
Ajax code
$("#submitBtn").submit(function(event) {
event.preventDefault();
var info = {};
info.name = $("#name").val();
info.hospital = $("#hospital").val();
info.url = $("#url").val();
info.version = $("#version").val();
info.description = $("#description").val();
$.post("/nuts/add", JSON.stringify(info), function(data) {
console.log(data);
}, "json");
}
The url always like this
http://localhost:8080/nuts/add.html?name=1&hospital=1&url=1&version=1&description=1
My backend framework is Spring MVC, and the controller code shown below
#RestController
#RequestMapping(value = "/nuts/add", produces = {APPLICATION_JSON_VALUE})
public class AddNutsApi {
private MongoBasicDao<Nuts> mongoBasicDao;
#Autowired
public void setMongoBasicDao(MongoBasicDao<Nuts> mongoBasicDao) {
this.mongoBasicDao = mongoBasicDao;
}
#RequestMapping(value = "", produces = {APPLICATION_JSON_VALUE}, method = RequestMethod.POST)
public ResponseEntity<Void> addNutsPost(#RequestBody Nuts nuts) throws NotFoundException {
if (nuts.getName() != null && nuts.getHospital() != null && nuts.getUrl() != null && nuts.getVersion() != null && nuts.getDescription() != null) {
try {
Nuts _nuts = new Nuts();
_nuts.setName(new String(nuts.getName().getBytes("ISO-8859-1"), "UTF-8"));
_nuts.setHospital(new String(nuts.getHospital().getBytes("ISO-8859-1"), "UTF-8"));
_nuts.setUrl(new String(nuts.getUrl().getBytes("ISO-8859-1"), "UTF-8"));
_nuts.setVersion(new String(nuts.getVersion().getBytes("ISO-8859-1"), "UTF-8"));
_nuts.setDescription(new String(nuts.getDescription().getBytes("ISO-8859-1"), "UTF-8"));
_nuts.setCreationTime(new Date());
Integer mark = mongoBasicDao.getCollectionMark(Constant.COLLECTION_NUTS);
_nuts.setMark(mark);
mongoBasicDao.addObject(_nuts, Constant.COLLECTION_NUTS);
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
} else {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
}
I have added jackson's dependency(jackson-databind), and set the <mvc:annotation-driven/> in the Spring MVC configuration file. By the way, the DispatcherServlet's url-pattern is / .
Can anyone tell me where am I getting it wrong? Thanks a lot!
When you call JSON.stringify(info), you will get a JSON string , e.g. something like this:
{ "name": "1", "hospital": "1", "url": "1", "version": "1", "description": "1" }
You certainly will not get a query string like this:
?name=1&hospital=1&url=1&version=1&description=1
That should be your hint that the JavaScript code is not responsible for the GET request you see.
The problem is that you're binding the submit function wrong. $("#submitBtn").submit(...) doesn't do anything, because a <button type="submit"> doesn't fire any submit events. The <form> does.
What happens is that the JavaScript code is ignored, and clicking the Submit button will trigger a submit of the form, and since the <form> element doesn't have a method="post" attribute, the form will be submitted as a GET.
Solution: Bind the submit(...) to the <form>.