Eclipse开发Servlet+jsp模式的简单计数器

Eclipse开发Servlet+jsp模式的简单计数器
1,点击File->TomcatProject,输入工程名;
2,在工程下新建一个index.jsp的页面作为首页
3,在WEB-INF目录下新建一个web.xm的文件,写入以下内容
<? xml version ="1.0" encoding ="UTF-8" ?>
< web-app version ="2.5" 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_2_5.xsd" >

< servlet >  
     < servlet-name >CountServlet </ servlet-name >
     < servlet-class >cn.sdut.chenqiang.CountServlet </ servlet-class >
</ servlet >
< servlet-mapping >
     < servlet-name >CountServlet </ servlet-name >
     < url-pattern >/CountServlet </ url-pattern >
</ servlet-mapping >
< welcome-file-list >
   < welcome-file >index.jsp </ welcome-file >
</ welcome-file-list >
</ web-app >
4,在src目录下新建类CountServlet,继承HttpServlet
package cn.sdut.chenqiang;

import java.io.IOException;
import java.io.PrintWriter;

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

public class CountServlet extends HttpServlet {
   public static final String CONTENT_TYPE= "text/html;charset=UTF-8";

  @Override
   public void init(ServletConfig config) throws ServletException {
     // TODO Auto-generated method stub
     super.init(config);
  }

  @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp)
       throws ServletException, IOException {
     // TODO Auto-generated method stub
    doPost(req, resp);
  }

  @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp)
       throws ServletException, IOException {
     // TODO Auto-generated method stub
    ServletContext context = getServletContext();
    Integer count = (Integer)context.getAttribute( "count");
    
     if (count== null)
    {
      count = new Integer(0);
      context.setAttribute( "count", new Integer(0));
    }
    resp.setContentType(CONTENT_TYPE);
    PrintWriter out = resp.getWriter();
    out.println( "<HTML>");
    out.println( "<HEAD><TITLE>点击计数</TITLE></HEAD>");
    out.println( "<BODY>");
    out.println( "<p>当前计数为:"+count+ "</p>");
    out.println( "</BODY></HEAD>");
    count = new Integer(count.intValue()+1);
    context.setAttribute( "count", count);
  }

  @Override
   public void destroy() {
     // TODO Auto-generated method stub
     super.destroy();
  }
  
}

5,运行即可



你可能感兴趣的:(职场,新建,工程,休闲,计数器)