【问题标题】:How to achieve the method of controller that will be requested by client in interceptor of Spring MVC如何在Spring MVC的拦截器中实现客户端请求的控制器方法
【发布时间】:2012-05-08 21:01:39
【问题描述】:

我的需求是实现拦截器中的控制器方法和拦截器中方法返回的对象。

为什么?

因为我想声明将使用方法上注释的注释返回给客户端的数据类型。例如:

@Controller
@Scope("prototype")
@RequestMapping("/hello/")
public class HelloWorld {
    @ResponseType(DataType.JSON)
    @RequestMapping(value="/{username}")
    public UserInfo hellowUser(@PathVariable("username") String username) {
         UserInfo userInfo = new UserInfo();
         userInfo.setUsername(username);
         return userInfo.
    }
}

然后是拦截器:

public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throw Exception {
    Method method = getRequestedMethod();
    Object result = getResultReturnedByTheMethod();
    ResponseType responseType = method.getAnnotation(ResponseType.class);
    DataType type = responseType.value();
    swich(type) {
    case DataType.JSON : writeJson(result);
    case .......
    ...
    }
}

那么,换句话说,如何正确实现“getRequestedMethod”和“getResultReturnedByTheMethod”?

【问题讨论】:

  • Spring MVC 能够使用 @ResponseBody 自行处理 JSON 输出(无需您为其编写自定义拦截器)

标签: servlets spring-mvc request interceptor


【解决方案1】:

您尝试过 Jackson 处理器吗? http://jackson.codehaus.org/

它会自动在控制器之间转换 JSON。并且受 Spring MVC 支持。

【讨论】:

    猜你喜欢
    • 2017-05-29
    • 2016-05-15
    • 2017-03-08
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2023-03-14
    相关资源
    最近更新 更多