为什么我的servlet间不能通信!!!

527xm 2006-01-10 04:10:33
设置servlet
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;


public class server extends HttpServlet
{
public Connection con=null;

String s="Hello" ;
String y=null;

public void init(ServletConfig config)
throws ServletException
{

super.init(config);

try{
ServletContext context=getServletContext();
//s=context.getServerInfo();


context.setAttribute("hh",s);
}
catch(Exception e)
{
System.err.println(e.getMessage());
}



}

public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
java.io.PrintWriter out=response.getWriter();

response.setContentType("text/html");

//ServletConfig config=getServletConfig();
ServletContext context=getServletContext();
y=(String)context.getAttribute("hh");
out.println(y);

}

public void destroy()
{

}

}


读取的servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.IOException;

public class test extends HttpServlet{

// private ConnectionPool pool=null;

private Connection con=null;

String s=null;

public void init(ServletConfig config)
throws ServletException
{


try{

s=(String)getServletContext().getAttribute("hh");
}

catch(Exception e)
{
System.err.println(e.getMessage());
}


}

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

java.io.PrintWriter out=response.getWriter();

response.setContentType("text/html");

out.print(s);


out.close();

}
}
...全文
130 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
527xm 2006-01-11
  • 打赏
  • 举报
回复
定义了也不成。我是过了.

我不懂xml。我照抄默认的。
superslash 2006-01-11
  • 打赏
  • 举报
回复
try{
ServletContext context=getServletContext();
//s=context.getServerInfo();


context.setAttribute("hh",s);
}
================================================================
把ServletContext context定义成类变量试试
lmxlj 2006-01-11
  • 打赏
  • 举报
回复
好像是配置文件的事。你检查一下 xml文件吧。
527xm 2006-01-11
  • 打赏
  • 举报
回复
帮帮忙阿!
jragon 2006-01-11
  • 打赏
  • 举报
回复
你在test的init方法中漏掉了
super.init(config)调用
所以你在test的init方法中无法获得servletContext对象

你可以通过e.printStackTrace这种方法跟踪错误.可以看到,在test.init时
抛出了空指针异常!
527xm 2006-01-10
  • 打赏
  • 举报
回复
在同一个servlet里可以用servletcontext.getAttribute取到事先设置好的值;可我用另一个servlet就取不到了。这是怎么回事啊?谢谢!!!

67,515

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧