Java-Servlet简单实例

Servlet简单实例:

1.引入依赖包:

 
      javax.servlet
      javax.servlet-api
      4.0.1
    

2.配置web.xml

 <servlet>
    
    <servlet-name>helloservlet-name>
    
    <servlet-class>com.servlet.TestServletservlet-class>
  servlet>
  <servlet-mapping>
    
    <servlet-name>helloservlet-name>
    
    <url-pattern>/hellourl-pattern>
  servlet-mapping>

  <servlet>
    <servlet-name>httpservlet-name>
    <servlet-class>com.servlet.HttpServletTestservlet-class>
  servlet>
  <servlet-mapping>
    <servlet-name>httpservlet-name>
    <url-pattern>/httpurl-pattern>
  servlet-mapping>

3.创建代码:

package com.servlet;

import javax.servlet.*;
import java.io.IOException;

public class TestServlet implements Servlet {
    /*
        当servlet被创建时调用。做初始化工作
        仅第一次被访问时调用(可以改的)
     */
    public void init(ServletConfig config) throws ServletException {

        System.out.println("servlet组件初始化。。。");
    }

    /*
        servlet的配置对象,初始化的时候可以进行配置
     */
    public ServletConfig getServletConfig() {
        System.out.println("getServletConfig方法调用。。。");
        return null;
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        System.out.println("service处理请求。。。");
        res.getOutputStream().write("HelloServlet".getBytes());
    }

    /*
        获取当前servlet一些属性信息
     */
    public String getServletInfo() {
        System.out.println("getServletInfo方法调用。。。");
        return null;
    }

    /*
        销毁时被调用
     */
    public void destroy() {
        System.out.println("destroy销毁实例。。。");
    }
}

4.创建代码:

package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HttpServletTest extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doGet方法调用了");
        resp.getOutputStream().write("doGet方法调用了".getBytes());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doPost方法调用了");
        doGet(req, resp);
    }
}

 

你可能感兴趣的:(Java-Servlet简单实例)