0

Below is my controller:

@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) {
        ...
    }

Student's ID, Name, Age are inputted by users,and these variables could not be null or blank space.

In normal case, the controller can handle http://localhost:8080/Student/003/Peter/17. However, it could not handle the cases such as http://localhost:8080/Student///17 or http://localhost:8080/Student/003/Peter/ . How could I do if I want to handle these cases in my controller?

Another question is, new Integer(Age) is a good way to examine the format?

LoveTW
  • 3,746
  • 12
  • 42
  • 52
  • 1
    Please see if the following helps: http://stackoverflow.com/questions/2513031/multiple-spring-requestmapping-annotations – PM 77-1 Sep 12 '13 at 03:17

1 Answers1

1

You can define error pages in your dispatcher configuration. Checkout this website http://blog.codeleak.pl/2013/04/how-to-custom-error-pages-in-tomcat.html it shows a basic 404 page, you can return any error code you want from your controller like this

@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);
}

And yea new Integer(Age); and catching the error is fine.

ug_
  • 11,267
  • 2
  • 35
  • 52