在线等 十万火急 新手求助 JSP ServletContext 报空指针错误 !!!!!!!!

小龙王2010 2010-11-24 05:14:14
错误信息:

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

java.lang.NullPointerException
com.dvd.view.ListLibraryServlet.doGet(ListLibraryServlet.java:87)
javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)


note The full stack trace of the root cause is available in the Apache Tomcat/6.0.14 logs.


--------------------------------------------------------------------------------

源代码:
ListLibraryServlet.java

package com.dvd.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Iterator;
//import java.util.ArrayList;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dvd.model.DVDItem;
import javax.servlet.ServletContext;

public class ListLibraryServlet extends HttpServlet {

/**
* Constructor of the object.
*/
public ListLibraryServlet() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//List dvds = new ArrayList();
//Create the set of dvds
//dvds.add(new DVDItem("Star Wars Episode I","1999","Sci-Fi"));
//dvds.add(new DVDItem("Star Wars","1977","Sci-Fi"));
//Set page title
String pageTitle ="ListLibraryServlet";

//Retrieve the list of dvdItems from the context-scope
ServletContext context = getServletContext();
List dvdList = (List)context.getAttribute("dvdList");
//Specify the content type is HTML
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//Generate the HTML response
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>"+pageTitle+"</TITLE></HEAD>");
out.println(" <BODY bgcolor='white'>");

//Generate page heading
out.print("<!--Page Heading-->");
out.print("<table border='0' cellpadding='3'cellspacing='1'width='400'>");
out.println("<tr bgcolor='#ccccff'");
out.println("<td align='center'><font size='5'>ListLibraryServlet</font></td>");
out.println("</tr>");
out.println("</table>");

//Generate main body
out.println("<p>");
int Size = 0;
//if(dvdList.size() != 0){ Size =dvdList.size();}
out.println("You currently have <font color='red' size='3'><b>"+Size+"</b></font> DVDs in your collection:");
out.println("</p>");
out.println("<table cellpadding='3' cellspacing='1'width='400'>");
out.println("<tr bgcolor='#ccccff'>");
out.println("<td align='left'>Title</td>");
out.println("<td align='center'>Year</td>");
out.println("<td align='center'>Genre</td>");
out.println("</tr>");
Iterator items = dvdList.iterator();
while(items.hasNext()){
DVDItem item = (DVDItem)items.next();
out.println("<tr>");
out.println("<td>"+item.getTitle()+"</td>");
out.println("<td align='center'>"+item.getYear()+"</td>");
out.println("<td align='center'>"+item.getGenre()+"</td>");
out.println("</tr>");
}
out.println("</table>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

/**
* The doPost method of theservlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}


InitializeLibrary.java


package com.dvd.web;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContext;

import com.dvd.model.DVDItem;
import java.util.List;
import java.util.LinkedList;

public class InitializeLibrary implements ServletContextListener {
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event){
ServletContext context = event.getServletContext();
List dvdList = new LinkedList();
String dvdsFile = context.getInitParameter("dvd_file");
InputStream is = null;
BufferedReader reader = null;

try{
is = context.getResourceAsStream(dvdsFile);
if(is != null){
reader = new BufferedReader(new InputStreamReader(is));
}
String record ;

//Read every record (one per line)

while((record = reader.readLine().toString()) != null){
String [] fields = record.split("\t");

//Extract the data fields for the record
String title = fields[0];
String year =fields[1];
String genre = fields[2];

//Add the new DVD Item to the list
DVDItem item = new DVDItem(title,year,genre);
dvdList.add(item);
}
context.setAttribute("dvdList", dvdList);
context.log("The DVD list has been loaded.");
}catch(Exception e){
context.log("Exception occured while proccessing the dvdsFile.",e);
}finally{
if(is != null){
try{is.close();}catch(Exception e){}
}
if(reader !=null){
try {reader.close();}catch(Exception e){}
}
}
}
public void contextDestroyed(ServletContextEvent event){ }

}
...全文
255 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
wangan27 2010-11-25
  • 打赏
  • 举报
回复
ServletContext context = getServletContext();
改成
ServletContext context=request.getServletContext();
或者
ServletContext context=request.getSession().getServletContext();

你上面的context肯定是取不到的 绝对是null
只看了第一个页面 估计是这个原因报空指针异常
小龙王2010 2010-11-25
  • 打赏
  • 举报
回复
谢谢 问题已解决 报错的原因是 保存数据的DVDFiles.txt文件里面的初始数据没有用tab键隔开 所以读不出来
谢谢各位哈
montao 2010-11-25
  • 打赏
  • 举报
回复
com.dvd.view.ListLibraryServlet.doGet(ListLibraryServlet.java:87)

发这个文件的代码出来 ListLibraryServlet.java 在87行后面加一个标注 我们好看一些!
小龙王2010 2010-11-24
  • 打赏
  • 举报
回复
每次运行tomcat Server的时候 都报这个空指针 郁闷:

错误提示:
严重: Exception occured while proccessing the dvdsFile.
java.lang.NullPointerException
at com.dvd.web.InitializeLibrary.contextInitialized(InitializeLibrary.java:36)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4342)
.......................................
2010-11-24 23:44:37 org.apache.catalina.core.ApplicationContext log
信息: ContextListener: contextInitialized()
2010-11-24 23:44:37 org.apache.catalina.core.ApplicationContext log
信息: SessionListener: contextInitialized()
2010-11-24 23:44:38 org.apache.coyote.http11.Http11Protocol start
信息: Starting Coyote HTTP/1.1 on http-8080
2010-11-24 23:44:38 org.apache.jk.common.ChannelSocket init
信息: JK: ajp13 listening on /0.0.0.0:8009
2010-11-24 23:44:38 org.apache.jk.server.JkMain start
信息: Jk running ID=0 time=0/31 config=null
2010-11-24 23:44:38 org.apache.catalina.startup.Catalina start
信息: Server startup in 2916 ms



代码:

package com.dvd.web;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContext;
import com.dvd.model.DVDItem;
import java.util.List;
import java.util.LinkedList;

public class InitializeLibrary implements ServletContextListener {
@SuppressWarnings("unchecked")

public void contextInitialized(ServletContextEvent event){
ServletContext context = event.getServletContext();
List dvdList = new LinkedList();
String dvdsFile = context.getInitParameter("dvd_file");
InputStream is = null;
BufferedReader reader = null;

try{
is = context.getResourceAsStream(dvdsFile);
if(is != null){
reader = new BufferedReader(new InputStreamReader(is));
}
String record ;

//Read every record (one per line)
record = reader.readLine().toString();
while((record = (String)reader.readLine().toString()) != null){ // 这一行就是每次提示报空指针错误的行 真是想不明白啊
String [] fields = record.split("\t");

//Extract the data fields for the record
String title = fields[0];
String year =fields[1];
String genre = fields[2];

//Add the new DVD Item to the list
DVDItem item = new DVDItem(title,year,genre);
dvdList.add(item);
}
context.setAttribute("dvdList", dvdList);
context.log("The DVD list has been loaded.");
}catch(Exception e){
context.log("Exception occured while proccessing the dvdsFile.",e);

}finally{
if(is != null){
try{is.close();}catch(Exception e){}
}
if(reader !=null){
try {reader.close();}catch(Exception e){}
}
}
}
public void contextDestroyed(ServletContextEvent event){ }

}
小龙王2010 2010-11-24
  • 打赏
  • 举报
回复
恩, 可以这么说吧 生成静态HTML

shengfq 2010-11-24
  • 打赏
  • 举报
回复
请问你这个代码就是通过servlet生成静态html页面吗
学习了,帮顶
小龙王2010 2010-11-24
  • 打赏
  • 举报
回复
没人回答么?
小龙王2010 2010-11-24
  • 打赏
  • 举报
回复
还有相关源代码 请各位大侠帮忙解答 谢谢
AddDVDServlet.java

package com.dvd.controller;

import java.io.IOException;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;

import com.dvd.model.DVDItem;
import java.util.List;
import java.util.ArrayList;

public class AddDVDServlet extends HttpServlet {

/**
* Constructor of the object.
*/
public AddDVDServlet() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List errorMsgs = new ArrayList();
request.setAttribute("errorMsgs", errorMsgs);

try{
//Retrieve form parameters
String titleStr = request.getParameter("title").trim();
String yearStr = request.getParameter("year").trim();
String genreStr = request.getParameter("genre").trim();
String newgenreStr = request.getParameter("newgenre").trim();

if(titleStr.length() == 0){
errorMsgs.add("Please enter the title of DVD Item");
}
int year = -1;
try{
year = Integer.parseInt(yearStr);
}catch(NumberFormatException nfe){
errorMsgs.add("The 'year' field must be a positive integer");
}
//Verify form parameters
if((year != -1)&&((year <2000)||(year>2100))){
errorMsgs.add("The 'year' field must within 2000 to 2100");
}
if(genreStr.equals("unknown")&&newgenreStr.equals("Add new genre")){
errorMsgs.add("Please select a genre Or define the new Genre");
}
if(!(genreStr.equals("unknown"))&&!(newgenreStr.equals("Add new genre"))){
errorMsgs.add("Please just select one genre:genre Or newgenre");
}
//Send the user back to the AddDVD form, if there were errors
if(! errorMsgs.isEmpty()){
RequestDispatcher view
= request.getRequestDispatcher("add_dvd.view");
view.forward(request, response);
}
//Perform business logic
if(genreStr.equals("unknown")){
genreStr = newgenreStr;
}
//Store the new DVD Application in the request-scope
DVDItem dvdItem = new DVDItem(titleStr,yearStr,genreStr);
request.setAttribute("dvdItem", dvdItem);

//Store the new DVD in the dvdList context-scope attribute
ServletContext context = getServletContext();
List dvdList =(List)context.getAttribute("dvdList");
dvdList.add(dvdItem);

//send the success view
RequestDispatcher view
=request.getRequestDispatcher("success.view");
view.forward(request, response);
}catch(Exception e){
errorMsgs.add(e.getMessage());

}
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}

81,114

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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