一、SpringBoot整合拦截器
1.添加拦截器
package com.by.interceptor;
import com.by.pojo.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user = request.getSession().getAttribute("user");
if(user!=null){
return true;
}
response.sendRedirect("/");
return false;
}
}
2.配置拦截器
@Component
public class SpringMVCConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
//配置拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/user/**").excludePathPatterns("/user/login");
registry.addInterceptor(loginInterceptor).addPathPatterns("/user/**").excludePathPatterns("/user/login");
}
}
3.运用拦截器
二、SpringBoot整合日期转换器
1.添加日期转换器
package com.by.converter;
import java.text.ParseException;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
import org.apache.commons.lang3.time.DateUtils;
public class DateConverter implements Converter<String, Date>{
/**
* 配置日期转换器
* @param str
* @return
*/
@Override
public Date convert(String str) {
try {
String[] patterns = new String[]{
"yyyy-MM-dd","yyyy-MM-dd hh:mm:ss","yyyy/MM/dd","yyyy/MM/dd hh:mm:ss",
"MM-dd-yyyy","dd-MM-yyyy"};
return DateUtils.parseDate(str, patterns);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
2.配置日期转换器
-
说明
WebMvcConfigurer配置类其实是
Spring
内部的一种配置方式,采用JavaBean
的形式来代替传统的xml
配置文件形式针对框架进行个性化定制,例如:拦截器,类型转化器等等。 -
代码示例
@Component
public class SpringMVCConfig implements WebMvcConfigurer {
//配置日期转换器
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateConverter());
}
}