SpringBoot如何返回頁面


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所訪問的目錄。但好像只能有一個目錄。

綜上:模板引擎的使用與否都可以實現頁面的訪問。區別在於頁面所存放的位置以及訪問或返回的時候后綴名加不加的問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM