programing

스프링: 필터에서 컨트롤러로 객체를 전달하는 방법

i4 2023. 8. 4. 22:40
반응형

스프링: 필터에서 컨트롤러로 객체를 전달하는 방법

Spring Boot 응용 프로그램의 컨트롤러 내에서 사용할 개체를 만드는 필터를 추가하려고 합니다.

필터를 요청별로 컨트롤러에서만 유용한 이 개체의 "중앙 집중식" 생성기로 사용하는 것이 좋습니다.나는 그것을 사용하려고 노력했습니다.HttpServletRequest request.getSession().setAttribute방법:컨트롤러의 개체에 액세스할 수 있지만 세션에 개체가 (명시하게) 추가됩니다.

필터가 올바른 방법입니까?그렇다면 컨트롤러에서 사용할 필터에서 생성한 임시 개체를 어디에 보관할 수 있습니까?

당신은 왜 콩을 사용하지 않습니까?@Scope('request')

@Component
@Scope(value="request", proxyMode= ScopedProxyMode.TARGET_CLASS)
class UserInfo {
   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

   private String password;
}

그러면 당신은 할 수 있습니다.Autowireed필터와 컨트롤러 모두에서 데이터 설정 및 가져오기 작업을 수행합니다.

이것의 라이프사이클UserInfobean은 요청 내에만 존재하므로 http 요청이 완료되면 인스턴스도 종료합니다.

서블릿 요청을 사용할 수 있습니다.set 속성(문자열 이름, Objecto);

예를들면

@RestController
@EnableAutoConfiguration
public class App {

    @RequestMapping("/")
    public String index(HttpServletRequest httpServletRequest) {
        return (String) httpServletRequest.getAttribute(MyFilter.passKey);
    }

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Component
    public static class MyFilter implements Filter {

        public static String passKey = "passKey";

        private static String passValue = "hello world";

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            request.setAttribute(passKey, passValue);
            chain.doFilter(request, response);
        }

        @Override
        public void destroy() {

        }
    }
}

wkong의 답변에 추가.Spring 4.3 이후 사용하여 속성을 설정한 후request.setAttribute(passKey, passValue);컨트롤러의 속성에 대한 주석을 달기만 하면 액세스할 수 있습니다.@RequestAttribute.

전에

@RequestMapping("/")
public String index(@RequestAttribute passKey) {
    return (String) passKey;
}

실제로 시나리오가 무엇인지는 모르겠지만 필터에서 개체를 만들고 코드의 어딘가에 사용하려면 다음을 사용할 수 있습니다.ThreadLocal그렇게 할 수 있는 수업

이 작업이 스레드 로컬 목적 질문에서 가장 많이 투표된 답변을 어떻게 확인하는지 알아보려면 다음과 같이 하십시오.

일반적으로 사용하는 방법ThreadLocal현재 스레드에서만 사용할 수 있는 개체를 저장할 수 있는 클래스를 만들 수 있습니다.

때때로 최적화의 이유로 동일한 스레드가 후속 요청을 처리하는 데 사용될 수 있으므로 요청이 처리된 후 threadLocal 값을 정리하는 것이 좋습니다.

class MyObjectStorage {
  static private ThreadLocal threadLocal = new ThreadLocal<MyObject>();

  static ThreadLocal<MyObject> getThreadLocal() {
    return threadLocal;
  }
}

필터 안에

MyObjectStorage.getThreadLocal().set(myObject);

및 컨트롤러에서

MyObjectStorage.getThreadLocal().get();

필터 대신 @ControllerAdvise를 사용하고 모델을 사용하여 지정된 컨트롤러에 개체를 전달할 수도 있습니다.

@ControllerAdvice(assignableTypes={MyController.class})
class AddMyObjectAdvice {

    // if you need request parameters
    private @Inject HttpServletRequest request; 

    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("myObject", myObject);
    }
}


@Controller
public class MyController{

   @RequestMapping(value = "/anyMethod", method = RequestMethod.POST)
   public String anyMethod(Model model) {
      MyObjecte myObject = model.getAttribute("myObject");

      return "result";
   }
}

언급URL : https://stackoverflow.com/questions/35444633/spring-how-to-pass-objects-from-filters-to-controllers

반응형