- 建立springboot项目
新建springboot项目的时候需要注意,JSP只支持war包。
相关依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--jsp页面使用jstl标签 不引用的话就没法使用js的一些标签-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- 内置tomcat对Jsp支持的依赖,用于编译Jsp -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
新建webapp目录,注意目录的位置和目录的颜色。如果颜色不对:点击这
做完上面这些要确保项目自动生成下面两个类
- 基本环境搭建
登录界面 webapp\WEB-INF\jsp\login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="login" method="post">
用户名:<input type="text" name="username"><br>
密 码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
application.yml配置jsp文件的前缀和后缀
spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
ViewController跳转页面
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
/**
* 此类负责页面跳转
*/
public class ViewController {
/**
* 登录页面
*/
@RequestMapping("/")
public String login(){
return "login";
}
}
登录的实现
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String username;//账号
private String password;
private String realName;//用户名
private String mobile;
}
/**
* 登录认证请求的参数
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AuthenticationRequest {
private String username;
private String password;
}
Service层
public interface AuthenticationService {
/**
* 用户认证
* @param authenticationRequest 用户认证请求,账号和密码
* @return 认证成功的用户信息
*/
User authentication(AuthenticationRequest authenticationRequest) ;
}
@Service
public class AuthenticationServiceImpl implements AuthenticationService {
//初始化两个用户用户用于测试
private Map<String,User> userMap=new HashMap<>();
{
userMap.put("admin",new User(1,"admin","123456","冬寂雪","12345678900"));
userMap.put("root",new User(2,"root","654321","懒鑫人","10987645321"));
}
//根据账号查询用户信息
private User selectUser(String username){
return userMap.get(username);
}
//用户登录认证
@Override
public User authentication(AuthenticationRequest authenticationRequest) {
//判断是否为空
if(authenticationRequest==null||authenticationRequest.getUsername().isEmpty()
||authenticationRequest.getPassword().isEmpty()){
throw new RuntimeException("账号和密码不能为空");
}
//查询登录用户是否存在
User user=selectUser(authenticationRequest.getUsername());
if (user==null){
throw new RuntimeException("还未注册");
}
//检验密码
if (!authenticationRequest.getPassword().equals(user.getPassword())){
throw new RuntimeException("账号或密码错误");
}
//认证通过
return user;
}
}
controller层 关于produces
@RestController
public class LoginController {
@Resource
AuthenticationService authenticationService;
//登录成功后返回文本格式 produces = "text/plain;charset=utf-8"
@PostMapping(value = "/login",produces = "text/plain;charset=utf-8")
public String login(AuthenticationRequest authenticationRequest){
User user=authenticationService.authentication(authenticationRequest);
return user.getUsername()+"登录成功";
}
}
测试:访问登录页面输入 账号和密码分别为 admin 123456
通过session实现权限操作
user类添加权限字段
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String username;//账号
private String password;
private String realName;//用户名
private String mobile;
private Set<String> authorities;//存放用户的权限
}
Service层 :AuthenticationServiceImpl 初始化快添加权限字段的值
//初始化两个用户用户用于测试
private Map<String,User> userMap=new HashMap<>();
{
Set<String> authorities1 = new HashSet<>();
authorities1.add("p1");//p1权限
Set<String> authorities2 = new HashSet<>();
authorities2.add("p2");//p2权限
userMap.put("admin",new User(1,"admin","123456","冬寂雪","12345678900",authorities1));
userMap.put("root",new User(2,"root","654321","懒鑫人","10987645321",authorities2));
}
Controller层
import com.dong.session.pojo.AuthenticationRequest;
import com.dong.session.pojo.User;
import com.dong.session.service.AuthenticationService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
@RestController
public class LoginController {
@Resource
AuthenticationService authenticationService;
@PostMapping(value = "/login", produces = "text/plain;charset=utf-8")
public String login(AuthenticationRequest authenticationRequest, HttpSession session) {
User user = authenticationService.authentication(authenticationRequest);
//登录成功后用session存放用户信息
session.setAttribute("userDetail", user);
return user.getUsername() + "登录成功";
}
@GetMapping(value = "/r/r1", produces = "text/plain;charset=UTF-8")
public String r1(HttpSession session) {
String realName = null;
Object object = session.getAttribute("userDetail");
if (object == null) {
realName = "匿名";
} else {
User user = (User) object;
realName = user.getRealName();
}
return realName + "访问资源r1";
}
@GetMapping(value = "/r/r2", produces = "text/plain;charset=UTF-8")
public String r2(HttpSession session) {
String realName = null;
Object object = session.getAttribute("userDetail");
if (object == null) {
realName = "匿名";
} else {
User user = (User) object;
realName = user.getRealName();
}
return realName + "访问资源r2";
}
@GetMapping(value = "/loginOut",produces = "text/plain;charset=UTF-8")
public String loginOut(HttpSession session) {
//退出时删除session
session.invalidate();
return "退出成功";
}
}
拦截器 interceptor
package com.dong.session.interceptor;
import com.dong.session.pojo.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Component
public class SimpleAuthenticationInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//解决乱码问题
response.setContentType("application/json;charset=utf-8");
//校验每个用户访问的接口,是否在用户拥有的权限接口中
//取出用户的session信息
Object object=request.getSession().getAttribute("userDetail");
if (object==null){
writeContent(response,"请登录");
return false;
}
User user=(User)object;
//判断用户是否拥有的权限去访问接口
String requestUrl=request.getRequestURI();//请求的接口
if(user.getAuthorities().contains("p1")&& requestUrl.contains("/r/r1")){
//p1 && /r/r1 就表示用户拥有p1权限,允许访问/r/r1接口。
//放行
return true;
}
if(user.getAuthorities().contains("p2")&& requestUrl.contains("/r/r2")){
//放行
return true;
}
writeContent(response,"没有权限,拒绝访问!");
return false;
}
//响应信息
private void writeContent(HttpServletResponse response,String msg) throws IOException {
PrintWriter writer = response.getWriter() ;
writer.print(msg);
writer.close();
}
}
config类
package com.dong.session.config;
import com.dong.session.interceptor.SimpleAuthenticationInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
/**
* 接下来我们需要将拦截器添加到SpringBoot的配置中,
* 让SpringBoot项目有这么一个拦截器存在,
* 我们新创建一个WebAppConfig,
* 将拦截器的配置以及拦截路径配置好
*/
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
@Resource
private SimpleAuthenticationInterceptor simpleAuthenticationInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 需要拦截的路径
registry.addInterceptor(simpleAuthenticationInterceptor).addPathPatterns("/r/**");
}
}
测试:
不等录访问:localhost:8080/r/r1 结果显示:请登录
登录:http://localhost:8080/ 输入正确的账户和密码(admin 123456)后点击登录显示:admin登录成功
登录成功后访问:localhost:8080/r/r1 结果显示:冬寂雪访问资源r1
登录成功后访问:localhost:8080/r/r2 结果显示:没有权限,拒绝访问!
退出登录:localhost:8080/loginOut 结果显示:退出成功
再次访问:localhost:8080/r/r1 结果显示:请登录
参考教程:黑马Security
原文:https://www.cnblogs.com/lanxinren/p/14726707.html