In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how to use @ component annotations in springboot". In daily operation, I believe many people have doubts about how to use @ component annotations in springboot. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods, hoping to help you answer the doubts about "how to use @ component annotations in springboot"! Next, please follow the editor to study!
Use of @ component annotations
Configure the contents of the response header.
Mode one
Configure the response header directly in the interceptor.
/ * interceptor-user identity confirmation. * / public class RestInterceptor implements HandlerInterceptor {private static final Logger log = LoggerFactory.getLogger (RestInterceptor.class); private static final String tokenHeader = "Authorization"; / * * returned value: true means to continue the process (such as calling the next interceptor or processor); false indicates that the process is interrupted (such as login check failure) and other interceptors or processors will not be called. In this case, we need to generate a response through response. * / public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {log.info ("intercept request"); / / response header response.setHeader ("Access-Control-Allow-Origin", "*"); response.setHeader ("Access-Control-Allow-Headers", "xmusic requestdlle withcontentlytypejurisdiction") Response.setHeader ("Access-Control-Allow-Methods", "POST,GET,OPTIONS"); if (request.getMethod (). Equals ("OPTIONS")) {response.setStatus (204); return true;} log.info ("calling API: method=" + request.getParameter ("method") + ", params=" + JSON.toJSONString (request.getParameterMap () / / HandlerMethod handlerMethod = (HandlerMethod) handler;// RequestAuth requestAuth = handlerMethod.getMethodAnnotation (RequestAuth.class); / / if (requestAuthorization null & & requestAuth.auth () = = false) {/ / non-authentication API / / return true;// skip verification / /} / verify / / String token = request.getHeader (tokenHeader) / / if (token = = null | | token.equals (")) {/ / log.info (" token not found "); / / throw new BusinessException (ResMsg.CODE_TOKEN_NOTFOUND," token not found "); / /} 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")) {/ / is an interface compatible with older versions / / 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 ("processing") } public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {if (ex! = null) {log.error ("API handling exception:" + ex); throw ex;} mode 2
Instantiate the normal JavaBean into the spring container using the @ component annotation.
Public class RestInterceptor implements HandlerInterceptor {private static final Logger log = LoggerFactory.getLogger (RestInterceptor.class); private static final String tokenHeader = "Authorization"; / * returned value: true means to continue the process (such as calling the next interceptor or processor); false indicates that the process is interrupted (such as login check failure) and will not continue to call other interceptors or processors. In this case, we need to generate a response through response. * / public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {log.info ("intercept request"); if (request.getMethod (). Equals ("OPTIONS")) {response.setStatus (204); return true } log.info ("calling API: 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 ("processing") } public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {if (ex! = null) {log.error ("API handling exception:" + ex); throw ex;}
Define SimpleCORSFilter.java classes, annotated with @ component
@ Componentpublic 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", "xmurrequestedcopyright withcontentlylytypejime"); chain.doFilter (req, res);} public void init (FilterConfig filterConfig) {} public void destroy () {}}
The response can be completed in both ways.
What is the purpose of @ component annotations? can be summarized in one sentence
Classes identified by the @ Component annotation will be uniformly managed in the Spring container. What are the benefits? To sum up in a word: you don't have to new yourself!
At this point, the study on "how to use @ component annotations in springboot" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.