package com.jayway.springsessionexample; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Optional; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.servlet.support.RequestContextUtils; /** * webTest in subcontainer * webTest2 in parent container * @author root * */ public class HelloServlet extends HttpServlet { private static final String NAME = "name"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) { /* * 1.ApplicationContextAware can get the parent container * WebTest webTest = (WebTest) SpringContextHelper.getBean("webTest2"); System.out.println("webTest2 :"+webTest); WebTest webTest2 = (WebTest) SpringContextHelper.getBean("webTest"); System.out.println("webTest :"+webTest2);*/ //2. Only get the parent container, /*WebTest webTest = (WebTest) ContextLoader.getCurrentWebApplicationContext().getBean("webTest2"); System.out.println("webTest :"+webTest); WebTest webTest2 = (WebTest) ContextLoader.getCurrentWebApplicationContext().getBean("webTest"); System.out.println("webTest2 :"+webTest2);*/ //3. Only the parent container can be obtained, /*WebTest webTest = (WebTest) WebApplicationContextUtils.getWebApplicationContext(req.getServletContext()).getBean("webTest2"); System.out.println("webTest :"+webTest); WebTest webTest2 = (WebTest) WebApplicationContextUtils.getWebApplicationContext(req.getServletContext()).getBean("webTest"); System.out.println("webTest2 :"+webTest2);*/ /* 4. * WebTest webTest = (WebTest) RequestContextUtils.getWebApplicationContext(req).getBean("webTest2"); System.out.println("webTest :"+webTest); WebTest webTest2 = (WebTest) RequestContextUtils.getWebApplicationContext(req).getBean("webTest"); System.out.println("webTest2 :"+webTest2);*/ /*// 5.WebApplicationObjectSupport can get the parent container WebTest webTest = (WebTest) ApplicationContextUtils.getBean("webTest2"); System.out.println("webTest2 :"+webTest); WebTest webTest2 = (WebTest) ApplicationContextUtils.getBean("webTest"); System.out.println("webTest :"+webTest2);*/ String name = Optional.ofNullable(req.getSession(false)) .map(session -> (String) session.getAttribute(NAME)) .orElse("World"); String greeting = String.format("Hello %s!", name); System.out.println("get====greeting "+greeting); try (ServletOutputStream out = resp.getOutputStream()) { out.write(greeting.getBytes(StandardCharsets.UTF_8)); out.flush(); } catch (IOException e) { e.printStackTrace (); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { String name = req.getParameter(NAME); System.out.println("post===="+name); req.getSession().setAttribute(NAME, name); } }