how to check existing user in a database with Struts and Ajax - ajax

I want to verify if an email exists in my database before form submission:
<form action="add" method="post">
<input type="text" name="user.email" />
<input type="submit" value="Ajouter" />
</form>
How can I use Ajax to check if the email exists already in the database before submitting?

You can use the Validate() method when you extends the ActionSupport calls in your Controller ; then you check your email and return an ActionFieldError if it dosent' exist.
it's simple:
public void validate() {
if(!emailExist(this.email)){
addFieldError(email, "Email already exist;You must choose another one"); }
}
That assumes that you have a field with the name ="email" and a function that check mail existence called emailExist(String mail)

If you really want ajax validation , you can use Struts2 jQuery Plugin and you instead of :
<s:submit />
you make something like this:
<sj:submit
targets="result"
button="true"
validate="true"
value="AJAX Submit"
indicator="indicator"
/>

Related

Thymeleaf: Partially set values to model object from outside the form tags

I have an model object that I send to front end. I populate that object inside the form. What I want to know is that if I can partially populate that object from a different event before user submits his/her form?
Example:
Entity:
public class Participant {
public String username;
public boolean taskCompleted;
}
Thymeleaf Form:
<form th:object="${participant}" th:action="#{/join}" method="post">
<input type="text" th:field="*{username}" >
<button type="submit">Join!</button>
</form>
Before submitting the form, I give users a task, like clicking a button on a different part of the page. If they do it, I want to do something like taskCompleted = true of the same participant object. Is that possible?
Use a hidden input in your form:
<form th:object="${participant}" method="post">
<input type="text" th:field="*{username}" >
<input type="hidden" th:field="*{taskCompleted}" />
<button type="submit">Join!</button>
</form>
When the user clicks a button, use JavaScript to set the value of the hidden input to true.
<!-- This button flips the value of taskCompleted to true -->
<button onclick="document.getElementById('taskCompleted').value = 'true';">Do the task first!</button>

Thymeleaf set default value [duplicate]

I am programming in Spring and using Thymeleaf as my view, and am trying to create a form where users can update their profile. I have a profile page which lists the user's information (first name, last name, address, etc), and there is a link which says "edit profile". When that link is clicked it takes them to a form where they can edit their profile. The form consists of text fields that they can input, just like your standard registration form.
Everything works fine, but my question is, when that link is clicked, how do I add the user's information to the input fields so that it is already present, and that they only modify what they want to change instead of having to re-enter all the fields.
This should behave just like a standard "edit profile" page.
Here is a segment of my edit_profile.html page:
First Name:
Here is the view controller method that returns edit_profile.html page:
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public String getEditProfilePage(Model model) {
model.addAttribute("currentUser", currentUser);
System.out.println("current user firstname: " + currentUser.getFirstname());
model.addAttribute("user", new User());
return "edit_profile";
}
currentUser.getFirstname() prints out the expected value, but I'm getting blank input values in the form.
Thanks.
Solved the problem by removing th:field altogether and instead using th:value to store the default value, and html name and id for the model's field. So name and id is acting like th:field.
I'm slightly confused, you're adding currentUser and a new'd user object to the model map.
But, if currentUser is the target object, you'd just do:
<input type="text" name="firstname" value="James" th:value="${currentUser.firstname}" />
From the documentation:
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html
I did not have a form with input elements but only a button that should call a specific Spring Controller method and submit an ID of an animal in a list (so I had a list of anmials already showing on my page). I struggled some time to figure out how to submit this id in the form. Here is my solution:
So I started having a form with just one input field (that I would change to a hidden field in the end). In this case of course the id would be empty after submitting the form.
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>
The following did not throw an error but neither did it submit the animalIAlreadyShownOnPage's ID.
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>
In another post user's recommended the "th:attr" attribute, but it didn't work either.
This finally worked - I simply added the name element ("id" is a String attribute in the Animal POJO).
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" name="id" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>

Create urls using forms in Thymeleaf

I am new to Thymeleaf, and I have an issue with dynamically creating URLs using forms.
I have a simple spring boot app that stores objects in a database, and I can query the database using simple urls. For instance, the url /distance/0.3 would return objects whose distance attribute is lower than or equal to 0.3. These urls work perfectly when I edit them in the browser.
I would like users to be able to set these search values themselves. I tried to create a simple form to create the above url with user inputs, but I am getting the following error:
Neither BindingResult nor plain target object for bean name 'dist' available as request attribute
I have tried with this in the html document:
<form th:action="#{/distance/{pathParam}(pathParam=${dist}}">`
<p>Distance: <input type="text" th:field="*{dist}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
and trying various answers from this discussion, but with no luck.
I have also tried to use the controller as suggested here, with this in the controller:
#GetMapping("/distance/search/")
public String userSetDistance(#RequestParam("dist") String dist) {
return "redirect:/distance/" + dist;
}
and this in the html file:
<form th:action="#{/distance/search/}">
<p>Distance: <input type="text" th:field="*{dist}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
But this did not work either.
Could you please help me with this? The idea is simple but I cannot get something that works... thank you!
UPDATE
Based on the below answer from MohamedSanaulla, I decided to use the controller to do this, created a "forms" object with the required fields and edited my code as follows:
<form action="#" th:action="#{/distance/search}" th:object="${param}" method="post">`
<p>Distance: <input type="text" th:field="*{dist}"/></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
#PostMapping("/distance/search")
public String userGetClose(#ModelAttribute ("param") Forms form) {
String distance = String.valueOf(form.getDist());
return "redirect:/distance/" + distance;
}
Ideally I wanted to create and call the url directly from the html page, to avoid going back to the controller just to create the url, but this works fine.
You have to either use ModelMap or Model in your controller and then use addAttribute to set the dist:
public String controllerMethod(#RequestParam("dist") String dist,
Model model){
model.addAttribute("dist", dist);
return "viewName";
}
Or Thymeleaf provides context object to get query params like ${param.dist} directly in your HTML
Update:
Just saw that there is a redirect: in the controller. So the dist is no longer available in the request param and hence ${param.dist} will not work. The easier solution is to use ModelMap and put the dist as part of the view model.

How to validate just one field for register a user for spring project with hibernate validator?

<input name="id" placeholder="input your id"/>
<button id="id_check">check</button>
<input name="password" placeholder="input your id"/>
<input type="submit" value="register" />
Currently, I uses a controller for user.
Controller code following...
#Controller
public class UserController {
#GetMapping("...")
public String registerForm(...) { ... }
#PostMapping("...")
public String register(#ModelAttribute #Validated ...) { ... }
.....
}
I want to check id using ajax call.
For id duplication check, can I use hibernate validator? (for one field. not submit action) Also it should be validate duplication of id.(using dao).
For example, one field for validation should be checked duplication and validated by hibernate validator(#NotEmpty, #Email...)

How to execute code after the jquery.validate validation event?

I am using jquery.validate 1.9 and wish to execute code every time the form automatically validates (using the default behavior).
I hoped there would exist an OnValidated event I could hook into, but can not find one.
After validation executes I wish to conditionally enable other parts of the page if the form is valid, and disable otherwise.
How would one go about adding a method call following the existing validate() function?
I'm using jquery validate 1.8.1, but you should still be able to accomplish this using the valid() function.
valid() will either validate the entire form if you pass it the form ID or individual fields if you pass their respective ID's. It will then return a Boolean based on if they are all valid or not.
Something like this should work:
<script type="text/javascript">
function tab1Validation(){
if($('#field1, #field2, #field3').valid()){
//Logic if all fields valid - eg: $('#NextTab').show();
}else{
//Logic if one or more is invalid
}
}
</script>
<form id="yourform">
<div>
<input type="text" id="field1" name="field1" />
<input type="text" id="field2" name="field2" />
<input type="text" id="field3" name="field3" />
</div>
<input name="nextTab" type="button" value="Next Tab" onClick="tab1Validation();" />
</form>

Resources