HelloServlet

来源:互联网 发布:last game 软件 编辑:程序博客网 时间:2024/05/02 01:38
package com.servlet.test;import java.io.*;import javax.servlet.http.*;import javax.servlet.*;import javax.servlet.ServletException;// 继承的类的可访问类型必须是public,否则servlet容器不能进行实例化public class HelloServlet extends HttpServlet{ // 1、servlet被装载后,Servlet容器创建一个Servlet实例public HelloServlet(){ super();System.out.println("create...");}// 2、Servlet实例化后,Servlet容器自动调用init()进行初始化,该方法在整个生命周期内仅被调用一次public void init() throws ServletException{ super.init();System.out.println("init...");}// 3、在发生请求时,Servlet容器调用service(request,response)方法,然后根据对应的请求去调用相应的doXXX方法public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException{System.out.println("service...");super.service(req, res);}// 4、servlet的结束//    当WEB应用被终止,或Servlet容器终止运行,或Servlet容器重新装载Servlet新实例时,//    Servlet容器会先调用Servlet的destroy()方法,在destroy()方法中可以释放掉Servlet所占用的资源。public void destroy(){System.out.println("destroy...");super.destroy();}// 3.1、对请求的响应public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{System.out.println("do get...");doServer(request, response);}// 3.2、对请求的响应public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{System.out.println("do post...");doServer(request, response);}private void doServer(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{// 设置请求以及响应的内容类型以及编码方式,一般要写在对请求相应的第一行  response.setContentType("text/html;charset=GB2312"); // 设置为html类型,且编码格式为gb2312 request.setCharacterEncoding("GB2312");PrintWriter pwOut = response.getWriter();pwOut.print("<html><head><title>Test Servlet</title></head>");pwOut.print("<body>");pwOut.print("<p style = " + "color:red" + "><b>测试 servlet 02</b></p>");pwOut.print("</body>");pwOut.print("</html>");}}

说明:

1、如果用Notepad++进行代码编写,建议设置文件编码格式为ANSI;试了其它几种格式在显示中文的时候依然乱码;


0 0
原创粉丝点击