本篇内容主要讲解“springboot怎么实现返回视图”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“springboot怎么实现返回视图”吧!
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
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就可以了
1.使用ModelAndView
在controller中
@RequestMapping("toTest")
public ModelAndView toTest(){
ModelAndView mv = new ModelAndView();
//视图名
mv.setViewName("login");
//想传的数据
mv.addObject("o1","数据1");
return mv;
}
2.使用webMVC配置
创建配置类
package com.ch.exercise.config.webMvc;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* MVC配置
* @author CH
* @date 2021-08-19 11:45
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry
//接收的请求
.addViewController("/toLogin")
//跳转的页面名
.setViewName("login");
}
}
快速上手
1.在pom.xml添加依赖
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.创建页面login.html
3.配置thymeleaf
在application.yml中添加上
spring:
thymeleaf:
#页面存放位置
prefix: classpath:/templates/
#是否缓存 这里是否
cache: false
suffix: .html
mode: LEGACYHTML5
template-resolver-order: 0
再进行视图配置就可以访问到了
到此,相信大家对“springboot怎么实现返回视图”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。