Input/Textarea - Required string parameter is not present - java

I'm having issues with the above code recognizing the 'defaultpagination' variable. It keeps throwing the 'Required String parameter 'defaultpagination' is not present' message on the user interface. This is part of an edit screen showing a configurable setting.
The controller method is below.
#RequestMapping(value = "/update", method = RequestMethod.POST)
public ModelAndView updateSetting(
#RequestParam("defaultpagination") String defaultPagination,
#RequestParam("id") long id) {
Setting setting = settingService.getOne(id);
setting.setDefaultPagination(Integer.parseInt(defaultPagination));
settingService.saveSetting(setting);
return new ModelAndView("redirect:/settings/setting-listing");
}
The thymleaf html can be seen below.
<form role="form" data-toggle="validator" name="createSetting" enctype="multipart/form-data" method="post" th:object="${setting}" action="/settings/update">
<div class="form-group">
<label for="defaultpagination">Default Pagination</label>
<input class="form-control" name="defaultpagination" type="number" th:field="${setting.defaultPagination}" placeholder="Enter default pagination" required="required" data-error="Pagination is required (maximum cannot exceed 100)" />
<div class="help-block with-errors"></div>
</div>
<input type="hidden" th:rows="1" class="form-control" id="id" name="id" th:value="${setting.id}"/>
<br />
<button type="submit" class="btn btn-default">Submit Button</button>
<br />
<br />
<br />
</form>
What's interesting is that I can change the 'input' tag to a textarea tag and everything would work as normal (the defaultpagination gets recognized). However, I want to use the input for validation. In this case the input needs to be a number. In similar cases, I will need a phone number and email. Has anyone faced this same problem regarding the input/textarea tag in thymeleaf?

one solution would be to change the String defaultPagination in the controller to Integer (if you expect only integer as defaultpagination)
ie
#RequestMapping(value = "/update", method = RequestMethod.POST)
public ModelAndView updateSetting(
#RequestParam("defaultpagination") Integer defaultPagination,
#RequestParam("id") long id) {
Another solution is to use the pattern attribute of the input tag (permit only numbers not decimal points)
<input class="form-control" name="defaultpagination" type="text"
pattern="\d+" th:field="${setting.defaultPagination}" placeholder="Enter default
pagination" required="required" data-error="Pagination is required (maximum cannot exceed 100)" />
Let me know if these worked for you

Related

How to display RequestParam errors in Thymeleaf

I want to use a form without an object. How to display errors?
Controller:
#PostMapping(value="/submit")
public String doSubmit(#RequestParam("myParameter") String param, BindingResult bindingResult) {
bindingResult.rejectValue("myParameter", "Oh nooo!!!!");
return "html";
}
HTML:
<form th:action = "#{/submit}" method="post">
<label for="myParameter" class="form-label">My Parameter</label>
<input name="myParameter" class="form-control" type="text"/>
<span class="text-danger" th:if="${#fields.hasErrors('myParameter')}" th:errors="myParameter">Error</span>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
th:if="${#fields.hasErrors('myParameter')}" th:errors="myParameter" throws errors, cause "myParameter" is not known.
How to display the error, without using th:object in <form>
I did it with the help of this question Thymeleaf: display global errors by error code
#PostMapping(value="/submit")
public String doSubmit(#RequestParam("myParameter") String param, BindingResult bindingResult) {
bindingResult.reject("myParameter", "myParameter");
return "html";
}
Important: myParameter must not be a key of a message source!
<form th:action="#{/submit}" method="post">
<label for="myParameter" class="form-label">My Parameter</label>
<input name="myParameter" class="form-control" type="text"/>
<span class="text-danger" th:if="${#lists.contains(#fields.globalErrors(), "myParameter")}" th:text="An Error happened">Error</span>
<button type="submit" class="btn btn-primary">Submit</button>
Important: Use " to indicate the string. th:text? may contain a message key like th:text="#{error.code1}"`.

Why my form data are not intercepted in my mainController in Java Intellij

I get an Internal Server Error, status=500: java.lang.NumberFormatException
The reason seems to be that my form data, sent via name attribute is not intercepted by #RequestMapping or HttpServletRequest doesn't work..
Here I try to pass the data:
<form action="/tankbeurt" method="get" style="padding: 5px;">
<div style="padding: 10px;">
<label for="huidig">Huidige kilometerstand</label>
<input type="text" name="huidig" id="huidig"></div>
<div style="padding: 10px;">
<label for="vorig">Vorige kilometerstand</label>
<input type="text" name="vorig" id="vorig"></div>
<div style="padding: 10px;">
<label for="liter">Hoeveel liter heb je bijgetankt</label>
<input type="text" name="liter" id="liter"></div>
<div><input type="submit" value="Bereken Verbruik"></div>
And I try to intercept it in the mainController:
#Controller
public class MainController {
#RequestMapping("/tankbeurt")
public String gegevens(HttpServletRequest request, Model model){
int huidigeKm = Integer.parseInt("huidig");
System.out.println(huidigeKm);
int vorigeKm= Integer.parseInt("vorig");
double liter= Double.parseDouble("liter");
Tankbeurt tankinformatie = new Tankbeurt(vorigeKm,huidigeKm,liter);
model.addAttribute("informatieTanken",tankinformatie);
return "tankbeurt";
}
Thankyou for your help. I don't see the problem.
Integer.parseInt("huidig");
You are trying to parse string "huidig" to integer. That's the cause of exception. Try looking for some method that extracts property from the model, like "model.getAttribute("huidig")".

Missing parameter error when submitting a form with two request params

Below is code from a controller that I'm aiming to make sure it's receiving two input parameters (name and code) from a front-end interface.
It's a page that takes two parameters within a submit form, "name" and "code".
#RequestMapping(method = RequestMethod.POST)
public String transfer(#RequestParam(name = "name") String name,
#RequestParam(name = "code") String code,
Errors errors, RedirectAttributes redirectAttributes) {
try {
User userToBeTransferred = usersRepository.findByName(name);
userToBeTransferred.setTransferred(true);
Region regionOfTransference = regionsRepository.findByCode(code);
regionOfTransference.setPopulationNumber(regionOfTransference.getPopulationNumber() + 1);
userToBeTransferred.setRegion(regionOfTransference);
usersRepository.save(userToBeTransferred);
regionsRepository.save(regionOfTransference);
return "redirect:/section/users/new";
} catch (IllegalArgumentException e) {
return "htmlPageOne";
}
}
The front-page form :
<form class="form-horizontal" method="POST" action="/section/users/new" th:object="${user}">
<input type="hidden" th:field="*{id}"/>
<div class="form-group row">
<label for="name" class="col-form-label">User name</label>
<input type="text" class="form-control" id="name" th:field="*{name}" name="name"/></div>
<div class="form-group row">
<label for="code" class="col-form-label">Code</label>
<input type="text" class="form-control" id="code" th:field="*{region.code}" name="code"/></div>
<button type="submit" class="btn btn-primary col-sm-6 ">Save</button>
</form>
For some reason, I'm getting the following error after I click to submit the form :
There was an unexpected error (type=Bad Request, status=400).
Required String parameter 'code' is not present
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'code' is not present
I'm not sure if I'm using the requestparams correctly, so maybe it's got something to do with this? I don't know, I've been stuck on this for a few hours now, so would appreciate if someone could help me.
The problem is that th:field="*{region.code}" overrides your name attribute into name="region.code". You can tell by inspecting the rendered <input> element using dev tools of your browser.
You can change following
th:field="*{region.code}"
...into:
th:value="${user.region.code}"

User Registration Form in HTML - Required String parameter 'user_id' is not present

I have an html page (format - FTL) in which I am trying to send data to a controller method. I am only trying to print the items that the user typed, nothing fancy for the beginning. I get the error - Required String parameter 'user_id' is not present
I work with spring mvc and freemarker.
This is the signup.ftl file -
<form method="POST", action="GET">
<div class="container">
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="email" id="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="password" id="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<label for="user_id" id="user_id"><b>User ID</b></label>
<input type="text" placeholder="user_id" name="user_id" required>
<hr>
<p>By creating an account you agree to our Terms & Privacy.</p>
<button type="submit" class="registerbtn">Register</button>
</div>
<div class="container signin">
<p>Already have an account? Sign in.</p>
</div>
</form>
</body>
</html>
This is the controller -
#RequestMapping(value = "/signup", method = RequestMethod.GET)
public String signup(#RequestParam("user_id")String user_id, #RequestParam("password")String password, #RequestParam("email")String email, Model model) {
System.out.println("coming in controller" + user_id + " " + password);
return "signup";
}
You are passing wrong action method and value.
You have to match the controller method signature which is
#RequestMapping(value = "/signup", method = RequestMethod.GET)
Change form tag to below line of code.
<form method="GET", action="signup">

Spring submit form get checkbox value not working

I cannot get "remember-me" checkbox value (getting 400 Required boolean parameter 'remember' is not present)
Trying to user #RequestParam. (as for inputs email/password).
How to get checkbox value and not 400 error?
Controller
#RequestMapping(value = "/login", method = RequestMethod.POST)
private String doLogin(#RequestParam(value = "inputEmail") String inputEmail,
#RequestParam(value = "inputPassword") String inputPassword,
#RequestParam(value = "remember") boolean remember,
HttpSession session) {
HTML form
<form class="form-login" method="post" action="/login">
<h2 class="form-login-heading">Please log in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" name="inputEmail" class="form-control" placeholder="Email address" required
autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" name="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" name="remember" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block btn-login" type="submit">Log in</button>
</form>
Please remove value="remember-me" from your check box.
When you will tick checkbox spring will map string value "remember-me" with Boolean which is not possible as i know.

Categories