【问题标题】:How to handle the format error of url in controller?如何处理控制器中url的格式错误?
【发布时间】:2013-09-16 06:33:19
【问题描述】:

下面是我的控制器:

@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/ 等情况。如果我想在我的控制器中处理这些情况,我该怎么做?

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

【问题讨论】:

标签: java spring spring-mvc spring-3


【解决方案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); 并且发现错误很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-26
    • 2016-11-06
    • 2016-05-19
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多