登录功能也就是当我们点击登录按钮的时候,会进入一个页面,这里进入dashboard.html
页面
因此我们首先在index.html
中的表单编写一个提交地址/user/login
,并给名称和密码输入框添加name
属性为了后面的传参
<body class="text-center">
<form class="form-signin" th:action="@{/user/login}">
......
<input type="text" name="username" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
<input type="password" name="password" class="form-control" th:placeholder="#{login.password}" required="">
......
body>
然后需要编写相对应的controller·,我们在com.kuang.controller
包下创建LoginController.java
类,用来处理登录请求
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;
@Controller
public class LoginController {
@RequestMapping("/user/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Model model){
//具体的业务,先简单设置为用户名不为空且密码为123456就可以登录成功
if(!StringUtils.isEmpty(username) && "123456".equals(password)){
return "dashboard";//跳转到dashboard页面
}else{
//告诉用户登录失败了
model.addAttribute("msg","用户名或者密码错误");
return "index";//跳转到首页
}
}
}
启动主程序,访问http://localhost:8080/kuang/
,输入任意用户名和密码123456,即可实现登录功能,并跳转到dashboard.html
页面
登录成功跳转到dashboard.html
页面时,浏览器url为http://localhost:8080/kuang/user/login?username=admin&password=123456
现在如果我们输入的用户名和密码不符合要求,只会重新跳转到index.html
,但我们并没有在index.html
中显示提示的消息
修改index.html
,在请登录下面加一个消息提示的标签,注意Thymeleaf模板引擎的语法
......
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign inh1>
<p style="color:#ff0000" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}">p>
......
这时,如果我们输入的用户名和密码不符合要求的话,会重新跳转index.html
,并给出错误提示
到此我们的登录功能实现完毕,但是有一个很大的问题,浏览器的url暴露了用户的用户名和密码。这在实际开发中是重大的漏洞,泄露了用户信息。
因此我们需要编写一个映射,我们在config
包下的自定义的配置类MyMvcConfig.java
中,设置跳转到dashboard.html
时映射到main.html
@Override
public void addViewControllers(ViewControllerRegistry registry) {
......
registry.addViewController("/main.html").setViewName("dashboard");
}
然后我们在登录成功时,重定向到main.html
即可,也就是修改LoginController.java
,在登录成功时进行重定向
if(!StringUtils.isEmpty(username) && "123456".equals(password)){
return "redirect:/main.html";
}
现在,我们成功登录之后,地址栏显示的url就会是http://localhost:8080/kuang/main.html
,而不会显示出我们提交的请求了
但是还有一个问题!
如果我们现在直接访问http://localhost:8080/kuang/main.html
,也是可以进入登录成功后的后台页面,这该如何解决呢?答案是设置登录拦截器