SpringBoot項(xiàng)目中改變web服務(wù)的路徑的兩種方案
背景:
之前是spring項(xiàng)目,增加了servlet,對(duì)應(yīng)非訪問路徑如/defA/inner-invoke/operator。
現(xiàn)在改造成了springboot項(xiàng)目后,默認(rèn)路徑是/oprator
希望不改動(dòng)原有controller代碼,讓路徑能夠增加前綴讓外面能正常調(diào)用。
原web.xml配置:
<!-- Web Servlet Configuration --> <servlet> <servlet-name>stariboss</servlet-name> <servlet-class>com.osgi.web.servlet.SpringProxyServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>defA</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>defA</servlet-name> <url-pattern>/inner-invoke/*</url-pattern> </servlet-mapping> <!-- End Web Servlet Configuration -->
方案一、統(tǒng)一增加前綴并增加攔截
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebIntfConfig implements WebMvcConfigurer { @Autowired private SessionManagerInterceptor sessionManagerInterceptor; @Autowired private LoginCheckInterceptor loginCheckInterceptor; @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.addPathPrefix("/defA/inner-invoke", c -> c.isAnnotationPresent(Controller.class) || c.isAnnotationPresent(RestController.class)); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(sessionManagerInterceptor) .addPathPatterns("/defA/inner-invoke/**"); registry.addInterceptor(loginCheckInterceptor) .addPathPatterns("/defA/inner-invoke/**"); } }
方案二:增加攔截器,然后服務(wù)器內(nèi)部增加請(qǐng)求轉(zhuǎn)發(fā)
import org.springframework.stereotype.Component; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class MvcRequestInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 獲取原始請(qǐng)求路徑 String originalPath = request.getRequestURI(); // 檢查請(qǐng)求路徑并決定是否需要重定向 if (originalPath.startsWith("/defA/inner-invoke/")) { // 將請(qǐng)求重定向到新的路徑 String newPath = transformUrl(originalPath); // 獲取 RequestDispatcher RequestDispatcher dispatcher = request.getRequestDispatcher(newPath); // 在服務(wù)器端內(nèi)部轉(zhuǎn)發(fā)請(qǐng)求 dispatcher.forward(request, response); // 返回 false 表示請(qǐng)求已被處理,不再繼續(xù) return false; } // 如果不需要重定向,則繼續(xù)處理請(qǐng)求 return true; } private String transformUrl(String currentUrl) { // 這里實(shí)現(xiàn)URL轉(zhuǎn)換邏輯 return currentUrl.replace("/defA/inner-invoke/", "/"); } }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class IntfInterceptorConfig implements WebMvcConfigurer { @Autowired private MvcRequestInterceptor mvcRequestInterceptor; @Autowired private SessionManagerInterceptor sessionManagerInterceptor; @Autowired private LoginCheckInterceptor loginCheckInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(mvcRequestInterceptor).addPathPatterns("/defA/inner-invoke/**"); registry.addInterceptor(sessionManagerInterceptor).addPathPatterns("/**"); registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**"); } }
增加其他幾個(gè)攔截器相關(guān)代碼
@Component public class SessionManagerInterceptor extends HandlerInterceptorAdapter { private final Log logger = LogFactory.getLog(SessionManagerInterceptor.class); public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { try { preReadRemoteInvocation(request); return true; } finally { preWriteRemoteInvocationResult(response,handler); } } private void preReadRemoteInvocation(HttpServletRequest request) { String sessionId = request.getHeader("sessionId"); ApplicationSession appSession =null; if(sessionId!=null && sessionId.length()>0){ appSession = getCache().getSession(sessionId); if(appSession == null){ if (logger.isWarnEnabled()) { logger.warn("not find session: " + sessionId); } }else{ if (logger.isDebugEnabled()) { logger.debug("getSession: " + sessionId); } } } if(appSession==null){ appSession = ApplicationSession.create(); if (logger.isDebugEnabled()) { logger.debug("create a new Session: " + appSession.getId()); } } ApplicationSessionHolder.put(appSession); } private void preWriteRemoteInvocationResult(HttpServletResponse response,Object handler) { ApplicationSession appSession = ApplicationSessionHolder.getApplicationSession(); if (appSession != null) { if (ApplicationSessionHolder.isClear() && !"login".equals(((HandlerMethod)handler).getMethod().getName())) { if (logger.isInfoEnabled()) { logger.info("remove cache Session : " + appSession.getId()); } getCache().clearSession(appSession.getId()); } else { appSession.updateLastAccessedTime(); response.setHeader("sessionId", appSession.getId()); getCache().putSession(appSession); } // ApplicationSessionHolder.remove(); } } public ISessionCache getCache() { if (BeanFactoryHolder.getContext().containsBean("proxySessionCache")) { return (ISessionCache) BeanFactoryHolder.getContext().getBean("proxySessionCache"); } return (ISessionCache) BeanFactoryHolder.getContext().getBean("sessionCache"); } }
package com.star.sms.webconfig; import com.star.sms.business.core.ApplicationSessionHolder; import com.star.sms.business.core.BeanFactoryHolder; import com.star.sms.exceptions.BossInnerServiceInvokeException; import com.star.sms.model.core.ApplicationSession; import com.star.sms.remote.session.ISessionCache; import org.apache.commons.lang.ArrayUtils; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class LoginCheckInterceptor extends HandlerInterceptorAdapter { private String[] methods = { "login", "logout", "unlock", "getVersion","getSystemParamInt", "getSession","getSupplyOperatorRecordSwitch" ,"agentLogin"}; public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws BossInnerServiceInvokeException { if (!(handler instanceof HandlerMethod)) { return true; } if (!ArrayUtils.contains(methods, ((HandlerMethod)handler).getMethod().getName()) && !isLogin()) { String sessionId = request.getHeader("sessionId"); if (StringUtils.hasText(sessionId)) { ApplicationSession session = getCache().getSession(sessionId); if (session == null || session.getAttribute("operator") == null) { throw BossInnerServiceInvokeException.error("not.login"); }else{ session.updateLastAccessedTime(); getCache().putSession(session); ApplicationSessionHolder.put(session); } } else { throw BossInnerServiceInvokeException.error("not.login"); } } return true; } public static boolean isLogin() { ApplicationSession session = ApplicationSessionHolder.getApplicationSession(); if (session == null) { return false; } Object o = session.getAttribute("operator"); return o != null; } public ISessionCache getCache() { if (BeanFactoryHolder.getContext().containsBean("proxySessionCache")) { return (ISessionCache) BeanFactoryHolder.getContext().getBean("proxySessionCache"); } return (ISessionCache) BeanFactoryHolder.getContext().getBean("sessionCache"); } }
以上就是SpringBoot項(xiàng)目中改變web服務(wù)的路徑的兩種方案的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot改變web服務(wù)路徑的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java實(shí)戰(zhàn)之實(shí)現(xiàn)OA辦公管理系統(tǒng)
這篇文章主要介紹了如何通過Java實(shí)現(xiàn)OA辦公管理系統(tǒng),文章采用到了JSP、JQuery、Ajax等技術(shù),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-02-02玩轉(zhuǎn)SpringBoot2快速整合攔截器的方法
這篇文章主要介紹了玩轉(zhuǎn)SpringBoot2快速整合攔截器的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09Java overload和override的區(qū)別分析
方法的重寫(Overriding)和重載(Overloading)是Java多態(tài)性的不同表現(xiàn),想要了解更多請(qǐng)參考本文2012-11-11Spring接口版本控制方案及RequestMappingHandlerMapping接口介紹(最新推薦)
RequestMappingHandlerMapping接口是Spring MVC中的一個(gè)核心組件,負(fù)責(zé)處理請(qǐng)求映射和處理器的匹配這篇文章主要介紹了Spring接口版本控制方案及RequestMappingHandlerMapping接口介紹,需要的朋友可以參考下2024-07-07Spring整合WebSocket應(yīng)用示例(上)
以下教程是小編在參與開發(fā)公司的一個(gè)crm系統(tǒng),整理些相關(guān)資料,在該系統(tǒng)中有很多消息推送功能,在其中用到了websocket技術(shù)。下面小編整理分享到腳本之家平臺(tái)供大家參考2016-04-04Spring?Boot?集成Redisson實(shí)現(xiàn)分布式鎖詳細(xì)案例
這篇文章主要介紹了Spring?Boot?集成Redisson實(shí)現(xiàn)分布式鎖詳細(xì)案例,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-08-08