功能需求:
springboot登陆页面进行登陆验证,并完成登陆跳转。错误的账户提示用户名密码错误,正确的账户跳转到index页面。
同时加上登陆拦截器,对于错误的账户不允许直接访问index页面。
一 登陆验证
实现输入正确的用户名密码直接进入index页面,输入错误提示用户名密码错误。
1. 要实现登录,我们需要先编写一个登录的controller类:
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
import java.util.Map;
@Controller
public class LoginController {
@RequestMapping("login")
public String tologin()
{
return "login";
}
@PostMapping(value="/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password, Map<String,Object> map,
HttpSession session){
//验证用户名和密码,输入正确,跳转到index
if(!StringUtils.isEmpty(username)&&"lss".equals(password)){
session.setAttribute("userName",username);
System.out.println("username===" + username);
return "redirect:/index";
}
else //输入错误,清空session,提示用户名密码错误
{
session.invalidate();
map.put("msg","用户名密码错误");
return "login";
}
}
@RequestMapping("index")
public String goIndex(Map<String,Object> map)
{
map.put("name","lishanshan");
map.put("age",29);
map.put("sex","女");
return "index";
}
}
说明:
(1) 跳转页面时使用 return ”redirect:/ index“,而不是 return ”index“ .
return ”redirect:/ index“,会直接调用controller, return ”index“ 只会访问目录下的文件
2. 登陆页面 login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>首页</title>
</head>
<body>
<form th:action="@{/login}" method="post">
<!-- 取值替换原来默认的值-->
<h1>Plea