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

<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...)

Related

Request method 'POST' not supported in spring MVC web app

i am using .html in mvc app. it's showing app perfectly.inside login.html i have used form with method POST for submission but when i submit form showing error that POST is not supported.but when i change everything with .jsp then it let submit form.
here's the controller
#Controller
public class mainController {
#RequestMapping("/login")
public ModelAndView login(Locale locale , Model m) {
System.out.println("modal");
return new ModelAndView ("login");
}
#RequestMapping(path = "/user" , method=RequestMethod.POST)
public String user(#ModelAttribute("user") User user) {
System.out.println(user);
return "user";
}
}
this is login form
<form action="user" method="post" name="user">
<input type="text" name="username" placeholder="uname"/> <br>
<input type="password" name="password" placeholder="password"/> <br>
<input type="date" name="date" placeholder="date"/> <br>
<button type="submit">Submit</button>
</form>
what can I do to submit form using POST method from .html file.

How to handle forms mapped to more than one entity using Thymeleaf + Hibernate + Spring Boot?

I have a form in Thymeleaf that I want to link to two different entity to be persisted to the database using Hibernate
I have the following form using Thymeleaf:
<form th:action="#{/app/handleForm}" th:object="${entity1}"
method="post">
<input type="text" th:field="*{field1}" />
<input type="text" th:field="*{field2}" />
<input type="text" th:field="*{field3}" />
</form>
Let's supposea the first two fields are bound to entity1 and the third field to be bound to entity2 (not entity1) how should I do this?
Also, in the controller method, I have two DAO implementation for persisting them:
#PostMapping("app/handleForm")
public String RHTraiterDemande(Model m, Entity1 entity1, Entity2
entity2) {
entity1Service.add(entity1);
entity2Service.add(entity2);
return "showResults";
}
How to do this?
You could create a custom object with the required information and mapped it using th:object.
New Class
public class MyClass {
private Entity1 entity1;
private Entity2 entity2;
// Getters and setters.
}
Form
<form th:action="#{/app/handleForm}" th:object="${myClass}"
method="post">
<input type="text" th:field="*{entity1.field1}"/>
<input type="text" th:field="*{entity1.field2}"/>
<input type="text" th:field="*{entity2.field3}"/>
</form>
Controller
#PostMapping("app/handleForm")
public String RHTraiterDemande(Model m, MyClass myClass) {
entity1Service.add(myClass.entity1);
entity2Service.add(myClass.entity2);
return "showResults";
}

how to intercept #modelattribute binding

Everyone.
I am using spring mvc framework, and spring form tag. I found unexpected thing when using form dynamically. For example,
public class Person {
public List<Car> myCars = new ArrayList<Car>();
// getter and setter
}
below code is html form
<form:form modelAttribute="car" ...>
<input type="hidden" name="myCars[0].id">
<input type="text" name="myCars[0].name">
<input type="hidden" name="myCars[1].id">
<input type="text" name="myCars[1].name">
<input type="hidden" name="myCars[2].id">
<input type="text" name="myCars[2].name">
</form:form>
and next code is a spring form controller
#Controller
#SessionAttribute({"car"})
public class CarController {
...
#RequestMapping(".....")
public String form(#ModelAttribute Car car, BindingResult result, ...) {
if (result.hasErrors()) {
....
return viewName;
}
....
return "redirect:/" + someWhere;
}
}
1) I entered data into html form.
2) I can confirm that there are 3 Car objects in car.getMyCars()
3) There are some errors as binding, so it's redirected to viewName
4) I changed html form using jQuery like this
<form:form modelAttribute="car" ...>
<input type="hidden" name="myCars[0].id">
<input type="text" name="myCars[0].name">
<input type="hidden" name="myCars[1].id">
<input type="text" name="myCars[1].name">
</form:form>
and, submit. The result of this test is that #ModelAttribue Car car still remains 3rd element in List myCars. I expected to remain 2 Car elements, but it wasn't. I think it remained in session. And it was overwritten new form data to #ModelAttribute Car car object, but last 3rd element wasn't. My test shows that if form elements increase dynamically, binding object using #ModelAttribute have them. But though decreased dynamically, binding object still have them. I hope that Car car object have accurate number of form inputs. What should I do?
Thanks in advance.

how to check existing user in a database with Struts and 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"
/>

Spring WebFlow: view-state is not calling validation method before <evaluate> tag

This problem is driving me crazy.
I have following view-state:
<on-start>
<evaluate expression="new com.zxxztech.zecure.services.webflow.FormularioConfirmacionCorreo()"
result="flowScope.ccForm" />
</on-start>
<view-state id="activacionManual" model="ccForm" >
<transition on="enviar" to="resultado" bind="true">
<evaluate expression="usersManager.activarUsuario(ccForm.correo, ccForm.codigo)"
result="flowScope.resultado" />
</transition>
<transition on="cancelar" to="cancelar" validate="false" bind="false" />
</view-state>
And this is this the Validation class:
#Component
public class FormularioConfirmacionCorreoValidator {
#Autowired
private UsersManager usersManager;
public void validateActivacionManual(FormularioConfirmacionCorreo ccForm, ValidationContext validContext) {
...
[Validation logic]
}
public UsersManager getUsersManager() {
return usersManager;
}
public void setUsersManager(UsersManager usersManager) {
this.usersManager = usersManager;
}
}
When form is submited, webflow execute <evaluate> tag directly, without calling validation method.
I don't know what could I doing wrong.
Edit:
This is the activacionManual.jsp file:
...
<form:form cssClass="ym-form" modelAttribute="ccf" method="post" action="${flowExecutionUrl}">
<form:errors cssClass="ym-error" element="div" path="*"/>
<div class="ym-box">
<div class="ym-fbox">
<label for="correo"><spring:message
code="activacion.form.correo.label"
text="activacion.form.correo.label" /></label>
<form:input path="correo" />
</div>
<div class="ym-fbox">
<label for="codigo"><spring:message
code="activacion.form.codigo.label"
text="activacion.form.codigo.label" /></label>
<form:input path="codigo" />
</div>
<div class="ym-fbox-footer ym-fbox-button">
<input class="ym-button ym-gr" type="submit"
value="<spring:message code="formulario.button.cancelar" text="formulario.button.cancelar" />"
name="_eventId_cancelar">
<input class="ym-button ym-primary ym-gr" type="submit"
value="<spring:message code="formulario.button.enviar" text="formulario.button.enviar" />"
name="_eventId_enviar">
</div>
</div>
</form:form>
...
The second way is to define a separate object, called a Validator, which validates your model object. To do this, first create a class whose name has the pattern ${model}Validator, where ${model} is the capitialized form of the model expression, such as booking. Then define a public method with the name validate${state}, where ${state} is the id of your view-state, such as enterBookingDetails.
Thus, since your model attribute is ccForm, the validator Class must be named CcFormValidator. (Or rename your model attribute.)
(Also, I think your JSP is going to have problems using modelAttribute="ccf" instead of "ccForm". The model name needs to match across flow.xml, JSPs, and validators.)

Resources