下面我将详细讲解Spring MVC+FastJson+hibernate-validator整合的完整实例教程。
一、概述
Spring MVC是一种用于Web开发的基于Java的MVC框架,可以方便地搭建Web应用。FastJson是阿里巴巴的一款开源的JSON处理库,相对于其他JSON处理库,FastJson有着更快的速度和更好的压缩率。hibernate-validator则是在Java Bean验证领域中最常用的一款验证框架。
本文将通过一个完整的实例,展示如何将Spring MVC、FastJson、hibernate-validator整合起来,实现一个Restful风格的API的开发。
二、环境准备
在开始之前,需要准备好以下环境:
- JDK 1.8及以上版本
- Maven
- IDE
三、整合步骤
1.创建Maven项目
在IDE中创建一个Maven项目,开发的过程中,我们将使用到以下几个依赖,因此需要在pom.xml文件中添加以下依赖:
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- FastJson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.5.Final</version>
</dependency>
<!-- Spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
2. 配置Spring MVC
在Spring MVC的配置文件(如:applicationContext.xml)中,需要配置RequestMappingHandlerAdapter和RequestMappingHandlerMapping,以及捕获Spring框架的异常:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="order" value="1" />
<property name="interceptors">
<list>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language" />
</bean>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver">
<property name="defaultErrorView" value="error"></property>
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver">
error
</prop>
</props>
</property>
</bean>
3. 配置hibernate-validator
在Spring MVC的配置文件中增加以下配置:
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
</bean>
<mvc:annotation-driven validator="validator">
<mvc:message-converters>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
4. 编写Controller层代码
在Controller层中,我们定义了两个API接口,一个是新增用户,另一个是查询用户:
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping(value = "/add")
public ResultVO addUser(@RequestBody @Validated UserVO userVO, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return new ResultVO(ResultCode.PARAM_ERROR.getCode(), bindingResult.getAllErrors().get(0).getDefaultMessage(), null);
}
return userService.addUser(userVO);
}
@GetMapping(value = "/{id}")
public ResultVO getUser(@PathVariable Long id) {
return userService.getUserById(id);
}
}
5. 编写Service层代码
在Service层中,我们使用hibernate-validator对UserVO进行校验,以及调用Dao层进行数据操作:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Autowired
private Validator validator;
@Override
public ResultVO addUser(UserVO userVO) {
Set<ConstraintViolation<UserVO>> constraintViolationSet = validator.validate(userVO);
if (!constraintViolationSet.isEmpty()) {
return new ResultVO(ResultCode.PARAM_ERROR.getCode(), constraintViolationSet.iterator().next().getMessage(), null);
}
User user = new User();
BeanUtils.copyProperties(userVO, user);
userDao.saveUser(user);
return new ResultVO(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), user.getId());
}
@Override
public ResultVO getUserById(Long id) {
User user = userDao.getUserById(id);
if (user == null) {
return new ResultVO(ResultCode.USER_NOT_FOUND.getCode(), ResultCode.USER_NOT_FOUND.getMessage(), id);
}
return new ResultVO(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), user);
}
}
6. 编写VO层代码
在VO层中,我们定义了一个UserVO对象,用于接收前端传递过来的参数,并通过hibernate-validator进行校验:
public class UserVO {
@NotNull(message = "用户名不能为空")
@Length(min = 6, max = 20, message = "用户名长度为6-20位")
private String username;
@NotNull(message = "密码不能为空")
@Length(min = 6, max = 20, message = "密码长度为6-20位")
private String password;
@Email(message = "邮箱格式不正确")
private String email;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
7. 编写Dao层代码
在Dao层中,我们使用Hibernate对数据库进行操作,代码如下:
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
private Session getSession() {
return sessionFactory.getCurrentSession();
}
@Override
public void saveUser(User user) {
getSession().save(user);
}
@Override
public User getUserById(Long id) {
return getSession().get(User.class, id);
}
}
四、示例演示
1. 新增用户
请求地址:/user/add
,请求方法:POST,请求参数:
{
"username": "admin",
"password": "admin123",
"email": "admin@example.com"
}
请求结果:
{
"code": 200,
"message": "成功",
"data": 1
}
2. 查询用户
请求地址:/user/1
,请求方法:GET,请求参数:无
请求结果:
{
"code": 200,
"message": "成功",
"data": {
"id": 1,
"username": "admin",
"password": "admin123",
"email": "admin@example.com"
}
}
至此,完整的Spring MVC+FastJson+hibernate-validator整合的实例教程就结束了。希望能对大家有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Spring MVC+FastJson+hibernate-validator整合的完整实例教程 - Python技术站