虽然目前主流开发方式为前后端分离,但是学到了springboot就想做出页面跳转,所以下面就介绍一种springboot的页面跳转方法-重定向
1.从头开始创建springboot项目(方式各种各样,这里只介绍一种)
在已经打开的idea项目目录下创建springboot项目,按ctrl+shift+alt+s键,弹出如下框
点击Modules,再点击左上角的加号
再点击new module
进入创建项目页面,编辑项目,server URL处推荐使用阿里云地址:start.aliyun.com,下载速度快
点击next进入下一个界面,添加相关技术
最后点击apply,再点击ok,这些操作就已经创建好一个springboot项目
2.实现整合thymeleaf登录跳转
新创建好的springboot项目的目录结构如下
2.1整合thymeleaf
需要在pom.xml文件下添加thymeleaf的坐标依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
还要在application.properties配置文件中添加如下配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.thymeleaf.suffix=.html
spring.thymeleaf.servlet.content-type=text/html
推荐使用yml配置文件,把application.properties删除后再自己再resource目录下创建application.yml配置文件,yml文件添加配置如下
spring:
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
encoding: UTF-8
content-type: text/html
mode: HTML5
check-template-location: true
查看resource目录下是否有templates子目录,没有则自己手动添加,在该目录下存放需要访问的静态资源
添加控制层接口
@Controller
@CrossOrigin//处理跨域问题
@RequestMapping( "/user")
public class UserController {
@Autowired
public UserDao userDao;
// 登录
@PostMapping("/login")
public String selectUser(@RequestParam("username") String username,
@RequestParam("password") String password,
Model md
){
// 结合mybatisplus根据用户名和密码进行条件查询,查询成功则登录成功,查询失败则登录失败
LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<User>();
qw.eq(User::getUsername, username).eq(User::getUserpassword,password);
User user = userDao.selectOne(qw);
// 查询成功重定向到登录成功后进入的html页面
if(user!=null){
return "redirect:/pages/book.html";
}else{
// 查询失败,返回提示信息给登录页面
md.addAttribute("msg","用户名或者密码错误!");
return "login";
}
}
}
html界面中的登录界表单(新手,写的有点繁杂)
<form action="/user/login" method="post">
<ul>
<span class="l">LOGIN IN</span>
<li class="w">
Username:<input type="text" id="username" name="username"
style="background-color:rgba(255,255,255,0.2);
border-radius: 3px;"></br>
Password: <input type="password" id="password" name="password"
style="background-color:rgba(255,255,255,0.2);
border-radius: 3px;"></br>
<p id="ts"style="color: red;font-size: small;text-align: center"
th:text="${msg}"></p>
</li>
<li class="q">
Rememberme: <input type="checkbox" id="remember"
style="position: relative;top:10px;color: white;
"></br>
<input type="submit" value="Login up" id="login"
style="background-color: rgba(38,127,232,0.6);
border-radius: 3px;width:70px;color:white;">
<input type="submit" value="logon" id="logon"
style="background-color: rgba(38,127,232,0.6);
border-radius: 3px;width:70px;color:white;">
<a href="register.html" style="font-size:smaller">没有账号?点击注册</a>
</li>
</ul>
</form>
准备展示登录跳转功能,先展示resource目录下的结构
3.演示登录跳转(如下演示省去了很多业务层代码)
运行springboot启动类,在浏览器中输入网站,进入网站在输入用户名与密码,再点击logon
若密码正确进入跳转后的book.html页面
若用户名与密码错误则返回报错信息到登录界面
完整代码已托管至Gitee,gitee地址:https://gitee.com/mutigmss/spring-boot-thymeleaf
欢迎在评论区交流使用体验和优化建议!
超详细的springBoot前后端完整案例:
以上,喜欢请点个赞吧~