springboot使用@RestController 进行页面跳转

@ResponseBody注解

@ResponseBody 注解可被应用于方法上,标志该方法的返回值应该被直接写回到 HTTP 响应体中去(而不会被被放置到 Model中 或 被解释为一个视图名)

springboot可以通过 controller 跳转:注入的时候一定要是@Controller,而不要是@RestController,因为它是 rest 接口(json格式)是解析不到 html的。

1.配置文件pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

<!--保证配置文件能被扫描到-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.html</include>
                </includes>
            </resource>
        </resources>

2.在配置文件application.properties中关闭Thymeleaf的页面缓存:

# 在构建URL时预先查看名称的前缀,写/templates/也可以
spring.thymeleaf.prefix=classpath:/templates/
#1.把视图页面放到文件夹中
spring.web.resources.static-locations=classpath:/templates
#关闭缓存 # 关闭thymeleaf缓存 开发时使用 否则没有实时画面
spring.thymeleaf.cache=false
# 构建URL时附加查看名称的后缀.
spring.thymeleaf.suffix=.html

3.controller:使用ModelAndView进行页面跳转

 @PostMapping(value = "/login")
    public ModelAndView login(User user){
        Result result = new Result();
        result.setSuccess(false);
        result.setDetail(null);

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //查询条件
        wrapper.eq("username", user.getUsername()).eq("password",user.getPassword());
        System.out.println(user);
        // 查询的数据超过一条时,会抛出异常
        User user1 = userService.getOne(wrapper);
        if (user1 != null) {
//            如果用户已经存在
            result.setMsg("登录成功");
            result.setSuccess(true);
            result.setDetail(user1);
        } else {
            result.setMsg("用户或密码错误");
        }
        ModelAndView mv = new ModelAndView("index");
        return mv;

    }
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值