Servlet——开发Servlet三种方法详解

● Java基础 专栏收录该内容
51 篇文章 0 订阅

该博客主要关于java servlet编程,开发servlet三种方法

该篇博客目录

1、实现servlet接口
2、继承GenericServlet
3、继承HttpServlet
4、用户登录(利用HttpServlet)

关于目录前三条,都是开发servlet的方法,发展过程按目录先后次序,目前HttpServlet最广泛

有一点要注意,每写一个servlet都要部署一次


一、实现servlet接口——开发servlet

开发servlet要引入servlet-api.jar

该接口中有三个生命周期

  • init():该init函数用于初始化该servlet,该函数只会被调用一次(当用户第一次访问该servlet时被调用)
  • destroy():销毁servlet实例(释放内存),关闭tomcat是调用
  • service:service函数用于处理业务逻辑,业务逻辑代码都写在这,当用户访问servlet时,都会调用该函数

还有两个普通方法

  • getServletInfo():获取servlet信息,可选项
  • getServletConfig:获取servlet配置信息,可选项

hello.java

package cn.linjie;

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 hello implements Servlet{

    //销毁servlet实例(释放内存),关闭tomcat是调用
    @Override
    public void destroy() {
        System.out.println("destroy");
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    //该init函数用于初始化该servlet,该函数只会被调用一次(当用户第一次访问该servlet时被调用)
    @Override
    public void init(ServletConfig arg0) throws ServletException {
        System.out.println("init it");
    }

    //service函数用于处理业务逻辑,业务逻辑代码都写在这
    //当用户访问servlet时,都会调用该函数
    //res:用于获得客户端(浏览器)的信息
    //ron:用于向客户端(浏览器)返回信息
    @Override
    public void service(ServletRequest res, ServletResponse ron) throws ServletException, IOException {
        System.out.println("service");

        //打印在浏览器上
        PrintWriter pw=ron.getWriter();
        pw.println("hello,this is servlet");
    }

}

web.xml(与lib同级)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<!--   实现servlet -->
  <display-name>hello</display-name>
  <!-- servlet部署 -->
  <servlet>
    <!--给servlet取名,任意 -->
    <servlet-name>name</servlet-name>
    <!-- 指明servlet路径,包名.类名 -->
    <servlet-class>cn.linjie.hello</servlet-class>
  </servlet>
  <servlet-mapping>
    <!--servlet映射,必须与servlet-name同名 -->
    <servlet-name>name</servlet-name>
    <!--这是浏览器中输入的访问该servlet的url-->
    <url-pattern>/sp</url-pattern>
  </servlet-mapping>
</web-app>

servlet生命周期有四个阶段

  • 加载和实例化:由servlet容器负责
  • 初始化:init
  • 请求处理:service
  • 服务终止:destroy

这里写图片描述

结果

这里写图片描述


二、继承GenericServlet——开发servlet

只需要重写service方法

helloGen.java

package cn.linjie;

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

import javax.servlet.*;


public class helloGen extends GenericServlet  {

    @Override
    public void service(ServletRequest res, ServletResponse ron) throws ServletException, IOException {
        System.out.println("service..");
        PrintWriter pw=ron.getWriter();
        pw.println("hello,this is a GenericServlet");
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<!--   实现servlet -->
  <display-name>hello</display-name>
  <!-- servlet部署 -->
  <servlet>
    <!--给servlet取名,任意 -->
    <servlet-name>name</servlet-name>
    <!-- 指明servlet路径,包名.类名 -->
    <servlet-class>cn.linjie.hello</servlet-class>
  </servlet>
  <servlet-mapping>
    <!--servlet映射,必须与servlet-name同名 -->
    <servlet-name>name</servlet-name>
    <!--这是浏览器中输入的访问该servlet的url-->
    <url-pattern>/sp</url-pattern>
  </servlet-mapping>
<!--   继承GenericSevlet -->
  <servlet>
    <servlet-name>name2</servlet-name>
    <servlet-class>cn.linjie.helloGen</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>name2</servlet-name>
    <url-pattern>/sp2</url-pattern>
  </servlet-mapping>
</web-app>

这里写图片描述


继承HttpServlet——开发servlet

需要重写doGet和doPost方法

表单提交数据get请求与post请求的区别

  • 安全性:get

helloHttp.java

package cn.linjie;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/helloHttp")
public class helloHttp extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public helloHttp() {
        super();
    }

    /*
     *doGet写业务逻辑 
     *doPost调用doGet 
     */

    //处理get请求
    //res获取浏览器信息
    //ron向浏览器返回信息
    protected void doGet(HttpServletRequest res, HttpServletResponse ron) throws ServletException, IOException {
        PrintWriter pw=ron.getWriter();
        pw.println("hello,this is a HttpServlet");
    }

    //处理post请求
    //为什么doGet合可以写在doPost中,因为两个方法代码一样,这样调用可以避免代码重复
    protected void doPost(HttpServletRequest res, HttpServletResponse ron) throws ServletException, IOException {
        doGet(res, ron);
    }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<!--   实现servlet -->
  <display-name>hello</display-name>
  <!-- servlet部署 -->
  <servlet>
    <!--给servlet取名,任意 -->
    <servlet-name>name</servlet-name>
    <!-- 指明servlet路径,包名.类名 -->
    <servlet-class>cn.linjie.hello</servlet-class>
  </servlet>
  <servlet-mapping>
    <!--servlet映射,必须与servlet-name同名 -->
    <servlet-name>name</servlet-name>
    <!--这是浏览器中输入的访问该servlet的url-->
    <url-pattern>/sp</url-pattern>
  </servlet-mapping>
<!--   继承GenericSevlet -->
  <servlet>
    <servlet-name>name2</servlet-name>
    <servlet-class>cn.linjie.helloGen</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>name2</servlet-name>
    <url-pattern>/sp2</url-pattern>
  </servlet-mapping>
<!--   继承HttpServlet -->
    <servlet>
    <servlet-name>name3</servlet-name>
    <servlet-class>cn.linjie.helloHttp</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>name3</servlet-name>
    <url-pattern>/sp3</url-pattern>
  </servlet-mapping>
</web-app>

这里写图片描述

四、用户登录开发(HttpServlet)

用户登录框架

这里写图片描述

logindemo.java

package cn.linjie;

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

import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录界面
 */
@WebServlet("/helloHttp")
public class logindemo extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public logindemo() {
        super();
        // TODO Auto-generated constructor stub
    }

    /*
     *doGet写业务逻辑 
     *doPost调用doGet 
     */

    //处理get请求
    //res获取浏览器信息
    //ron向浏览器返回信息
    protected void doGet(HttpServletRequest res, HttpServletResponse ron) throws ServletException, IOException {

        //处理中文乱码
        ron.setContentType("text/html;charset=utf-8");

        PrintWriter pw=ron.getWriter();

        pw.println("<html>");
        pw.println("<body>");
        pw.println("<title>登录</title>");
        pw.println("<h1>登录</h1>");
        pw.println("<form action=loginC method=post>");
        pw.println("用户名<input type=text name=username><br>");
        pw.println("密码<input type=password name=passwd><br>");
        pw.println("<input type=submit value=login><br>");
        pw.println("</form>");
        pw.println("</body>");
        pw.println("</html>");
    }

    //处理post请求
    //为什么doGet合可以写在doPost中,因为两个方法代码一样,这样调用可以避免代码重复
    protected void doPost(HttpServletRequest res, HttpServletResponse ron) throws ServletException, IOException {
        doGet(res, ron);
    }


}

loginC.java

package cn.linjie;

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;

/**
 * 登录验证
 */
@WebServlet("/loginC")
public class loginC extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public loginC() {
        super();
        // TODO Auto-generated constructor stub
    }


    protected void doGet(HttpServletRequest res, HttpServletResponse ron) throws ServletException, IOException {
        //接受用户名和密码(res是获取浏览器信息)
        String u=res.getParameter("username");
        String p=res.getParameter("passwd");

        //验证
        if(u.equals("xlj")&&p.equals("123"))
        {
            //合法
            //跳转
            ron.sendRedirect("welcome");
        }else {
            //不合法
            //跳转(参数是跳转至的url)
            ron.sendRedirect("login");
        }
    }


    protected void doPost(HttpServletRequest res, HttpServletResponse ron) throws ServletException, IOException {
        doGet(res, ron);
    }

}

Wlcome.java

package cn.linjie;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Welcome
 */
@WebServlet("/Welcome")
public class Welcome extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Welcome() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest res, HttpServletResponse ron) throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter pw=ron.getWriter();
        pw.println("welcome");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest res, HttpServletResponse ron) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(res, ron);
    }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <servlet>
    <servlet-name>logindemo</servlet-name>
    <servlet-class>cn.linjie.logindemo</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>logindemo</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
    <servlet>
    <servlet-name>loginC</servlet-name>
    <servlet-class>cn.linjie.loginC</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>loginC</servlet-name>
    <url-pattern>/loginc</url-pattern>
  </servlet-mapping>
    <servlet>
    <servlet-name>Welcome</servlet-name>
    <servlet-class>cn.linjie.Welcome</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Welcome</servlet-name>
    <url-pattern>/welcome</url-pattern>
  </servlet-mapping>
</web-app>

这里写图片描述

这里写图片描述

  • 17
    点赞
  • 3
    评论
  • 54
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 程序猿惹谁了 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值