我想让浏览网站的所有人都能从一个类中读取相同的值,以前在jsp中这样做
在某页面代码中写<%application.setAttribute(String name, Object object);%>
这样是不是服务器启动后当第一个人运行了这个页面,这个类才能被生效?现在的项目要求不能在JSP页面中写,这样的话我该如何实现?
我试着写了一个Servlet,配置了web.xml,可在init()中没有ServletRequest参数,也就不能获得application,写在doPost中吧,这样又得在服务器启动后运行一下这个Servlet的地址才能生效?我该用什么来启动Application呢?

解决方案 »

  1.   

    把此servlet设置为随服务器启动而加载,像这样:
       <servlet>
            <servlet-name>bookstore</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
      

  2.   

    感谢killme2008(zane dennis),我还是有点不明白。我继承HttpServlet后如果把application.setAttribute("name", new MyObject());写在doPost中还是无法运行到啊?
    放到init()中又得不到HttpServletRequest request,也不行?
    public class MyServlet extends HttpServlet { public voi init() {
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }}
      

  3.   

    一楼的正解,你需要把application.setAttribute("name", new MyObject());写在init()中private ServletContext application = null;
    public void init(){
      application = getServletContext(); // 你需要的是这个吧?
      application.setAttribute("name", new MyObject());
    }
      

  4.   

    写在servlet的init()方法中,漏了说这点,楼上已经补充