必威体育Betway必威体育官网
当前位置:首页 > IT技术

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

时间:2019-08-13 23:13:28来源:IT技术作者:seo实验室小编阅读:84次「手机版」
 

servlet

博客主要关于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>

这里写图片描述

这里写图片描述

相关阅读

在servlet 中使用 request.getSession().getServletCo

今天恰好有个上传文件的练习需要使用 request.getSession().getServletContext().getRealPath("upload/" ); 获取上传到服务器上

ContextLoaderListener与DispatcherServlet

在基于XML的Spring MVC配置中,您必须在web.xml文件中看到两个声明,即ContextLoaderListener和DispatcherServlet。让我们试着理解他

jsp servlet mysql实现的新闻发布管理系统项目源码附

今天给大家演示一下一款由jsp servlet mysql实现的新闻发布管理系统,主要实现了前台游客浏览新闻、评论新闻,后台管理员管理新闻等

Servlet中request.getParameter和getParameterValues

Servlet中request.getParameter和getParameterValuesgetParameterNames三者区别 1.request.getParameter:获取前台表单单个元素na

Servlet转发和重定向response.sendRedirecte()区别

转发(forward):IE浏览器地址不会改变,始终是同一个请求。重定向(sendRedirect): IE浏览器地址会改变,用两个请求。1)转发 a)地址栏不

分享到:

栏目导航

推荐阅读

热门阅读