Professional Documents
Culture Documents
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.
Validation Annotations
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";
}
}
}
final.jsp
<html>
<body>
Username: ${emp.name} <br><br>
Password: ${emp.pass}
</body>
</html>
Let's submit the form without entering the password.
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
template.execute(query,map,new PreparedStatementCallback() {
@Override
public Object doInPreparedStatement(PreparedStatement ps)
throws SQLException, DataAccessException {
return ps.executeUpdate();
}
});
}
@PathVariable
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";
}
}
}