如何处理控制器中url的格式错误?

时间:2013-09-12 03:06:44

标签: java spring spring-mvc spring-3

以下是我的控制器:

@RequestMapping("Student/{ID}/{Name}/{Age}")
public void addStudent(@PathVariable String ID,
                       @PathVariable String Name,
                       @PathVariable String Age,
                       HttpServletRequest request, 
                       HttpServletResponse response) throws IOException {
    try {
         // Handling some type errors
        new Integer(Age); // Examine the format of age
        StatusBean bean = new StatusBean();
        bean.setResonCode("000"); // Success/Fail reasons
        bean.setStatus("1"); // 1: Success; 0: Fail
        outputJson(bean, response);
    }
    catch (NumberFormatException e) {
        ...
    }
    catch (Exception e) {
        ...
    }

学生的ID,姓名,年龄由用户输入,这些变量不能为空或空格。

在正常情况下,控制器可以处理http://localhost:8080/Student/003/Peter/17。 但是,它无法处理http://localhost:8080/Student///17http://localhost:8080/Student/003/Peter/等情况。如果我想在控制器中处理这些情况,我该怎么办?

另一个问题是,新的整数(年龄)是检查格式的好方法吗?

1 个答案:

答案 0 :(得分:1)

您可以在调度程序配置中定义错误页面。查看此网站http://blog.codeleak.pl/2013/04/how-to-custom-error-pages-in-tomcat.html它显示一个基本的404页面,您可以从控制器返回任何错误代码,如下所示

@RequestMapping("Student/{ID}/{Name}/{Age}")
public void addStudent(@PathVariable String ID,
                   @PathVariable String Name,
                   @PathVariable String Age,
                   HttpServletRequest request, 
                   HttpServletResponse response) throws IOException {
try {
     // Handling some type errors
    new Integer(Age); // Examine the format of age
    StatusBean bean = new StatusBean();
    bean.setResonCode("000"); // Success/Fail reasons
    bean.setStatus("1"); // 1: Success; 0: Fail
    outputJson(bean, response);
}
catch (NumberFormatException e) {
    ...
    // set http code and let the dispatcher show the error page.
    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
catch (Exception e) {
    ...
    // set http code and let the dispatcher show the error page.
    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}

然后new Integer(Age);并抓住错误。