Friday, 2 March 2018

16.0 Java's Standard Bean Validation For Form - @Max @Min and Resource property file

Example of @Max and @Min validation (Download)





































Below code helps to convert this big exception into a customize one .
-----------------------------------------------------------------------------------------------------------------
spring-mvc-demo-servlet.xml
-----------------------------------------------------------------------------------------------------------------
<!-- load custom message resources -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="resources/messages"></property>
</bean>


-----------------------------------------------------------------------------------------------------------------
messages.properties
-----------------------------------------------------------------------------------------------------------------
typeMismatch.programmer.experience=invalid number





















-----------------------------------------------------------------------------------------------------------------
Programmer.java
-----------------------------------------------------------------------------------------------------------------
package com.spring.demo.validation;

import java.util.LinkedHashMap;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Programmer {
@NotNull
@Size(min=1,message="is required")
private String firstName;

@NotNull
@Size(min=1,message="is required")
private String lastName;

@NotNull(message="is required")
@Min(value=0,message="must be greater than or equal to zero")
@Max(value=10,message="must be less than or equal to 10")
private int experience;
private String[] editor;
private String time;
private String language;
LinkedHashMap<String, String> expertise=new LinkedHashMap<>();

public Programmer(){
expertise=new LinkedHashMap<>();
expertise.put("JAVA", "JAVA");
expertise.put("CPP", "CPP");
expertise.put("PYTHON", "PYTHON");
expertise.put("PHP", "PHP");
expertise.put("ASP", "ASP");
}

public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}

public LinkedHashMap<String, String> getExpertise() {
return expertise;
}

public String getLanguage() {
return language;
}

public void setLanguage(String language) {
this.language = language;
}

public String[] getEditor() {
return editor;
}

public void setEditor(String[] editor) {
this.editor = editor;
}

public int getExperience() {
return experience;
}

public void setExperience(int experience) {
this.experience = experience;
}


}


-----------------------------------------------------------------------------------------------------------------
ProgramController.java
-----------------------------------------------------------------------------------------------------------------
package com.spring.demo.validation;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ProgramController {
@RequestMapping("/")
public String showHome(){
return "home";
}
@RequestMapping("/form")
public String showForm(Model model){
Programmer programmer=new Programmer();
model.addAttribute(programmer);
return "form";
}
@RequestMapping("/processForm")
public String processForm(@Valid @ModelAttribute("programmer") Programmer p,BindingResult br){
if(br.hasErrors())
{
System.out.println(br);
return "form";
}
else
{
return "output";
}
}
}

when you print br object you'll get the code in your console which you have to use in your messages.properties to manipulate the long exceptions.

-----------------------------------------------------------------------------------------------------------------
messages.properties
-----------------------------------------------------------------------------------------------------------------
typeMismatch.programmer.experience=invalid number

-----------------------------------------------------------------------------------------------------------------
home.jsp
-----------------------------------------------------------------------------------------------------------------
<html>
<head>
<title>HOME</title>
</head>
<body>
<h2>Welcome to Spring Validation Practice</h2>
<h3><a href="form">Click here to fill programmer's form</a></h3>
</body>
</html>


-----------------------------------------------------------------------------------------------------------------
form.jsp
-----------------------------------------------------------------------------------------------------------------
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>FORM</title>
<style type="text/css">
.error{color: red;}
</style>
</head>
<body>
<h2>Welcome to Spring Validation Practice</h2>
<form:form action="processForm" modelAttribute="programmer">
<table>
<tr>
<td></td>
<td>PROGRAMMER</td>
<td></td>
</tr>
<tr>
<td>First Name (*)</td>
<td><form:input path="firstName" /></td>
<td><form:errors path="firstName" cssClass="error" /></td>
</tr>
<tr>
<td>Last Name (*)</td>
<td><form:input path="lastName"/></td>
<td><form:errors path="lastName" cssClass="error" /></td>
</tr>
<tr>
<td>Which time is good for coding</td>
<td>
<form:radiobutton path="time" value="Day"/>Day
<form:radiobutton path="time" value="Night"/>Night
</td>
<td></td>
</tr>
<tr>
<td>What is your Expertise </td>
<td>
<form:select path="language">
<form:options  items="${programmer.expertise}" />
</form:select>
</td>
<td></td>
</tr>
<tr>
<td>Which is your Favourite Editor</td>
<td>
<form:checkbox path="editor" value="Notepad++"/>Notepad++
<form:checkbox path="editor" value="Edit++"/>Edit++
<form:checkbox path="editor" value="Sublime"/>Sublime
<form:checkbox path="editor" value="Comodo"/>Comodo
</td>
<td></td>
</tr>
<tr>
<td>Experience in coding (*)</td>
<td><form:input path="experience"/></td>
<td><form:errors path="experience" cssClass="error" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="SUBMIT"></td>
<td></td>
</tr>
</table>
</form:form>
</body>
</html>

-----------------------------------------------------------------------------------------------------------------
output.jsp
-----------------------------------------------------------------------------------------------------------------
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>OUTPUT</title>
<style type="text/css">
.error{color: red;}
</style>
</head>
<body>
<h2>Welcome to Spring Validation Practice</h2>
<table border=1 style="width: 50%;border-collapse: collapse;">
<tr><td colspan="2" align="center">PROGRAMMER</td></tr>
<tr>
<td>First Name</td>
<td>${programmer.firstName}</td>
</tr>
<tr>
<td>Last Name</td>
<td>${programmer.lastName}</td>
</tr>
<tr>
<td>Which time is good for coding</td>
<td>${programmer.time}</td>
</tr>
<tr>
<td>What is your Expertise</td>
<td>${programmer.language}</td>
</tr>
<tr>
<td>Which is your Favourite Editor</td>
<td><c:forEach items="${programmer.editor}" var="temp">${temp} , </c:forEach></td>
</tr>
<tr>
<td>Experience in coding</td>
<td>${programmer.experience}</td>
</tr>
</table>
</body>
</html>


-----------------------------------------------------------------------------------------------------------------
spring-mvc-demo-servlet.xml
-----------------------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!-- Step 3: Add support for component scanning -->
<context:component-scan base-package="com.spring.demo.validation" />

<!-- Step 4: Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>

<!-- Step 5: Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- load custom message resources -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="resources/messages"></property>
</bean>
</beans>

-----------------------------------------------------------------------------------------------------------------
web.xml
-----------------------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">

<display-name>spring-mvc-demo</display-name>

<!-- Spring MVC Configs -->

<!-- Step 1: Configure Spring MVC Dispatcher Servlet -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-demo-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>



No comments:

Post a Comment