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

在文章的开头,先声明此源码参考至: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 {

	@Autowired
	private UserRepository userRepository;

	// 显示用户列表页面
	@RequestMapping("/list")
	public String list() {
		return "user";
	}

	// 从user.jsp列表页面由easyui-datagrid发出ajax请求获取json数据
	@RequestMapping("/json")
	@ResponseBody
	public 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>() {
			@Override
			public 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")
	@ResponseBody
	public 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")
	@ResponseBody
	public 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;

@Component
public class InitApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

	@Override
	public 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
@ResponseBody
public 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 Settings
spring.jpa.generate-ddl: true
spring.jpa.show-sql: true
spring.jpa.hibernate.ddl-auto: create
spring.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

#添加那个目录的文件需要restart
spring.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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值