Reputation: 399
Hi I am very new to Spring MVC. I am trying to create 1 login page with annotation based validation. Since I have kept @NonEmpty for user ID and password, I am expecting when user enters nothing and submit then validation should fail. But my if block(result.hasErrors()) in login controller is not getting executed when user do not enters anything.I have tried different approach but still no good result for me.
LoginController.java
public ModelAndView doLogin(HttpServletRequest request, @Valid @ModelAttribute("user") User user, BindingResult result, Model model) {
if(result.hasErrors()) {
return new ModelAndView("loginForm");
}
}
User.java
public class User {
@NonEmpty
private String userID;
@NonEmpty
private String password;
.
.
.
}
loginForm.jsp
<body>
<form:form modelAtrribute="user" method="POST" commandName="user">
User ID:
<input type="text" name="userID"/>
<form:errors path="userID"/>
Password:
<form:password path="password"/>
<form:errors path="password"/>
<input type="submit" value="Login"/>
</form>
</body>
spring-servlet.xml
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="viewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property
</bean>
<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" id="tilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</peroperty>
</bean>
tiles.xml
<tiles-definitions>
<definition name="plain.definition" template="/WEB-INF/plain/plain.jsp">
<put-attribute name="body" value=""></put-attribute>
</definition>
<definition extends="plain.definition" name="loginForm">
<put-attribute name="title" value="Login"></put-attribute>
<put-attribute name="body" value="/WEB-INF/jsp/loginForm.jsp"></put-attribute>
</definition>
</tiles-definitions>
Upvotes: 2
Views: 388
Reputation: 399
Found solution for this problem. In my spring-servlet.xml I had <context:annotation-config>
but not <mvc:annotation-driven />
.
<context:annotation-config>
supported some annotations but for @Valid
I needed <mvc:annotation-driven />
. After adding this my validations are running fine.
Though I have not figured out completely differences between these 2 tags.
Upvotes: 1