本地存储资源上传与访问

This commit is contained in:
wangliwen 2022-04-18 13:59:25 +08:00
parent 5f2bd3aeab
commit e1c935a254
9 changed files with 298 additions and 3 deletions

View File

@ -27,6 +27,7 @@
<activiti.version>5.22.0</activiti.version>
<ureport2.version>2.2.9</ureport2.version>
<IJPay.version>2.7.1</IJPay.version>
<yawei-pso.version>2.0.2</yawei-pso.version>
</properties>
<dependencies>
@ -200,6 +201,12 @@
<artifactId>IJPay-AliPay</artifactId>
<version>${IJPay.version}</version>
</dependency>
<!-- 亚微单点登录 -->
<dependency>
<groupId>com.yawei.oav2</groupId>
<artifactId>yawei-pso</artifactId>
<version>${yawei-pso.version}</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,60 @@
package io.renren.common.controller;
import io.renren.common.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@RestController
public class FileUploadController {
@Value("${resource.path}")
private String uploadPath;
@Value("${resource.root_url}")
private String root_url;
@Value("${server.servlet.context-path}")
private String context_path;
private static Logger logger = LoggerFactory.getLogger(FileUploadController.class);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
@PostMapping("/upload")
public Result<String> upload(@RequestParam("file") MultipartFile uploadFile,
HttpServletRequest request) {
logger.info("上传文件:" + uploadFile.getOriginalFilename());
String format = sdf.format(new Date());
File folder = new File(uploadPath + "upload" + File.separator + format);
logger.info(uploadPath + format);
if (!folder.isDirectory()) {
folder.mkdirs();
}
// 对上传的文件重命名避免文件重名
String oldName = uploadFile.getOriginalFilename();
String newName = UUID.randomUUID().toString()
+ oldName.substring(oldName.lastIndexOf("."), oldName.length());
try {
// 文件保存
uploadFile.transferTo(new File(folder, newName));
// 返回上传文件的访问路径
String filePath = request.getScheme() + "://" + root_url
+ ":" + request.getServerPort() + context_path + "/upload/" + format + newName;
return new Result<String>().ok(filePath);
} catch (IOException e) {
return new Result<String>().error(e.getMessage());
}
}
}

View File

@ -0,0 +1,111 @@
package io.renren.common.interceptor;
import com.yawei.pso.PSORequest;
import com.yawei.pso.SSOResponse;
import com.yawei.pso.TicketManager;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map.Entry;
/**
* 亚微 sso拦截
*/
@Component
public class IdentityInterceptor implements HandlerInterceptor {
private static Logger logger = LoggerFactory.getLogger(IdentityInterceptor.class);
public final static String SEESION_USER = "seesion_user";
@Autowired
private YaweiSSOProperties yaweiSSOProperties;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.info("==============执行顺序: 1、preHandle================");
// 获取当前请求的url
String requestUri = request.getRequestURI();
Validator validator = Validator.getInstance();
String strResponse = request.getParameter(yaweiSSOProperties.getSsoKey());
if (StringUtils.isEmpty(strResponse)) {
TicketManager tm = new TicketManager();
if (!tm.LoadTicket(request)) {
PSORequest psoRequest = new PSORequest(request);
String requeststr = psoRequest.CreateHash();
String keeperUrl = yaweiSSOProperties.getKeeperUrl();
keeperUrl = keeperUrl + "?" + yaweiSSOProperties.getSsoKey() + "="
+ URLEncoder.encode(requeststr, "UTF-8");
response.sendRedirect(keeperUrl);
return false;
}
} else {
// 如果服务器端通过认证后会返回后执行改操作然后写入cookie
SSOResponse ssoResp = new SSOResponse(strResponse);
TicketManager tm = ssoResp.CreatePSOTicket();
if (tm == null) {
PSORequest psoRequest = new PSORequest(request);
String requeststr = psoRequest.CreateHash();
String keeperUrl = yaweiSSOProperties.getKeeperUrl();
keeperUrl = keeperUrl + "?" + yaweiSSOProperties.getSsoKey() + "="
+ URLEncoder.encode(requeststr, "UTF-8");
response.sendRedirect(keeperUrl);
} else {
String domainName = yaweiSSOProperties.getDomain();
tm.SaveTicket(response, domainName);
Iterator<Entry<String, String[]>> iterator = request
.getParameterMap().entrySet().iterator();
StringBuffer param = new StringBuffer();
int i = 0;
while (iterator.hasNext()) {
Entry<String, String[]> entry = (Entry<String, String[]>) iterator
.next();
if (entry.getKey().equals(yaweiSSOProperties.getSsoKey()))
continue;
else {
i++;
if (i == 1)
param.append("?").append(entry.getKey())
.append("=");
else
param.append("&").append(entry.getKey())
.append("=");
if (entry.getValue() instanceof String[]) {
param.append(((String[]) entry.getValue())[0]);
} else {
param.append(entry.getValue());
}
}
}
response.sendRedirect(requestUri + param.toString());
return false;
}
}
validator.SetUserTicket(request);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
logger.info("==============执行顺序: 2、postHandle================");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
logger.info("==============执行顺序: 3、afterCompletion================");
}
}

View File

@ -0,0 +1,83 @@
package io.renren.common.interceptor;
import com.yawei.pso.TicketManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* 验证器
*/
public class Validator {
private static Logger logger = LoggerFactory.getLogger(Validator.class);
private static ThreadLocal<Validator> validatorHolder = new ThreadLocal<Validator>() {
protected Validator initialValue() {
return new Validator();
}
};
// 当前请求的session
private HttpSession session = null;
// 当前的请求
private HttpServletRequest request = null;
private Validator() {
}
public static Validator getInstance() {
return validatorHolder.get();
}
/**
* 执行初始化
*
* @param httpRequest
*/
public void init(HttpServletRequest httpRequest) {
this.request = httpRequest;
this.session = request.getSession();
}
/**
* 将凭证身份加入到session
*
* @param httpRequest
*/
public void SetUserTicket(HttpServletRequest httpRequest) {
try {
if (httpRequest.getSession()
.getAttribute(IdentityInterceptor.SEESION_USER) == null) {
TicketManager ticket = new TicketManager();
if (ticket.LoadTicket(httpRequest)) {
// 登录用户姓名
String userName = ticket.getUserName();
// 登录用户账号
String userAccount = ticket.getUserID();
// 登录用户标识
String userGuid = ticket.getADGUID();
logger.info("===userName===" + userName);
logger.info("===userAccount===" + userAccount);
logger.info("===userGuid===" + userGuid);
}
} else {
}
} catch (Exception ex) {
logger.error("", ex);
}
}
/**
* 清除session
*/
public void cancel() {
this.session = null;
}
}

View File

@ -0,0 +1,18 @@
package io.renren.common.interceptor;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Data
@Component
@PropertySource("classpath:/yaweisso.properties")
@ConfigurationProperties(prefix = "sso")
public class YaweiSSOProperties {
private String domain;
private String ssoKey;
private String keeperUrl;
}

View File

@ -19,13 +19,12 @@ import java.util.Map;
/**
* Shiro的配置文件
*
*/
@Configuration
public class ShiroConfig {
@Bean
public DefaultWebSessionManager sessionManager(){
public DefaultWebSessionManager sessionManager() {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setSessionValidationSchedulerEnabled(false);
sessionManager.setSessionIdUrlRewritingEnabled(false);
@ -72,6 +71,13 @@ public class ShiroConfig {
filterMap.put("/front/**", "anon");
filterMap.put("/applyRecord/**", "anon");
filterMap.put("/bsabilityrecord/**", "anon");
/**
* 资源上传
*/
filterMap.put("/upload", "anon");
filterMap.put("/upload/**", "anon");
filterMap.put("/**", "oauth2");
shiroFilter.setFilterChainDefinitionMap(filterMap);

View File

@ -37,6 +37,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AliPayInterceptor()).addPathPatterns("/pay/alipay/**");
// registry.addInterceptor(new IdentityInterceptor());
}
@Override

View File

@ -1,3 +1,7 @@
#上传的静态资源配置
resource:
root_url: 127.0.0.1
path: E:\liwen\
# Tomcat
server:
tomcat:
@ -38,12 +42,14 @@ spring:
min-idle: 5 # 连接池中的最小空闲连接
activiti:
check-process-definitions: false
resources:
static-locations: classpath:/static,classpath:/public,file:${resource.path}
fdfs:
so-timeout: 600000
connect-timeout: 6000
tracker-list: #TrackerList参数,支持多个
tracker-list: #TrackerList参数,支持多个
- 192.168.10.10:22122
# 是否开启redis缓存 true开启 false关闭

View File

@ -0,0 +1,3 @@
sso.domain=yw.com.cn
sso.ssoKey=SSOToken
sso.keeperUrl=http://127.0.0.1:9090/renren-admin/sys/user/123