您好,登錄后才能下訂單哦!
這篇文章主要介紹“springboot中@component注解如何使用”,在日常操作中,相信很多人在springboot中@component注解如何使用問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”springboot中@component注解如何使用”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
配置響應頭的內容。
直接在攔截器里配置響應頭內容。
/** * 攔截器--用戶身份確認。 */ public class RestInterceptor implements HandlerInterceptor { private static final Logger log = LoggerFactory.getLogger(RestInterceptor.class); private static final String tokenHeader = "Authorization"; /** * 返回值:true表示繼續流程(如調用下一個攔截器或處理器);false表示流程中斷(如登錄檢查失敗),不會繼續調用其他的攔截器或處理器,此時我們需要通過response來產生響應; */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("攔截請求"); //響應頭 response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,authorization"); response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS"); if(request.getMethod().equals("OPTIONS")){ response.setStatus(204); return true; } log.info("調用接口:method=" +request.getParameter("method")+",params="+JSON.toJSONString(request.getParameterMap())); // HandlerMethod handlerMethod = (HandlerMethod)handler; // RequestAuth requestAuth = handlerMethod.getMethodAnnotation(RequestAuth.class); // if(requestAuth!=null && requestAuth.auth()==false){ //非驗證API // return true;//跳過驗證 // } //驗證 // String token = request.getHeader(tokenHeader); // if(token == null || token.equals("")) { // log.info("沒有找到token"); // throw new BusinessException(ResMsg.CODE_TOKEN_NOTFOUND, "沒有找到token"); // } else { // JWSObject jwsObject = JWSObject.parse(token); // Payload payload = jwsObject.getPayload(); // JSONObject obj = payload.toJSONObject(); // String roleNames = String.valueOf(obj.get("roleNames")); // Authentication auth = new Authentication(); // if(obj.containsKey("platformId")) { // Long platformId = Long.valueOf(String.valueOf(obj.get("platformId"))); // auth.setPlatformId(platformId); // } // if(obj.containsKey("userid")) { // Long userId = Long.valueOf(String.valueOf(obj.get("userid"))); // auth.setUserId(userId); // } // if(obj.containsKey("orgId")) { // Long orgId = Long.valueOf(String.valueOf(obj.get("orgId"))); // auth.setOrgId(orgId); // } // if(obj.containsKey("orgid")) {//為兼容老版本的接口 // String orgid = String.valueOf(obj.get("orgid")); // orgid = orgid.replace(",", ""); // Long orgId = Long.valueOf(orgid); // auth.setOrgId(orgId); // } // auth.setRoleNames(roleNames); // SecurityContext.setContext(auth); // JwtUtil.verify(jwsObject); // } return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { //log.info("處理中"); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { if(ex != null) { log.error("接口處理異常:"+ex); throw ex; } } }
使用@component注解,將普通JavaBean實例化到spring容器中。
public class RestInterceptor implements HandlerInterceptor { private static final Logger log = LoggerFactory.getLogger(RestInterceptor.class); private static final String tokenHeader = "Authorization"; /** * 返回值:true表示繼續流程(如調用下一個攔截器或處理器);false表示流程中斷(如登錄檢查失敗),不會繼續調用其他的攔截器或處理器,此時我們需要通過response來產生響應; */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("攔截請求"); if(request.getMethod().equals("OPTIONS")){ response.setStatus(204); return true; } log.info("調用接口:method=" +request.getParameter("method")+",params="+JSON.toJSONString(request.getParameterMap())); return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { //log.info("處理中"); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { if(ex != null) { log.error("接口處理異常:"+ex); throw ex; } } }
定義 SimpleCORSFilter.java 類, 使用@component注解
@Component public class SimpleCORSFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,authorization"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {} }
兩種方式都可以完成響應。
被@Component注解標識的類,會被納入Spring容器中統一管理,好處是什么?一句話概括:你不用自己new了!
到此,關于“springboot中@component注解如何使用”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。