springboot加入拦截器interceptor


实现目标:只有当用户登陆成功才能访问其他路径

                   1.访问路径时需要拦截所有请求uri

                   2.过滤部分uri (登录页面的uri和登录验证的uri)并判断session是否有用户信息(有用户信息,则可以访问路径,若没有 ,则重定向到登录页面)

                   3.登录验证成功后,session中添加用户信息

 

springboot中Resources的application.yml

spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/world?characterEncoding=utf8
driverClassName: com.mysql.jdbc.Driver
username: root
password: root
filters: stat,wall,log4j
maxActive: 20
initiaSize: 1
maxWait: 60000
poolPrepareStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
connectionProperties: druid.stat.mergeSql=true;druid.stat.showSqlMillis=5000
minldle: 1
timeBetweenEvictionRunsMillis: 60000
minevictableidleTimeMillis: 30000
validationQuery: select 1 from dual
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
jpa:
database: MySQL
show-sql: true
hibernate:
naming-strategy : org.hibernate.cfg.ImprovedNamingStrategy
mvc:
view:
prefix: /WEB-INF/jso
suffix: .jsp

首先我们需要将SessionInterceptor拦截器添加到SpringBoot的配置中,让SpringBoot项目有这么一个拦截器存在,我们新创建一个SessionConfiguration,将拦截器的配置以及拦截路径配置好

@Configuration
public class SessionConfiguraction implements WebMvcConfigurer {
//配置拦截器
public void addInterceptors(InterceptorRegistry registry){
//registry.addInterceptor此方法添加拦截器
registry.addInterceptor(new SessionInterceptor()).addPathPatterns("/**");
}
}

接着 我们需要创建sessionInterceptor类,实现HandlerInterceptor接口 并重写其父类方法,并且添加如果没有session状态直接跳转到/user/login_view地址也就是我们对应的login.jsp页面

public class SessionInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception{
System.out.println(request.getRequestURI());
if (request.getRequestURI().equals("/city/login")||request.getRequestURI().equals("/user/login_view")){
return true;
}
Object obj = request.getSession().getAttribute("session_user");
if (obj == null){
response.sendRedirect("/user/login_view");
return false;
}
return true;
}
}

编写Controller 和model类及其jpa接口

IndexController      /user/login_view 跳转登录页面    /user/index跳转访问路径

@Controller
@RequestMapping("/user")
public class IndexController {

@RequestMapping(method = RequestMethod.GET,value = "/login_view")
public String login_view(){
return "login";
}

@RequestMapping(method = RequestMethod.GET,value = "/index")
public String index(){
return "index";
}
}

CityController    /city/login 登录验证controller  登陆成功需把用户存放于session中

@RestController
@RequestMapping("/city")
public class CityController {
@Autowired
private CityJPA cityJPA;
@RequestMapping(value = "/login", method = RequestMethod.GET)
private String login(CityEntity city, HttpServletRequest request) {
boolean flag = true ;
String result = "登录成功";
Optional<CityEntity> cityEntity = cityJPA.findOne(new Specification<CityEntity>() {
@Override
public Predicate toPredicate(Root<CityEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
criteriaQuery.where(criteriaBuilder.equal(root.get("id"),city.getId()));
return null;
}
});
if (cityEntity == null){
flag = false;
result ="用户不存在,登录失败";
}else if (!cityEntity.get().getName().equals(city.getName())){
flag = false;
result ="用户密码不符合,登陆失败";
}
if (flag){
request.getSession().setAttribute("session_user",cityEntity);
}
return result;
}
}

city类

@Entity
@Table(name = "city")
public class CityEntity implements Serializable{
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "district")
private String district;
@Column(name = "population")
private String population;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getDistrict() {
return district;
}

public void setDistrict(String district) {
this.district = district;
}

public String getPopulation() {
return population;
}

public void setPopulation(String population) {
this.population = population;
}
}

jpa接口



public interface CityJPA extends JpaRepository<CityEntity,Long>,
JpaSpecificationExecutor<CityEntity> ,Serializable {
}

 

登录页面 login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form method="get" action="/city/login">
城市id:<input type="text" name="id"/><br/>
城市名:<input type="text" name="name"/>
<input type="submit" value="提交">
</form>
</body>
</html>

登录访问页面 index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
您已经成功访问到主页面!
</body>
</html>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM