0

下面是我的控制器:

@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///17或之类的情况http://localhost:8080/Student/003/Peter/。如果我想在我的控制器中处理这些情况,我该怎么办?

另一个问题是, new Integer(Age) 是检查格式的好方法吗?

4

1 回答 1

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);的,发现错误很好。

于 2013-09-12T03:27:44.090 回答