3.自定义类型转换器开发及配置。
java转换器代码:
public class MyStringToDateConverter implements Converter<String, Date> {
@Override
public Date convert(String s) {
if (s==null) {
throw new RuntimeException("请您传入数据");
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/mm/dd");
try {
if (s.charAt(4) == '-') {
return sdf.parse(s);
} else {
return sdf2.parse(s);
}
} catch (Exception e) {
throw new RuntimeException("数据格式有误!!!");
}
}
}
配置自定义类型转换器:
<!--配置自定义类转换器--><!--需要在下面启用注解配置conversion-service-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.lz.utils.MyStringToDateConverter"/>
</set>
</property>
</bean>
<!--启用注解-->
<mvc:annotation-driven enable-matrix-variables="true" conversion-service="conversionService">
<mvc:async-support default-timeout="10"/><!--子元素可指定异步拦截器-->
</mvc:annotation-driven>
9.自定义异常处理器
1.自定义异常
/**
* 自定义异常
* @author lz先生
*/
public class MyException extends Exception {
private String message;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public MyException(String message) {
this.message = message;
}
}
2.异常处理
/**
* 异常处理跳转到自定义myError页面
* @author lz先生
*/
public class MyExceptionResolver implements HandlerExceptionResolver {
/**
* 异常处理器
* @param request
* @param response
* @param o
* @param e
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
/*获取异常*/
MyException myException = null;
if (e instanceof MyException) {
myException = (MyException) e;
} else {
myException = new MyException("系统正在维护...");
}
ModelAndView view = new ModelAndView();
view.addObject("errorMsg", myException.getMessage());
view.setViewName("myError");
return view;
}
}
3.配置自定义异常处理器
<!--配置异常处理器-->
<bean id="myExceptionResolver" class="com.lz.exception.MyExceptionResolver"/>
4.异常模拟
/**
* 模拟异常
* @return
* @throws Exception
*/
@RequestMapping("/testException")
public String testException() throws Exception {
System.out.println("testException执行了....");
try {
/*模拟异常*/
int a = 10 / 0;
} catch (Exception e) {
e.printStackTrace();
throw new MyException("模拟异常出错");
}
return "good";
}