小五六资源网,小五六博客
  • 首页
  • Java
  • springboot controller返回html页面

springboot controller返回html页面

发布:小五六资源网 2020年10月27日 9:02 星期二分类: Java

SpringBoot中使用Controller和页面的结合能够很好地实现用户的功能及页面数据的传递。但是在返回页面的时候竟然会出现404或者500的错误,我总结了一下如何实现页面的返回以及这里面所包含的坑。


SpringBoot中对Thymeleaf的集成已经基本完善,但在特殊情况下,并不需要或者不能使用Thymeleaf,所以分成两种情况对页面的返回进行阐述。

首先说一下这两种情况下都会发生的错误,也是新手们经常会出现的错误。

直接上代码:

复制代码
@RestController public class TestController {
    @RequestMapping("/") public String index() { return "index";
    }
}
复制代码

这个代码的初衷是返回index.html页面,但是执行的结果是在页面中输出index。

原因分析:@RestController注解相当于@ResponseBody和@Controller合在一起的作用。在使用@RestController注解Controller时,Controller中的方法无法返回jsp页面,或者html,配置的视图解析器 InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。

包括在Mapping注解使用的同时使用@ResponseBody时也会出现同样的问题。

解决办法:①去除@ResponseBody或将含有Rest的注解换成对应的原始注解;

           ②不通过String返回,通过ModelAndView对象返回,上述例子可将return语句换成下面的句子:

 return new ModelAndView("index");

在使用ModelAndView对象返回的时候,不需要考虑有没有@ResponseBody类似的注解。

还有一个需要注意的点:@RequestMapping中的路径一定不要和返回的页面名称完全相同,这样会报500的错误!!!!

如下面这样是不行的:

复制代码
@Controller public class TestController {
    @RequestMapping("/index") public String idx() { return "index";
    }
}
复制代码

 

--------------------------------------------------------分隔线-----------------------------------------------

1、在不使用模板引擎的情况下:

在不使用模板引擎的情况下,访问页面的方法有两种:

1)将所需要访问的页面放在resources/static/文件夹下,这样就可以直接访问这个页面。如:

在未配置任何东西的情况下可以直接访问:

而同样在resources,但是在templates文件夹下的login.html却无法访问:

 2)使用redirect实现页面的跳转

示例代码(在页面路径和上面一致的情况下):

复制代码
@Controller public class TestController {
    @RequestMapping("/map1") public String index() { return "redirect:index.html";
    }
    @RequestMapping("/map2") public String map2() { return "redirect:login.html";
    }
}
复制代码

执行结果:

 

 这说明这种方法也需要将html文件放在static目录下才能实现页面的跳转。

当然还是有终极解决方案来解决这个存放路径问题的,那就是使用springmvc的配置:

复制代码
spring:
  mvc:
    view:
      suffix: .html static-path-pattern: /** resources:
    static-locations: classpath:/templates/,classpath:/static/
复制代码

这样配置后,map1和map2都可以访问到页面了。

2、使用Thymeleaf模板引擎:

先将所需要的依赖添加至pom.xml

复制代码
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.1.6.RELEASE</version> </dependency>
复制代码

同样的页面路径下将controller代码修改成下面的代码:

复制代码
@Controller public class TestController {
    @RequestMapping("/map1") public String index() { return "index";
    } /** 下面的代码可以实现和上面代码一样的功能 */ /*public ModelAndView index() {
        return new ModelAndView("index");
    }*/ @RequestMapping("map2") public String map2() { return "login";
    }
}
复制代码

执行结果:

这又说明一个问题,所需要的页面必须放在templates文件夹下。当然也可以修改,更改配置文件:

spring:
  thymeleaf:
    prefix: classpath:/static/ suffix: .html
    cache: false #关闭缓存

更改prefix对应的值可以改变Thymeleaf所访问的目录。但好像只能有一个目录。

温馨提示如有转载或引用以上内容之必要,敬请将本文链接作为出处标注,谢谢合作!

发表评论: