一、创建转换器(以日期格式为例)
(1)创建转换器类,实现Converter接口
//注意导的包
import org.springframework.core.convert.converter.Converter;
//S代表的是源 Source
//T代表的是目标 Target
public class DateTimeConvert implements Converter<S, T>{
@Override
public T convert(S arg0) {
// TODO Auto-generated method stub
return null;
}}
(2)修改转换器类
public class DateTimeConvert implements Converter<String, Date> {
@Override
public Date convert(String Source) {//设置日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {//将字符串转换为日期
Date date = sdf.parse(Source);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}}
(3)在SpringMvc.xml中配置转换器
<bean id="MyConvert" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="recruit.utils.DateTimeConvert"/>
</set>
</property>
</bean>
除了bean里的id是可以随意取的,其他的都是固定的
<bean id="MyConvert" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<bean class="recruit.utils.DateTimeConvert"/>转换器类的全路径
(4)告诉注解驱动
<mvc:annotation-driven conversion-service="MyConvert"/> 与自定义id名称一致
二、创建拦截器器(以登录拦截为例)
(1)创建拦截器,实现HandlerInterceptor接口
public class Login implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub}
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
// TODO Auto-generated method stub
return false;
}}
(2)对preHandle进行操作
preHandle方法是在被拦截方法执行之前执行,postHandle是在被拦截方法执行之后执行,afterCompletion是当preHandle执行后,必然执行的方法,在postHandle之后执行。
public class Login implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {}
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object obj) throws Exception {//在登录的时候我将email存到session域中,通过request获取session
if(request.getSession().getAttribute("email")!=null){//return true 表示放行
return true;
}else{
//返回到登录界面
response.sendRedirect(request.getContextPath()+"loginUI.action");
}
return false;
}}
(3)在SpringMvc.xml中配置拦截器
<mvc:interceptors>
<mvc:interceptor>
<!-- 拦截user和company路径下的所有子集路径 -->
<mvc:mapping path="/user/**"/>
<mvc:mapping path="/company/**"/><!-- 自定义拦截器的全路径 -->
<bean class="recruit.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>