简体   繁体   English

在不将Controller映射到URL模式的情况下获取Spring视图

[英]Get Spring view without mapping a Controller to a URL pattern

I need to create a method just like a Controller method, but without mapping it to a request pattern, as it should be called from another piece of code. 我需要创建一个与Controller方法类似的方法,但是没有将其映射到请求模式,因为应该从另一段代码中调用它。

The method will take some parameters and, probably, populate the model. 该方法将采用一些参数,并且可能会填充模型。

Basically I want Spring MVC to do the job of merging model with the view jsp, and, probably, print it to the HttpServletResponse that I provide and set some other headers like Spring will normally do. 基本上,我希望Spring MVC完成将模型与视图jsp合并的工作,并且可能将其打印到我提供的HttpServletResponse并设置其他通常类似于Spring的标头。

Should be a few lines of code but I can't imagine which:) 应该是几行代码,但我无法想象:

You can try ViewControllerRegistry to generated the view without using the controller. 您可以尝试使用ViewControllerRegistry生成视图而不使用控制器。

Please check the example bellow. 请检查以下示例。 I am using java based configration. 我正在使用基于Java的配置。

@Configuration
@EnableWebMvc
public class MVCConfig extends WebMvcConfigurerAdapter {
    @Bean  
    public InternalResourceViewResolver viewResolver() {  
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();  
        resolver.setPrefix("/WEB-INF/pages/");  
        resolver.setSuffix(".jsp");
        return resolver;  
    }
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("myhome");
        registry.addViewController("/hello").setViewName("helloworld");
        registry.addRedirectViewController("/home", "/hello");
        registry.addStatusController("/detail", HttpStatus.BAD_REQUEST);        
    }    
}

My myhome.jsp file would be 我的myhome.jsp文件是

<html>
<head><title>Home Page</title></head>
<body>
   <h3> Home Page </h3>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM