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 在子容器 * webTest2 在父容器 * @author root * */ public class HelloServlet extends HttpServlet { private static final String NAME = "name"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) { /* * 1.ApplicationContextAware 之能获取父容器中的 * WebTest webTest = (WebTest) SpringContextHelper.getBean("webTest2"); System.out.println("webTest2 :"+webTest); WebTest webTest2 = (WebTest) SpringContextHelper.getBean("webTest"); System.out.println("webTest :"+webTest2);*/ //2.只能获取父容器中的, /*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.只能获取父容器中的, /*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 之能获取父容器中的 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); } }
spring 获取bean 测试
猜你喜欢
转载自m635674608.iteye.com/blog/2399033
今日推荐
周排行