spring boot 如何返回视图而不是string的方法

package com.example.demo.controller;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@EnableAutoConfiguration
public class HelloController {

    @RequestMapping("/hello")

    public String hello() {
        System.out.println("进入controller");
        return "hello";
    }
}

注意释@Controller而不是@RestContreller

@RestController返回的是json(JSON 是 JS 对象的字符串表示法,它使用文本表示一个 JS 对象的信息,本质是一个字符串。)如果用了@RestController则不要用@Responsebody

还有一种就是通过ModelAndView

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@EnableAutoConfiguration
public class HelloController {

    @RequestMapping("/hello")

    @ResponseBody
    public ModelAndView hello(){
        System.out.println("hello!");
        ModelAndView mode = new ModelAndView();
        mode.setViewName("hello");
        return mode;
    }
}

一般用于携带参数且返回视图,如果要带参数的话,加上mode.addObject()函数

另外需要注意一点,html文件中所有标签都必须要有结束符,idea有时候生成meta标签时会没有结束符,所以要加上

最终输入http://localhost:8080/hello就可以了

猜你喜欢

转载自blog.csdn.net/floraruo/article/details/81052838