Spring 3 MVC And JSR303 @Valid Example

简介:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package  com.xxx.training.controller;
 
import  com.xxx.training.model.User;
import  org.springframework.stereotype.Controller;
import  org.springframework.validation.BindingResult;
import  org.springframework.web.bind.annotation.RequestMapping;
import  org.springframework.web.bind.annotation.RequestMethod;
import  org.springframework.web.servlet.ModelAndView;
 
import  javax.validation.Valid;
 
@Controller
@RequestMapping (value =  "/user" )
public  class  SignUpController {
     @RequestMapping (value =  "signup" , method = RequestMethod.POST)
     public  ModelAndView signUp( @Valid  User user, BindingResult result) {
         if  (result.hasErrors()) {
             return  new  ModelAndView( "signUpForm" );
         }
         return  new  ModelAndView( "done" );
     }
 
     @RequestMapping (method = RequestMethod.GET)
     public  ModelAndView displaySignUpForm() {
         return  new  ModelAndView( "signUpForm" "user" new  User());
     }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package  com.xxx.training.model;
 
 
import  org.hibernate.validator.constraints.NotEmpty;
import  org.hibernate.validator.constraints.Range;
 
public  class  User {
 
     @NotEmpty
     private  String name;
 
     @Range (min =  1 , max =  150 )
     private  int  age;
 
     public  String getName() {
         return  name;
     }
 
     public  void  setName(String name) {
         this .name = name;
     }
 
     public  int  getAge() {
         return  age;
     }
 
     public  void  setAge( int  age) {
         this .age = age;
     }
}

  message.properties

1
2
NotEmpty.user.name = Name is required!
Range.user.age = Age value must be between  1  and  150

  signUpForm.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<%@ taglib prefix= "form"  uri= "http://www.springframework.org/tags/form"  %>
<html>
<head>
     <style>
         .error {
             color: #ff0000;
         }
 
         .errorblock {
             color: # 000 ;
             background-color: #ffEEEE;
             border: 3px solid #ff0000;
             padding: 8px;
             margin: 16px;
         }
     </style>
</head>
 
<body>
<h2>Customer SignUp Form - JSR303  @Valid  example</h2>
 
<form:form method= "POST"  commandName= "user"  action= "signup" >
     <form:errors path= "*"  cssClass= "errorblock"  element= "div" />
     <table>
         <tr>
             <td>Customer Name :</td>
             <td><form:input path= "name" /></td>
             <td><form:errors path= "name"  cssClass= "error" /></td>
         </tr>
         <tr>
             <td>Customer Age :</td>
             <td><form:input path= "age" /></td>
             <td><form:errors path= "age"  cssClass= "error" /></td>
         </tr>
         <tr>
             <td colspan= "3" ><input type= "submit" /></td>
         </tr>
     </table>
</form:form>
 
</body>
</html>

  dispatchServlet-servlet.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
< 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-2.5.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
 
     < context:component-scan  base-package="com.xxx.training"/>
 
     < bean  id="viewResolver"
           class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         < property  name="prefix">
             < value >/WEB-INF/pages/</ value >
         </ property >
         < property  name="suffix">
             < value >.jsp</ value >
         </ property >
     </ bean >
 
     <!-- support JSR303 annotation if JSR 303 validation present on classpath -->
     < mvc:annotation-driven  />
 
     < bean  class="org.springframework.context.support.ResourceBundleMessageSource"
           id="messageSource">
         < property  name="basename" value="messages" />
     </ bean >
 
</ beans >

  web。xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<? xml  version="1.0" encoding="UTF-8"?>
< web-app  version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
     < welcome-file-list >
         < welcome-file >index.jsp</ welcome-file >
     </ welcome-file-list >
 
     < context-param >
         < param-name >contextConfigLocation</ param-name >
         < param-value >classpath:applicationContext.xml</ param-value >
     </ context-param >
 
     < listener >
         < listener-class >org.springframework.web.context.ContextLoaderListener</ listener-class >
     </ listener >
 
     < servlet-mapping >
         < servlet-name >default</ servlet-name >
         < url-pattern >*.png</ url-pattern >
     </ servlet-mapping >
     < servlet-mapping >
         < servlet-name >default</ servlet-name >
         < url-pattern >*.js</ url-pattern >
     </ servlet-mapping >
     < servlet-mapping >
         < servlet-name >default</ servlet-name >
         < url-pattern >*.css</ url-pattern >
     </ servlet-mapping >
 
     < servlet >
         < servlet-name >dispatcherServlet</ servlet-name >
         < servlet-class >org.springframework.web.servlet.DispatcherServlet</ servlet-class >
         < load-on-startup >1</ load-on-startup >
     </ servlet >
 
     < servlet-mapping >
         < servlet-name >dispatcherServlet</ servlet-name >
         < url-pattern >/</ url-pattern >
     </ servlet-mapping >
 
     < filter >
         < filter-name >CharacterEncodingFilter</ filter-name >
         < filter-class >org.springframework.web.filter.CharacterEncodingFilter</ filter-class >
         < init-param >
             < param-name >encoding</ param-name >
             < param-value >UTF-8</ param-value >
         </ init-param >
     </ filter >
     < filter-mapping >
         < filter-name >CharacterEncodingFilter</ filter-name >
         < url-pattern >/</ url-pattern >
     </ filter-mapping >
 
     < error-page >
         < error-code >404</ error-code >
         < location >/WEB-INF/pages/404.jsp</ location >
     </ error-page >
 
</ web-app >

  


==============================================================================
本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/archive/2012/12/27/2836374.html,如需转载请自行联系原作者
目录
打赏
0
0
0
0
15
分享
相关文章
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
本文介绍了 `@RequestParam` 注解的使用方法及其与 `@PathVariable` 的区别。`@RequestParam` 用于从请求中获取参数值(如 GET 请求的 URL 参数或 POST 请求的表单数据),而 `@PathVariable` 用于从 URL 模板中提取参数。文章通过示例代码详细说明了 `@RequestParam` 的常用属性,如 `required` 和 `defaultValue`,并展示了如何用实体类封装大量表单参数以简化处理流程。最后,结合 Postman 测试工具验证了接口的功能。
40 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestBody
`@RequestBody` 是 Spring 框架中的注解,用于将 HTTP 请求体中的 JSON 数据自动映射为 Java 对象。例如,前端通过 POST 请求发送包含 `username` 和 `password` 的 JSON 数据,后端可通过带有 `@RequestBody` 注解的方法参数接收并处理。此注解适用于传递复杂对象的场景,简化了数据解析过程。与表单提交不同,它主要用于接收 JSON 格式的实体数据。
41 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@PathVariable
`@PathVariable` 是 Spring Boot 中用于从 URL 中提取参数的注解,支持 RESTful 风格接口开发。例如,通过 `@GetMapping(&quot;/user/{id}&quot;)` 可以将 URL 中的 `{id}` 参数自动映射到方法参数中。若参数名不一致,可通过 `@PathVariable(&quot;自定义名&quot;)` 指定绑定关系。此外,还支持多参数占位符,如 `/user/{id}/{name}`,分别映射到方法中的多个参数。运行项目后,访问指定 URL 即可验证参数是否正确接收。
30 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestMapping
@RequestMapping 是 Spring MVC 中用于请求地址映射的注解,可作用于类或方法上。类级别定义控制器父路径,方法级别进一步指定处理逻辑。常用属性包括 value(请求地址)、method(请求类型,如 GET/POST 等,默认 GET)和 produces(返回内容类型)。例如:`@RequestMapping(value = &quot;/test&quot;, produces = &quot;application/json; charset=UTF-8&quot;)`。此外,针对不同请求方式还有简化注解,如 @GetMapping、@PostMapping 等。
38 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RestController
本文主要介绍 Spring Boot 中 MVC 开发常用的几个注解及其使用方式,包括 `@RestController`、`@RequestMapping`、`@PathVariable`、`@RequestParam` 和 `@RequestBody`。其中重点讲解了 `@RestController` 注解的构成与特点:它是 `@Controller` 和 `@ResponseBody` 的结合体,适用于返回 JSON 数据的场景。文章还指出,在需要模板渲染(如 Thymeleaf)而非前后端分离的情况下,应使用 `@Controller` 而非 `@RestController`
28 0
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
155 29
步步深入SpringMvc DispatcherServlet源码掌握springmvc全流程原理
通过对 `DispatcherServlet`源码的深入剖析,我们了解了SpringMVC请求处理的全流程。`DispatcherServlet`作为前端控制器,负责请求的接收和分发,处理器映射和适配负责将请求分派到具体的处理器方法,视图解析器负责生成和渲染视图。理解这些核心组件及其交互原理,有助于开发者更好地使用和扩展SpringMVC框架。
82 4
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
32 0
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 介绍
本课介绍Spring Boot集成Thymeleaf模板引擎。Thymeleaf是一款现代服务器端Java模板引擎,支持Web和独立环境,可实现自然模板开发,便于团队协作。与传统JSP不同,Thymeleaf模板可以直接在浏览器中打开,方便前端人员查看静态原型。通过在HTML标签中添加扩展属性(如`th:text`),Thymeleaf能够在服务运行时动态替换内容,展示数据库中的数据,同时兼容静态页面展示,为开发带来灵活性和便利性。
35 0
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
本课主要讲解Spring Boot项目中的属性配置方法。在实际开发中,测试与生产环境的配置往往不同,因此不应将配置信息硬编码在代码中,而应使用配置文件管理,如`application.yml`。例如,在微服务架构下,可通过配置文件设置调用其他服务的地址(如订单服务端口8002),并利用`@Value`注解在代码中读取这些配置值。这种方式使项目更灵活,便于后续修改和维护。
18 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等