當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring Security——根据请求Header[Accept]不同返回不同类型资源解决方案
生活随笔
收集整理的這篇文章主要介紹了
Spring Security——根据请求Header[Accept]不同返回不同类型资源解决方案
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
解決方案
/*** @Author ShenTuZhiGang* @Version 1.0.0* @Date 2020-03-21 13:10*/@Component public class CustomSavedRequestAwareAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {@AutowiredILogService iLogService;@Overridepublic void onAuthenticationSuccess(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,Authentication authentication)throws ServletException, IOException {RequestCache requestCache = new HttpSessionRequestCache();SavedRequest savedRequest = requestCache.getRequest(httpServletRequest,httpServletResponse);String ip = IPUtil.getIPAddress(httpServletRequest);AuthenticationUser user = (AuthenticationUser) authentication.getPrincipal();logSuccess(ip,user);String accept = httpServletRequest.getHeader("Accept");MediaType acceptMediaType;if(StringUtils.isEmpty(accept)){acceptMediaType = MediaType.APPLICATION_JSON;}else{String[] str = accept.split(",");if(str.length>0){try {acceptMediaType = MediaType.valueOf(str[0]);}catch (InvalidMediaTypeException ex){acceptMediaType = MediaType.APPLICATION_JSON;}}else{acceptMediaType = MediaType.APPLICATION_JSON;}}if(MediaType.TEXT_HTML.compareTo(acceptMediaType)==0){if(savedRequest != null){//url = savedRequest.getRedirectUrl();super.onAuthenticationSuccess(httpServletRequest, httpServletResponse, authentication);}else{getRedirectStrategy().sendRedirect(httpServletRequest,httpServletResponse,"/");}}else if(MediaType.APPLICATION_JSON.compareTo(acceptMediaType)==0){ResponseBean ok = ResponseBean.ok("登錄成功!", user);HttpServletUtil.writeObjectToResponse(httpServletResponse,ok);}else if(MediaType.ALL.compareTo(acceptMediaType)==0){ResponseBean ok = ResponseBean.ok("登錄成功!", user);HttpServletUtil.writeObjectToResponse(httpServletResponse,ok);}}private void logSuccess(String ip, AuthenticationUser user){//登錄日志Log loginLog = new Log();loginLog.setOperation("登錄");loginLog.setType("login");loginLog.setIp(ip);loginLog.setOperator(user.getUsername());loginLog.setTime(LocalDateTime.now());loginLog.setStatus("success");loginLog.setRemark("登錄成功!");iLogService.save(loginLog);} }參考文章
Spring Boot 同一URL返回不同資源
HTTP報文頭Accept和Content-Type總結
總結
以上是生活随笔為你收集整理的Spring Security——根据请求Header[Accept]不同返回不同类型资源解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《操作系统》实验报告——进程调度的模拟
- 下一篇: LeetCode176 第二高的薪水