当前位置: 技术问答>java相关
ServletContext 技术问题
来源: 互联网 发布时间:2015-11-18
本文导语: 有2个servlet,servleta,servletb, 在a中用config.getServletContext().setAttribute("testbean",bean)后,在jsp中可以得到bean实例的引用,但在servletb 中用bean = ServletContext.getAttribute("testbean") 会出一个类型比配错误,jb7认为ServletContext.getA...
有2个servlet,servleta,servletb, 在a中用config.getServletContext().setAttribute("testbean",bean)后,在jsp中可以得到bean实例的引用,但在servletb 中用bean = ServletContext.getAttribute("testbean") 会出一个类型比配错误,jb7认为ServletContext.getAttribute("testbean")是一个java.lang.object ,无法编译;如果用(bean)ServletContext.getAttribute("testbean")强制类型转换,得到的(bean)ServletContext.getAttribute("testbean")是null 。
这个问题可否解决?
这个问题可否解决?
|
我测试了一下,没有问题的!
测试代码如下:
test.jsp
Servleta.java
..
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
this.getServletContext().setAttribute("test", new TestBean("abc"));
RequestDispatcher rd = request.getRequestDispatcher("test.jsp");
rd.forward(request, response);
}
..
Servletb.java
..
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
TestBean s = (TestBean)this.getServletContext().getAttribute("test");
System.out.println(s.getTest());
}
..
TestBean.java
public class TestBean {
private String test;
public TestBean() {
}
public TestBean(String test) {
this.test = test;
}
public String getTest() {
return test;
}
}
测试代码如下:
test.jsp
Servleta.java
..
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
this.getServletContext().setAttribute("test", new TestBean("abc"));
RequestDispatcher rd = request.getRequestDispatcher("test.jsp");
rd.forward(request, response);
}
..
Servletb.java
..
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
TestBean s = (TestBean)this.getServletContext().getAttribute("test");
System.out.println(s.getTest());
}
..
TestBean.java
public class TestBean {
private String test;
public TestBean() {
}
public TestBean(String test) {
this.test = test;
}
public String getTest() {
return test;
}
}
|
Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.
也就是说,ServletContext是用来和容器通讯的,不是和别的servlet聊天用的
也就是说,ServletContext是用来和容器通讯的,不是和别的servlet聊天用的
|
我试了,tomcat不行,weblogic7中可以
根据servlet规范2.3应该可以
根据servlet规范2.3应该可以