【问题标题】:Returning either a JSP view or a plain message on a Controller在控制器上返回 JSP 视图或普通消息
【发布时间】:2018-06-13 13:48:48
【问题描述】:

在同一个控制器处理程序方法上,我想:

  • 请求有效时返回 JSP 视图
  • 设置适当的 HTTP 状态代码,如果请求无效,只需将简单的字符串消息写入响应正文

Spring MVC 可以做到这一点吗?

【问题讨论】:

    标签: java spring-mvc


    【解决方案1】:

    可以。

    @RequestMapping(value = "/show", method = RequestMethod.GET)
    public String show(ModelMap model, 
                        HttpServletRequest request, 
                        HttpServletResponse response) {
    
        if (isValidAsYouWant(request)) { // check validity 
             // setup reference data
    
            return "viewName";
    
        } else {
            response.setStatus(400);
            try {
                response.getWriter().write("Invalid Request");
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return null;           
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多