spring boot+JPA+easyUI 实现基于浏览器语言的国际化配置

来源:互联网 发布:python递归函数怎么写 编辑:程序博客网 时间:2024/06/05 02:21

在文章的开头,先声明此源码参考至:http://www.cnblogs.com/je-ge/p/6135676.html。

标题我相信大家已经看过了,文章的大致内容我就不再赘述了,直接上图、上源码,文章最后提供了源码下载,欢迎一起交流。


因为提供了源码下载,我个人比较懒,此处便只附上部分的代码片段:

UserCotroller.java

package com.jege.spring.boot.controller;import java.util.ArrayList;import java.util.List;import java.util.Map;import javax.persistence.criteria.CriteriaBuilder;import javax.persistence.criteria.CriteriaQuery;import javax.persistence.criteria.Predicate;import javax.persistence.criteria.Root;import javax.servlet.http.HttpServletRequest;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Pageable;import org.springframework.data.domain.Sort;import org.springframework.data.jpa.domain.Specification;import org.springframework.stereotype.Controller;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import com.jege.spring.boot.data.jpa.entity.User;import com.jege.spring.boot.data.jpa.repository.UserRepository;import com.jege.spring.boot.json.AjaxResult;@Controller@RequestMapping("/user")public class UserController extends BaseController {@Autowiredprivate UserRepository userRepository;// 显示用户列表页面@RequestMapping("/list")public String list() {return "user";}// 从user.jsp列表页面由easyui-datagrid发出ajax请求获取json数据@RequestMapping("/json")@ResponseBodypublic Map<String, Object> json(@RequestParam(name = "page", defaultValue = "1") int page, @RequestParam(name = "rows", defaultValue = "10") int rows,final String q, HttpServletRequest request) {// 按照id降序Sort sort = new Sort(Sort.Direction.DESC, "id");// 封装分页查询条件Pageable pageable = new PageRequest(page - 1, rows, sort);// 拼接查询条件Specification<User> specification = new Specification<User>() {@Overridepublic Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {List<Predicate> list = new ArrayList<Predicate>();if (!StringUtils.isEmpty(q)) {list.add(cb.like(root.get("name").as(String.class), "%" + q + "%"));}if (request.getLocale().toString().contains("en")) {list.add(cb.like(root.get("locale").as(String.class), "%en%"));} else {list.add(cb.like(root.get("locale").as(String.class), "%zh%"));}Predicate[] p = new Predicate[list.size()];return cb.and(list.toArray(p));}};return findEasyUIData(userRepository.findAll(specification, pageable));}// 处理保存@RequestMapping("/save")@ResponseBodypublic AjaxResult save(HttpServletRequest request, User user) {String locale = request.getLocale().toString();user.setLocale(locale.substring(0, locale.indexOf(("_"))));userRepository.save(user);return new AjaxResult().success();}// 处理删除@RequestMapping("/delete")@ResponseBodypublic AjaxResult delete(Long id) {userRepository.delete(id);return new AjaxResult().success();}}


初始化数据的InitApplicationListener.java

package com.jege.spring.boot.controller;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationListener;import org.springframework.context.event.ContextRefreshedEvent;import org.springframework.stereotype.Component;import com.jege.spring.boot.data.jpa.entity.User;import com.jege.spring.boot.data.jpa.repository.UserRepository;@Componentpublic class InitApplicationListener implements ApplicationListener<ContextRefreshedEvent> {@Overridepublic void onApplicationEvent(ContextRefreshedEvent event) {ApplicationContext context = event.getApplicationContext();UserRepository userRepository = context.getBean("userRepository", UserRepository.class);User user;for (int i = 1; i < 21; i++) {if (i % 2 == 0) {user = new User("je哥" + i, 25 + i);user.setLocale("zh");} else {user = new User("je-ge" + i, 25 + i);user.setLocale("en");}userRepository.save(user);}}}


全局异常处理类

package com.jege.spring.boot.exception;import java.util.Set;import javax.validation.ConstraintViolation;import javax.validation.ConstraintViolationException;import javax.validation.ValidationException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.dao.DataIntegrityViolationException;import org.springframework.http.HttpStatus;import org.springframework.http.converter.HttpMessageNotReadableException;import org.springframework.validation.BindException;import org.springframework.validation.BindingResult;import org.springframework.validation.FieldError;import org.springframework.web.HttpMediaTypeNotSupportedException;import org.springframework.web.HttpRequestMethodNotSupportedException;import org.springframework.web.bind.MethodArgumentNotValidException;import org.springframework.web.bind.MissingServletRequestParameterException;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.ResponseStatus;import com.jege.spring.boot.json.AjaxResult;@ControllerAdvice@ResponseBodypublic class CommonExceptionAdvice {private static Logger logger = LoggerFactory.getLogger(CommonExceptionAdvice.class);/** * 400 - Bad Request */@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(MissingServletRequestParameterException.class)public AjaxResult handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {logger.error("缺少请求参数", e);return new AjaxResult().failure("required_parameter_is_not_present");}/** * 400 - Bad Request */@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(HttpMessageNotReadableException.class)public AjaxResult handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {logger.error("参数解析失败", e);return new AjaxResult().failure("could_not_read_json");}/** * 400 - Bad Request */@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(MethodArgumentNotValidException.class)public AjaxResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {logger.error("参数验证失败", e);BindingResult result = e.getBindingResult();FieldError error = result.getFieldError();String field = error.getField();String code = error.getDefaultMessage();String message = String.format("%s:%s", field, code);return new AjaxResult().failure(message);}/** * 400 - Bad Request */@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(BindException.class)public AjaxResult handleBindException(BindException e) {logger.error("参数绑定失败", e);BindingResult result = e.getBindingResult();FieldError error = result.getFieldError();String field = error.getField();String code = error.getDefaultMessage();String message = String.format("%s:%s", field, code);return new AjaxResult().failure(message);}/** * 400 - Bad Request */@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(ConstraintViolationException.class)public AjaxResult handleServiceException(ConstraintViolationException e) {logger.error("参数验证失败", e);Set<ConstraintViolation<?>> violations = e.getConstraintViolations();ConstraintViolation<?> violation = violations.iterator().next();String message = violation.getMessage();return new AjaxResult().failure("parameter:" + message);}/** * 400 - Bad Request */@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(ValidationException.class)public AjaxResult handleValidationException(ValidationException e) {logger.error("参数验证失败", e);return new AjaxResult().failure("validation_exception");}/** * 405 - Method Not Allowed */@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)@ExceptionHandler(HttpRequestMethodNotSupportedException.class)public AjaxResult handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {logger.error("不支持当前请求方法", e);return new AjaxResult().failure("request_method_not_supported");}/** * 415 - Unsupported Media Type */@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)@ExceptionHandler(HttpMediaTypeNotSupportedException.class)public AjaxResult handleHttpMediaTypeNotSupportedException(Exception e) {logger.error("不支持当前媒体类型", e);return new AjaxResult().failure("content_type_not_supported");}/** * 500 - Internal Server Error */@ResponseStatus(HttpStatus.OK)@ExceptionHandler(ServiceException.class)public AjaxResult handleServiceException(ServiceException e) {logger.error("业务逻辑异常", e);return new AjaxResult().failure("业务逻辑异常:" + e.getMessage());}/** * 500 - Internal Server Error */@ResponseStatus(HttpStatus.OK)@ExceptionHandler(Exception.class)public AjaxResult handleException(Exception e) {logger.error("通用异常", e);return new AjaxResult().failure("通用异常:" + e.getMessage());}/** * 操作数据库出现异常:名称重复,外键关联 */@ResponseStatus(HttpStatus.OK)@ExceptionHandler(DataIntegrityViolationException.class)public AjaxResult handleException(DataIntegrityViolationException e) {logger.error("操作数据库出现异常:", e);return new AjaxResult().failure("操作数据库出现异常:字段重复、有外键关联等");}}


一些属性配置

## JPA Settingsspring.jpa.generate-ddl: truespring.jpa.show-sql: truespring.jpa.hibernate.ddl-auto: createspring.jpa.properties.hibernate.format_sql: false# 如果不想使用springboot 内嵌的数据库,可以去掉此处注释,建一个test数据库即可#spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8#spring.datasource.username = root#spring.datasource.password = root#spring.datasource.driverClassName = com.mysql.jdbc.Driver# 页面默认前缀目录spring.mvc.view.prefix=/WEB-INF/page/# 响应页面默认后缀spring.mvc.view.suffix=.jsp#添加那个目录的文件需要restartspring.devtools.restart.additional-paths=src/main/java#排除那个目录的文件不需要restart#spring.devtools.restart.exclude=static/**,public/**



一些jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%><!-- c标签:定义项目的路径 --><c:set var="ctx" value="${pageContext.request.contextPath}" /><!-- easyui默认主题样式 --><link rel="stylesheet" type="text/css" href="${ctx}/static/easyui/themes/default/easyui.css"><!-- easyui图标样式--><link rel="stylesheet" type="text/css" href="${ctx}/static/easyui/themes/icon.css"><!-- easyui颜色样式 --><link rel="stylesheet" type="text/css" href="${ctx}/static/easyui/themes/color.css"><!-- 先引入jQuery核心的js --><script type="text/javascript" src="${ctx}/static/easyui/jquery.min.js"></script><!-- 在引入easyui的核心的js--><script type="text/javascript" src="${ctx}/static/easyui/jquery.easyui.min.js"></script><!-- 国际化的js--><c:if test="${fn:contains(request.locale, 'en')}"><script type="text/javascript" src="${ctx}/static/easyui/locale/easyui-lang-en.js"></script></c:if><c:if test="${fn:contains(request.locale, 'zh')}"><script type="text/javascript" src="${ctx}/static/easyui/locale/easyui-lang-zh_CN.js"></script></c:if>


pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.jege.spring.boot</groupId><artifactId>spring-boot-data-jpa-easyui-datagrid-i18n-data</artifactId><version>1.0.0.RELEASE</version><packaging>jar</packaging><name>spring-boot-data-jpa-easyui-datagrid-i18n-data</name><url>http://blog.csdn.net/je_ge</url><developers><developer><id>je_ge</id><name>je_ge</name><email>1272434821@qq.com</email><url>http://blog.csdn.net/je_ge</url><timezone>8</timezone></developer></developers><!-- 公共spring-boot配置,下面依赖jar文件不用在写版本号 --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.4.1.RELEASE</version><relativePath /></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><java.version>1.8</java.version></properties><dependencies><!-- web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 持久层 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><!-- h2内存数据库 --><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency><!-- tomcat 的支持. --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId><scope>provided</scope></dependency><dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId><scope>provided</scope></dependency><!-- servlet --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><scope>provided</scope></dependency><!-- jstl --><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId></dependency><!-- 热部署 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- mysql 数据库驱动. --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency></dependencies><build><finalName>spring-boot-data-jpa-easyui-datagrid-i18n-data</finalName><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><fork>true</fork></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>${java.version}</source><target>${java.version}</target></configuration></plugin></plugins></build></project>



代码目录结构:




效果截图:











附上源码:下载


0 0