如果不加以异常处理,错误信息肯定会抛在浏览器页面上,这样很不友好,所以必须进行异常处理。
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
@Component
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", ex.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAccount14")
public String findAccount14(Model model) {
model.addAttribute("msg", "欢迎你 springmvc");
//模拟异常信息
int i = 10/0;
return "success";
}
}
<a href="/account/findAccount14">异常处理器</a>
public class DataConvert implements Converter<String, Date> {
/***
* 配置时间转换类
* @param date
* @return
*/
@Override
public Date convert(String date) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
<!--注册类型转换器:处理器映射器去调用convertionServiceBean-->
<mvc:annotation-driven conversion-service="convertionServiceBean"/>
<!-- 配置转换器 -->
<bean id="convertionServiceBean"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.by.converter.DataConverter"></bean>
</set>
</property>
</bean>