欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

创建servlet的三种方式 1.实现 servlet接口 2.继承GenericServlet类 3.继承HttpServlet类

程序员文章站 2022-05-23 18:30:24
...

创建servlet的三种方式


1.实现 servlet接口

 

package servlet_mvn_jd2007;

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

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class FirstServlet implements Servlet{

	public FirstServlet() {
		System.out.println("FirstServlet 构造器。。。。");
	}
	
	@Override
	public void destroy() {
		System.out.println("destory.....删除方法");
		
	}

	@Override
	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void init(ServletConfig arg0) throws ServletException {
		System.out.println("FirstServlet init......初始化方法init");
		
	}

	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		System.out.println("service----------------");
		res.setContentType("text/html;charset=UTF-8");
		double r = Math.random();
		PrintWriter pw = res.getWriter();
		pw.println("<html>");
			pw.println("<head>");
				pw.println("<meta charset='UTF-8'>");
				pw.println("<title>First Servlet</title>");
			pw.println("</head>");
			pw.println("<body>");
				pw.println(
						"<font color='green' size='7'>随机数为:"+r+"</font>");
			pw.println("</body>");
	   pw.println("</html>");
	}

}









注意:三种方法都要在web.xml中配置<servlet>信息才可以运行,servlet3.0以后也可以通过写注解的方式来实现,第三种方法见

<servlet>中的顺序必须下面的一样

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>servlet_jd2007</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  <!-- 两个name必须相同,class里面时该类的权限类名,URL除通配符*外都必须以/开头 -->
    <servlet-name>first</servlet-name>
    <servlet-class>servlet_mvn_jd2007.FirstServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>first</servlet-name>
    <url-pattern>/first.do</url-pattern>
  </servlet-mapping>

<!--第二种方法的配置信息-->
<servlet>
    <servlet-name>Second</servlet-name>
    <servlet-class>servlet_mvn_jd2007.SecondServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Second</servlet-name>
    <url-pattern>/second.do</url-pattern>
  </servlet-mapping>
</web-app>

2.继承GenericServlet类

package servlet_mvn_jd2007;

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

import javax.security.auth.Refreshable;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class SecondServlet extends GenericServlet{

	private static final long serialVersionUID = 1L;

	public SecondServlet() {
		System.out.println("SecondServlet Construtor....");
	}
	@Override
	public void init() throws ServletException {
		System.out.println("SecondServlet init ....");
	}
	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		res.setContentType("application/xml;charset+UTF-8");
		PrintWriter pw = res.getWriter();
		pw.println("<students>");
			pw.println("<student sno='s1'>");
				pw.println("<name>briup1</name>");
				pw.println("<age>18</age>");
			pw.println("</student>");
			pw.println("<student sno='s2'>");
				pw.println("<name>briup2</name>");
				pw.println("<age>19</age>");
			pw.println("</student>");
		pw.println("</students>");
		pw.flush();
	}

}

3.继承HttpServlet类

package servlet_mvn_jd2007;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//通过注解的方式,就不需要在web.xml中配置信息了,name可以省略.推荐使用该方法
//@WebServlet(name = "three",urlPatterns = {"/three.do"})
@WebServlet("/three.do")
public class ThreeServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	public ThreeServlet() {
		System.out.println("Threeservlet constructor..");
	}
	@Override
	public void init() throws ServletException {
		System.out.println("ThreeServlet init...");
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("doGet.....threServlet..");
		resp.setContentType("image/jpeg");
		try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream("F:\\A图片\\1.jpg"));
				BufferedOutputStream bos = new BufferedOutputStream(resp.getOutputStream());
				) {
			byte[] b = new byte[1024];
			int len = 0;
			while((len=bis.read(b))!=-1) {
				bos.write(b, 0, len);
			}
			bos.flush();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
	@Override
	public void destroy() {
		System.out.println("ThreeServlet destory...");
		System.out.println("");
	}

}

注意:在maven项目中要在pom.xml中配置一些信息才可以写servlet

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.briup.jd2007</groupId>
  <artifactId>servlet_mvn_jd2007</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
  
    <dependencies>
    <!-- 引入servlet3.1的依赖 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    
    <!-- 引入jstl的依赖,jsp页面中会使用到 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version></dependency>
    </dependencies>
</project>