Spring Boot學習之路——自定義攔截器
阿新 • • 發佈:2019-01-27
Spring Boot簡介
Spring Boot很大程度上簡化了基於Spring的應用開發,只需要呼叫“run”方法就可以建立一個獨立的,產品級別的Spring應用。Spring Boot能夠為所有Spring開發提供一個從根本上更快,且隨處可得的入門體驗;提供了一系列大型專案常用的飛功能性特徵,比如:內嵌伺服器,安全,指標,健康監測和外部化配置;絕對不會有程式碼生成,也不需要XML配置。
本文示例採用了eclipse、maven、Jdk 1.7等軟體,資料持久層採用的是mybatis,資料庫採用的mysql。
示例專案結構圖
Spring Boot核心配置檔案
#mysql配置項
spring.datasource.platform=mysql
spring.datasource.url=jdbc:mysql://10.64.11.192:3306/appcv?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driverClassName=com.mysql.jdbc.Driver
# Advanced configuration...
spring.datasource.max -active=50
spring.datasource.max-idle=6
spring.datasource.min-idle=2
spring.datasource.initial-size=6
#server
server.port=8080
server.session-timeout=30
server.tomcat.uri-encoding=UTF-8
#spring profiles
spring.http.encoding.charset=UTF-8
spring.http.encoding.enable=true
spring.http.encoding.force=true
#MyBatis
mybatis.typeAliasesPackage=com.zenglei.entity #定義別名
mybatis.mapperLocations=classpath:/mybatis/UserMapper.xml #mybatis配置檔案
#log日誌
logging.level.com.zenglei=DEBUG
logging.file=logg.txt
專案依賴 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.zenglei.changan</groupId>
<artifactId>springbootDemo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springbootDemo Maven Webapp</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
</parent>
<dependencies>
<!--測試 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!-- Spring boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- myBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- mysql依賴 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.17</version>
</dependency>
<!-- jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>production</id>
<dependencies>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<type>pom.lastUpdated</type>
</dependency>
</dependencies>
</profile>
</profiles>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Spring Boot主入口程式
只需要呼叫SpringApplication的static run方法,執行java application即可啟動。
@SpringBootApplication
@ComponentScan
/**
* SpringBoot主入口程式
* @author ZengL
*
*/
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
通過WebMvcConfigurerAdapter來配置攔截器
自定義類來繼承WebMvcConfigurerAdapter,重寫addInterceptors方法。
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//super.addInterceptors(registry);
//攔截所有請求
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
}
}
具體實現MyInterceptor攔截器
這個與Spring MVC類似,實現HandlerInterceptor介面,根據具體業務要求來分別重寫afterCompletion、postHandle和preHandle三個方法。
public class MyInterceptor implements HandlerInterceptor{
/**
* 完成整個請求之後呼叫
*/
@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("3333333333333333333");
}
/**
* 進入controller方法之後,渲染檢視之前呼叫
*/
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
System.out.println("2222222222222222222");
}
/**
* 進入controller方法之前呼叫
*/
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
System.out.println("1111111111111111111");
return true;
}
}
controller層
/**
* 使用者控制器
*
* @author ZengL
*
*/
@RestController
@RequestMapping(value = "/user")
public class UserController {
private final Logger log = LoggerFactory.getLogger(UserController.class);
@Autowired
private IUserService userService;
@RequestMapping(value = "/addUser")
public void addUser(HttpServletRequest request , HttpServletResponse response) {
log.debug("REST request to add user");
String id = request.getParameter("id");
String userName = request.getParameter("userName");
String passWord = request.getParameter("passWord");
User user = new User();
String msg = null ;
if(id != null && id != ""){
user.setId(id);
}
if(userName != null && userName != ""){
user.setUserName(userName);
}
if(passWord != null && passWord != ""){
user.setPassWord(passWord);
}
try {
userService.addUser(user);
log.debug("新增成功!");
msg = "註冊成功!";
} catch (Exception e) {
log.debug("新增異常!");
msg = "註冊失敗!";
}
try {
response.sendRedirect("/test.jsp");
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping(value = "/add")
public void add(HttpServletRequest request, HttpServletResponse response) {
log.debug("REST request to add user");
try {
response.sendRedirect("/login.jsp");
} catch (Exception e) {
e.printStackTrace();
}
}
}
service實現
/**
* 使用者service實現類
* @author ZengL
*
*/
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao;
@Override
public void addUser(User user) {
try {
userDao.addUser(user);
} catch (Exception e) {
throw e;
}
}
@Override
public void updateUser(User user) {
try {
userDao.updateUser(user);
} catch (Exception e) {
throw e;
}
}
@Override
public void deleteUser(String id) {
try {
userDao.deleteUser(id);
} catch (Exception e) {
throw e;
}
}
@Override
public User getUserByUserName(User user) {
User userR = null;
try {
userR = userDao.getUserByUserName(user);
return userR;
} catch (Exception e) {
throw e;
}
}
}
dao層
注意IUserDao上的註解加的是@Mapper,這個與Spring MVC有點區別
/**
* 使用者dao層
* @author ZengL
*
*/
@Mapper
public interface IUserDao {
/**
* 新增使用者
* @param user
*/
public void addUser(User user);
/**
* 更新使用者
* @param user
*/
public void updateUser(User user);
/**
* 刪除使用者
* @param id
*/
public void deleteUser(String id);
/**
* 根據使用者名稱查詢使用者
* @param user
* @return
*/
public User getUserByUserName(User user);
}
user實體類
/**
* user實體類
* @author zengl
*
*/
public class User {
private String id;
private String userName;
private String passWord;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
}
mapper.xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zenglei.dao.IUserDao" >
<!--新增使用者 -->
<insert id="addUser" parameterType="com.zenglei.entity.User" >
insert into zengTest (id, userName, passWord)
values (#{id,jdbcType=VARCHAR},
#{userName,jdbcType=VARCHAR},
#{passWord,jdbcType=VARCHAR})
</insert>
<!--更新使用者 -->
<update id="updateUser" parameterType="com.zenglei.entity.User" >
update zengTest set
(userName = #{userName,jdbcType=VARCHAR},
passWord = #{passWord,jdbcType=VARCHAR})
<where>
id = #{id,jdbcType=VARCHAR}
</where>
</update>
<!--刪除使用者 -->
<delete id="deleteUser" parameterType="java.lang.String" >
delete from zengTest
<where>
id = #{id,jdbcType=VARCHAR}
</where>
</delete>
<!-- 根據使用者名稱查詢使用者 -->
<select id="getUserByUserName" resultType="com.zenglei.entity.User" parameterType="com.zenglei.entity.User" >
select id , userName , passWord
from zengTest
<where>
userName = #{userName,jdbcType=VARCHAR}
</where>
</select>
</mapper>
資料庫建表
CREATE TABLE `zengTest` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`userName` VARCHAR(50) NOT NULL,
`passWord` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`)
)
通過以上步驟,就可以自定義攔截器,這裡為Spring Boot入門朋友提供一個簡單教程,可快速上手Spring Boot,有什麼問題歡迎大家留言,一起進步。
溫馨提示:上述程式碼可以直接複製使用。