放置图片资源:
将图片资源放在src/main/resources/static目录下。Spring Boot会自动映射这个目录下的资源到/路径。
访问图片资源:
你可以通过访问http://localhost:8080/your-image-name.jpg来获取图片资源,其中your-image-name.jpg是你的图片文件名。
自定义静态资源路径:
拦截器可以用于记录请求信息或进行权限验证。以下是一个简单的拦截器示例:
package com.dxw.project.ljq;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
/**
* 配置需要拦截和放行的bean HttpInterceptorConfig
* @Author dxw
* @Create 2023/1/3 15:32
* Version 1.0
*/
@Configuration
public class HttpInterceptorConfig implements WebMvcConfigurer {
@Resource
private HttpSampleInterceptor httpSampleInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(httpSampleInterceptor)
.addPathPatterns("/**")//需要拦截的路径
.excludePathPatterns("/file/**");//需要放行的路径
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/file/**").addResourceLocations("file:" + System.getProperty("user.dir") + "/");
}
}
如果需要对请求进行更细粒度的控制,可以使用过滤器。以下是一个示例过滤器:
package com.dxw.project.ljq;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* # 配置拦截器 HttpSampleInterceptor
* @Author dxw
* @Create 2023/1/3 15:25
* Version 1.0
*/
@Component
@Slf4j
public class HttpSampleInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
String ip = request.getRemoteAddr();
System.out.println("ip: " + ip + " 过了拦截器-时间-: " + DateUtil.now() + " url: " + requestURI);
if (ip.equals("0:0:0:0:0:0:0:1") || ip.equals("127.0.0.1")) return true;
return HandlerInterceptor.super.preHandle(request, response, handler);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
package com.dxw.project.ljq;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* Classname: ReplaceStreamFilter
* Package: com.example.dxw.utils
* Description:
*
* @Author dxw
* @Create 2023/6/10 23:09
* Version 1.0
*/
@Order(5)
@Component
@Slf4j
@WebFilter(filterName = "ReplaceStreamFilter", urlPatterns = "/*")
public class ReplaceStreamFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("项目启动初始化");
Filter.super.init(filterConfig);
}
@SneakyThrows
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request1 = (HttpServletRequest) request;
String requestUri2 = request1.getRequestURI();
String ip = request1.getRemoteAddr();
System.out.println();
log.info("IP:{}",ip);
if (requestUri2.contains("upload")) {
chain.doFilter(request, response);
return;
}
if (requestUri2.contains("goStraight")) {
chain.doFilter(request1, response);
return;
}
if (request1.getMethod().equals("GET")) {
Map<String, String[]> parameterMap = request1.getParameterMap();
if (MapUtil.isNotEmpty(parameterMap)) {
String parameters =JSONUtil.toJsonStr(parameterMap);
log.info("URL[{}],参数类型[param]",requestUri2);
log.info("GET 参数:{}",parameters);
} else {
log.info("URL[{}],无参数", requestUri2);
}
System.out.println();
chain.doFilter(request1, response);
return;
}
// if (!requestUri2.contains("encrypt")) {
// chain.doFilter(request, response);
// return;
// }
RequestWrapper requestWrapper = new RequestWrapper(request1);
StringBuffer buffer = new StringBuffer();
String line = null;
BufferedReader reader = null;
reader = requestWrapper.getReader();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
log.info("URL[{}],参数类型[json]",requestUri2);
log.info("POST 参数:{}", ellipsize(String.valueOf(buffer), 200) );
System.out.println();
requestWrapper.setBody(buffer.toString().getBytes(StandardCharsets.UTF_8));
chain.doFilter(requestWrapper, response);
}
public static String ellipsize(String str, int maxLength) {
if (str.length() <= maxLength) {
return str;
} else {
return str.substring(0, maxLength) + "...";
}
}
}
package com.dxw.project.ljq;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;
public class RequestWrapper extends HttpServletRequestWrapper {
/**
* 存储body数据
*/
private byte[] body;
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
// 将body数据存储起来
String bodyStr = getBodyString(request);
body = bodyStr.getBytes(Charset.defaultCharset());
}
/**
* 获取请求Body
*
* @param request request
* @return String
*/
public String getBodyString(final ServletRequest request) {
try {
return inputStream2String(request.getInputStream());
} catch (IOException e) {
// log.error("", e);
throw new RuntimeException(e);
}
}
// 赋值给body字段
public void setBody(byte[] body) {
this.body = body;
}
/**
* 获取请求Body
*
* @return String
*/
public String getBodyString() {
final InputStream inputStream = new ByteArrayInputStream(body);
return inputStream2String(inputStream);
}
/**
* 将inputStream里的数据读取出来并转换成字符串
*
* @param inputStream inputStream
* @return String
*/
private String inputStream2String(InputStream inputStream) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// log.error("", e);
throw new RuntimeException(e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// log.error("", e);
}
}
}
return sb.toString();
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream inputStream = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return inputStream.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
}
}