洞察探索如何利用兼容微信生态的小程序容器,实现跨平台开发,助力金融和车联网行业的数字化转型。
458
2023-06-19
SpringBoot-Filter的使用方法详解
前言:
最新Servlet 3.0-的使用
1.pom.xml添加需要使用的依赖
</plugin>
1.8
2.添加Filter-
package top.ytheng.demo.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//Servlet3.0特性
//urlPatterns:拦截的url地址
//filterName:-名称
@WebFilter(urlPatterns="/api/*", filterName="loginFilter")
public class LoginFilter implements Filter{
/*
* 容器加载完成调用
* */
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
System.out.println("filter init...");
}
/*
* 请求被拦截的时候调用
* */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("doFilter...");
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
String username = req.getParameter("username");
if(username.equals("theng")) {
chain.doFilter(request, response);
} else {
//重定向
resp.sendRedirect("/filter.html");
return;
}
}
/*
http://* 容器被销毁的时候调用
* */
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("filter destroy...");
}
}
3.添加测试控制器
package top.ytheng.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/filter")
public class FilterController {
@RequestMapping("/test")
public Object testFilter() {
Map
map.put("name", "theng");
map.put("pwd", "123456");
return map;
}
}
4.添加启动类
package top.ytheng.demo;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication //等于下面3个
//@SpringBootConfiguration
//@EnableAutoConfiguration
//@ComponentScan
//-用到
@ServletComponentScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
5.添加拦截后调整的页面filter.html
6.右键项目Run As启动项目
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~