全局变量
package cn.tedu.servlet; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //@WebServlet("/DemoServlet")//@WebServlet(urlPatterns={"/DemoServlet2"},loadOnStartup=0)多个映射 @WebServlet(urlPatterns = { "/DemoServlet" }, initParams = { @WebInitParam(name="name", value = "hello"), @WebInitParam(name="name2", value = "java") } ) public class DemoServlet extends HttpServlet { private String fileName; private String name; private static final long serialVersionUID = 1L; public DemoServlet() { System.out.println("DemoServlet"); } @Override public void init() throws ServletException { // TODO Auto-generated method stub System.out.println("init()"); // 1.获取servletconfig对象,从配置对象中 ServletConfig config = this.getServletConfig(); // 2.获取属性值得方法 fileName = config.getInitParameter("fileName"); name=config.getInitParameter("name"); System.out.println(fileName); System.out.println(name); } @Override protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { // TODO Auto-generated method stub super.service(arg0, arg1); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()).append(fileName).append(name); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override public void destroy() { // TODO Auto-generated method stub System.out.println("销毁当前方法"); super.destroy(); } }