Custom controller without view name

扶醉桌前 提交于 2020-01-24 01:08:19

问题


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.

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?

EDIT.

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 ?

ANSWER.

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

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

回答1:


@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.



来源:https://stackoverflow.com/questions/41016018/custom-controller-without-view-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!