- package com.example;
- public class Dog {
- private String breed;
- public Dog(String breed) {
- this.breed = breed;
- }
- public String getBreed() {
- return breed;
- }
- }
复制代码- package com.example;
- import java.io.IOException;
- import java.io.PrintWriter;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class ListenerTester extends HttpServlet {
-
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html");
- PrintWriter out = response.getWriter();
- out.println("test context attributes set by listener<br>");
- out.println("<br>");
- Dog dog = (Dog) getServletContext().getAttribute("dog");
- out.println("Dog’s breed is: " + dog.getBreed());
- }
- }
复制代码- package com.example;
- import javax.servlet.ServletContext;
- import javax.servlet.ServletContextEvent;
- import javax.servlet.ServletContextListener;
- public class MyServletContextListener implements ServletContextListener {
- @Override
- public void contextDestroyed(ServletContextEvent event) {
- ServletContext sc = event.getServletContext();
- String dogBreed = sc.getInitParameter("breed");
- Dog d = new Dog(dogBreed);
- sc.setAttribute("dog", d);
- }
- @Override
- public void contextInitialized(ServletContextEvent arg0) {
- // TODO Auto-generated method stub
- }
- }
复制代码- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="3.0"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
- <display-name></display-name>
- <servlet>
- <servlet-name>ListenerTester</servlet-name>
- <servlet-class>com.example.ListenerTester</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>ListenerTester</servlet-name>
- <url-pattern>/ListenTest.do</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
-
- <context-param>
- <param-name>breed</param-name>
- <param-value>Great Dane</param-value>
- </context-param>
- <listener>
- <listener-class>
- com.example.MyServletContextListener
- </listener-class>
- </listener>
-
- </web-app>
复制代码 这个webapp是测试listener的,但总是出现空指针异常,自己找了很久,没找出错误来,望各位鼎力相助。
http://localhost:8080/ListenerTest/ListenTest.do
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
com.example.ListenerTester.doGet(ListenerTester.java:22)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.33 logs.
Apache Tomcat/6.0.33
|
|