首页 > 解决方案 > Spring 5 控制器返回要在浏览器中加载的 html 字符串

问题描述

我的旧代码是一个 Java Servlet,它接受一些参数并推出一个 HTML 字符串:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Delegate the action
    doAction(request, response);
}

'doAction' 方法做了这样的事情:

public void doAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Read the template EHR HTML file
    String html = FileUtils.readFileToString(new File(getServletContext().getRealPath("/viewer.html")), "utf-8");
     ... make some changes to html ...
     PrintWriter out = response.getWriter();
    out.println(html);   
}

这会向浏览器发送一个 HTML 字符串,并且所有相对位置都有效。我的意思是我们有一个目录结构,我们有:

webapp/viewer.html
webapp/js
webapp/css
webapp/img

加载此页面,所有加载的 js 和 css 和 img 文件都运行良好。我应该说对此的调用是这样的: http://localhost:8080/webapp/servlet ?{some parameters)

现在,我们使用的是 Spring 5,我在设置 Spring 和创建输出 JSON 的 RESTful 端点方面拥有丰富的经验。我调用了一个新的 Spring Controller 传入变量,后端逻辑一切正常。现在我想以与旧 servlet 相同的方式输出 HTML。这就是我现在所拥有的。

@Controller
public class ViewerController
{
    @GetMapping(value = "/viewer", produces = MediaType.TEXT_HTML_VALUE)
    public @ResponseBody String getPatientViewerData(
@RequestParam(value = "token", required = true) String token, 
@RequestParam(value = "myid", required = true) String myid)
{
    String html = "";
    try {
        html = service.getHtmlFromBusinessLogic();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return html;
}

当我测试这个时,我确实将 HTML 返回到我的字符串,但是所有相关链接都被丢弃了,所以如果我对这个控制器的调用是: http://localhost:8080/webapp/api/controller ?{一些参数) 然后我所有的相关链接都在寻找: http://localhost:8080/webapp/api/js/somejs.jshttp://localhost:8080/webapp/api/css/somecss.css

这个 Spring 5 webapp 中的 Application Initializer 如下:

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

private static final Log logger = LogFactory.getLog(ApplicationInitializer.class);

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[]
    { ViewerAppConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return new Class[]
    {};
}

    @Override
    protected String[] getServletMappings() {
       return new String[] { "/api/*" };
    }

}

所以,我确信最简单的解决方案是删除“/api/”以进行任何休息呼叫。我希望会有另一种解决方案,但我不确定是否有任何解决方案。

任何帮助都会很棒。谢谢!

标签: javahtmlspringrestspring-mvc

解决方案


你的代码看起来不错。也许您唯一需要定义的是如何在Spring 配置中提供静态资源。像这样的东西:

@Configuration
@EnableWebMvc 
public class MvcConfig implements WebMvcConfigurer { 
    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**") // your prefered mapping, for example web app root
                .addResourceLocations("/resources/"); // project files location
    }
}

通过这种方式,您可以告诉Spring在哪里公开您的所有内容,您css, js, etc...也不需要更改DispatcherServlet url 映射。


推荐阅读