Java common class request | session

Source: Internet
Author: User

Many people are looking for ways to obtain the system's request or session in a common class. I also looked for it, but I didn't have it. I realized it myself and looked forward to the target people, hope it can help a little bit. Perform the following steps: 1. define a Thread class. In general, the most important parameter in the class is to define a parameter: private static ThreadLocal <HttpServletRequest> httpRequest = new ThreadLocal <HttpServletRequest> (); in addition, three methods related to set get remove and thread are provided. Details are as follows: [java] public class SystemRequestContext {private static ThreadLocal <HttpServletRequest> httpRequest = new ThreadLocal <HttpServletRequest> (); private static ThreadLocal <HttpSession> session = new ThreadLocal <HttpSession> (); Public static void removeHttpSession () {session. remove ();} public static HttpSession getSession () {return session. get ();} public static void setSession (HttpSession _ session) {session. set (_ session);} 2. define a filter, intercept all requests, and load the request into [java] SystemRequestContext. The Code is as follows: [java] public void doFilter (ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletExcept Ion {HttpServletRequest request = (HttpServletRequest) req; SystemRequestContext. setHttpRequest (request); SystemRequestContext. setSession (request. getSession (); try {chain. doFilter (request, response);} finally {SystemRequestContext. removeHttpRequest (); SystemRequestContext. removeHttpSession () ;}} 3. how to Use: [java] public class UserModuleValidateTag {public static boolean validateModule (String module) {HttpServletRequest request = SystemRequestContext. getHttpRequest (); if (null! = Request) System. out. println ("^_^" + request );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.