没有视图名称的自定义控制器 [英] Custom controller without view name

查看:47
本文介绍了没有视图名称的自定义控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在研究 Spring Controller 层的实际工作方式.如果我想要一个返回模型和视图名称(例如 HTML 文件名)的控制器,我只需扩展 AbstractController 类,然后实现一个 handleRequestInternal 方法,将该控制器注册为 bean,并在我的 HandlerMapping(例如 SimpleUrlHandlerMapping)中设置什么路径映射到什么控制器.

I'm investigating now on how Spring Controller layer actually works. If I want to have a controller that returns a model and view name (e.g. HTML file name) I just extend AbstractController class, then implement a handleRequestInternal method, registering that controller as a bean, and setting in my HandlerMapping (e.g. SimpleUrlHandlerMapping) what path is mapped to what controller.

但这迫使我返回视图名称.

But that forces me to return view name.

如果我不想指定视图名称,而只想返回字符串(例如格式化的 json 或纯文本)或对象以与 @RestController 显示相同怎么办?

What if I would like to not specify the view name, and just return String (e.g. formatted json or plain text) or Object to display same as @RestController displays?

或者换句话说.我应该使用什么视图层 bean 来省略视图名称和显示模型,就像 json/xml/plain text 一样?

Or maybe in other words. What view layer bean should I use to omit view name and display model just as json/xml/plain text ?

我找不到 Spring 提供的任何 JSON 视图 bean.

I couldn't find any JSON view bean provided by Spring.

我提出的解决方法是创建自己的 JSONViewResolver,将其注册为 bean,然后在控制器中指定我想要的视图.

Workaround I made, was to create own JSONViewResolver, register it as bean, and then specify in controller, what view I want.

public class JsonViewResolver implements ViewResolver {

    @Override
    public View resolveViewName(String viewName, Locale locale) throws Exception {
    MappingJackson2JsonView mappingJackson2JsonView = new MappingJackson2JsonView();
    mappingJackson2JsonView.setPrettyPrint(true);
    return mappingJackson2JsonView;
    }
}

推荐答案

@nowszy94 - 只要在方法前提及@ResponseBody.Spring 会自动将其转换为字符串,而不是通过视图解析器来查找 jsp.

@nowszy94 - just mention @ResponseBody before the method. Spring will automatically convert it into a string instead of going through the view resolver to find the jsp.

这篇关于没有视图名称的自定义控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆