You are on page 1of 12

Spring MVC Validation

The Spring MVC Validation is used to restrict the input provided by the user. To validate the
user's input, the Spring 4 or higher version supports and use Bean Validation API. It can
validate both server-side as well as client-side applications.

Bean Validation API


The Bean Validation API is a Java specification which is used to apply constraints on
object model via annotations. Here, we can validate a length, number, regular
expression, etc. Apart from that, we can also provide custom validations.

As Bean Validation API is just a specification, it requires an implementation. So, for


that, it uses Hibernate Validator. The Hibernate Validator is a fully compliant JSR-
303/309 implementation that allows to express and validate application constraints.

Validation Annotations

Add dependencies to pom.xml file.


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-
validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
</dependency>

Create the bean class


import javax.validation.constraints.Size;

public class Employee {

private String name;


@Size(min=1,message="required")
private String pass;

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
3. Create the controller class

The @Valid annotation applies validation rules on the provided object.

The BindingResult interface contains the result of 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 EmployeeController {

@RequestMapping("/hello")
public String display(Model m)
{
m.addAttribute("emp", new Employee());
return "viewpage";
}
@RequestMapping("/helloagain")
public String submitForm( @Valid @ModelAttribute("emp") Employee e, Bi
ndingResult br)
{
if(br.hasErrors())
{
return "viewpage";
}
else
{
return "final";
}
}
}

Create the requested page


index.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"


%>
<html>
<body>
<a href="hello">Click here...</a>
</body>
</html>
Create the other view components
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"
%>
<html>
<head>
<style>
.error{color:red}
</style>
</head>
<body>
<form:form action="helloagain" modelAttribute="emp">
Username: <form:input path="name"/> <br><br>
Password(*): <form:password path="pass"/>
<form:errors path="pass" cssClass="error"/><br><br>
<input type="submit" value="submit">
</form:form>
</body>
</html>

final.jsp

<html>
<body>
Username: ${emp.name} <br><br>
Password: ${emp.pass}
</body>
</html>
Let's submit the form without entering the password.

Now, we entered the password and then submit the form.


JSR-250 Annotations in the Spring
Spring also provides support for JSR-250 annotations which
include @PostConstruct, @PreDestroy and @Resource annotations. JSR-250 aka Common
Annotations for the Java Platform was introduced as part of Java EE 5 an is usually used to
annotated EJB3s.

 @PostContruct – This annotation is applied to a method to indicate that it


should be invoked after all dependency injection is complete.
 @PreDestroy – This is applied to a method to indicate that it should be invoked
before the bean is removed from the Spring context, i.e. just before it’s
destroyed.
 @Resource – This duplicates the functionality of @Autowired combined
with @Qualifier as you get the additional benefit of being able to name which
bean you’re injecting, without the need for two annotations.

@RequestMapping is one of the most widely used Spring


MVC annotation. org.springframework.web.bind.annotation.RequestMapping
annotation is used to map web requests onto specific handler classes
and/or handler methods.
@RequestMapping can be applied to the controller class as well as methods

Spring @RequestMapping
1. @RequestMapping with Class: We can use it with class definition to create
the base URI. For example:
@Controller
@RequestMapping("/home")
public class HomeController {

Now /home is the URI for which this controller will be used. This concept is
very similar to servlet context of a web application.
2. @RequestMapping with Method: We can use it with method to provide the
URI pattern for which handler method will be used. For example:
@RequestMapping(value="/method0")
@ResponseBody
public String method0(){
return "method0";

Spring
NamedParameterJdbcTemplate
Example

Spring provides another way to insert data by named


parameter. In such way, we use names instead of ?(question
mark). So it is better to remember the data for the column.

1. insert into employee values (:id,:name,:salary)


Method of NamedParameterJdbcTemplate class

In this example,we are going to call only the execute method of


NamedParameterJdbcTemplate class. Syntax of the method is as follows:

pubic T execute(String sql,Map map,PreparedStatementCallback psc)

create table employee(


id number(10),
name varchar2(100),
salary number(10)
);

public class Employee {


private int id;
private String name;
private float salary;
//no-arg and parameterized constructors
//getters and setters
}
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTe
mplate;
import java.util.*;

public class EmpDao {


NamedParameterJdbcTemplate template;

public EmpDao(NamedParameterJdbcTemplate template) {


this.template = template;
}
public void save (Emp e){
String query="insert into employee values (:id,:name,:salary)";

Map<String,Object> map=new HashMap<String,Object>();


map.put("id",e.getId());
map.put("name",e.getName());
map.put("salary",e.getSalary());

template.execute(query,map,new PreparedStatementCallback() {
@Override
public Object doInPreparedStatement(PreparedStatement ps)
throws SQLException, DataAccessException {
return ps.executeUpdate();
}
});
}

@PathVariable

the @PathVariable annotation can be used to handle template variables in the


request URI mapping,

A simple use case of the @PathVariable annotation would be an endpoint that


identifies an entity with a primary key:
@GetMapping("/api/employees/{id}")
@ResponseBody
public String getEmployeesById(@PathVariable String id) {
return "ID: " + id;
}

Spring – MVC RequestParam


Annotation
In Spring MVC, the @RequestParam annotation is used to read the form data and
bind it automatically to the parameter present in the provided method. So, it ignores
the requirement of HttpServletRequest object to read the provided data.

Including form data, it also maps the request parameter to query parameter and
parts in multipart requests. If the method parameter type is Map and a request
parameter name is specified, then the request parameter value is converted to a Map
else the map parameter is populated with all request parameter names and values

@Controller
public class HelloController {

@RequestMapping("/hello")
//read the provided form data
public String display(@RequestParam("name") String name,@RequestPara
m("pass") String pass,Model m)
{
if(pass.equals("admin"))
{
String msg="Hello "+ name;
//add a message to the model
m.addAttribute("message", msg);
return "viewpage";
}
else
{
String msg="Sorry "+ name+". You entered an incorrect password";
m.addAttribute("message", msg);
return "errorpage";
}
}
}

You might also like