05_Sevlet

  • Post author:
  • Post category:其他




一.Servlet程序(1)



1.实现Servlet接口.重写service方法

package com.example.web02;

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

public class Hello implements Servlet {
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

    }

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

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        servletResponse.getWriter().println("servlet请求");
        System.out.println("测试servlet成功");
    }

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

    @Override
    public void destroy() {

    }
}



2.WEB-INF下配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>Hello</servlet-name> <!--起别名,通常为类名-->
        <servlet-class>com.example.web02.Hello</servlet-class><!--servlet程序路径-->
    </servlet>

    <servlet-mapping> <!--配置网络访问地址-->
        <servlet-name>Hello</servlet-name><!--servlet程序别名-->
        <!--    访问的路径
                /hello 表示为 http:localhost:8080/web02/hello 其中web02为资源名
                /      http:localhost:8080/web02 表示为资源名
        -->
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

</web-app>



二.Servlet程序(2,通常使用)


  1. 继承HttpServlet,重写doGet/doPost方法

  2. 添加注解@WebServlet

    (或者web.xml配置)
package com.example.web02;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "helloServlet", value = "/hello-servlet") // name程序别名 value网络路径
public class HelloServlet extends HttpServlet {
    private String message;

    public void init() { //初始化
        message = "Hello World!";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");

        // Hello
        PrintWriter out = response.getWriter(); //响应
        // 页面打印
        out.println("<html><body>"); 
        out.println("<h1>" + message + "</h1>");
        out.println("</body></html>");
    }

    public void destroy() {
    }
}



三.Servlet生命周期

  1. 执行构造器
  2. 执行init方法
  3. 执行service方法
  4. 执行destroy销毁方法

其中1,2,只会在第一次访问时调用, 3每次访问都会调用, 4只会在停止Tomcat时调用

package com.example.web02;

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

/**
 * 测试servlet声明周期
 */
public class Hello implements Servlet {

    public Hello(){
        System.out.println("1.执行构造器");
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("2.init方法执行");
    }

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

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        servletResponse.getWriter().println("servlet请求");
        System.out.println("3.测试servlet成功");
    }

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

    @Override
    public void destroy() {
        System.out.println("4.销毁方法调用");
    }
}



四.请求分发

通过在service方法对拦截的请求进行分发

  1. 类型转换 HttpServletRequest request = (HttpServletRequest) ServletRequest
  2. 方法调用 request.getMethod()
@Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String method = request.getMethod();
    }



五.ServletConfig的作用

  1. 获取程序别名
  2. 获取初始化参数
  3. 获取Servletcontext


java程序

package com.example.web02;

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

//@WebServlet(name = "Hello02",value = "/hello02")
public class Hello02 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().println("测试一下,中文乱码?");
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        // 1.获取servlet别名
        System.out.println(config.getServletName());
        // 2.获取init-param
        System.out.println(config.getInitParameter("username"));
        // 3.获取ServletContext
        System.out.println(config.getServletContext());
    }

}


web.xml配置

<servlet>
        <servlet-name>Hello02</servlet-name>
        <servlet-class>com.example.web02.Hello02</servlet-class>
        
        <init-param>
            <param-name>username</param-name>
            <param-value>admin</param-value>
        </init-param>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>Hello02</servlet-name>
        <url-pattern>/hello02</url-pattern>
    </servlet-mapping>



六.ServletContext的作用

ServletContext是一个接口,表示servlet上下文.


一个工程只有一个servletContext实例


ServletContext属于域对象

ServletContext在部署启动时创建, 停止时销毁

  1. 获取web.xml中的context-param参数信息
  2. 获取当前的工程路径; /工程路径
  3. 获取工程部署后在服务器硬盘的绝对路径
  4. Map一样操作数据


Java程序

package com.example.web02;

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

@WebServlet(name = "Hello03",value = "/hello03")
public class Hello03 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);
        ServletContext servletContext = getServletContext();
        //1.获取context-param参数信息
        String pwd = servletContext.getInitParameter("pwd");
        System.out.println(pwd);
        //2.获取工程路径
        String path = servletContext.getContextPath();
        System.out.println(path);
        //3.获取部署在服务器硬盘的绝对路径
        /* / 服务器解析为 http://ip:port/工程名/  映射到IDEA的web目录  */
        String realPath = servletContext.getRealPath("/");
        System.out.println(realPath);
        //4.map一样操作数据
        servletContext.setAttribute("apple",12000);
        Object apple = servletContext.getAttribute("apple");
        System.out.println(apple);
    }
}


web.xml

    <context-param>
        <param-name>pwd</param-name>
        <param-value>123456</param-value>
    </context-param>



7.HTTPServletRequest常用方法

  • getRequestURI() 获取请求的资源路径
  • getRequestURL() 获取请求的统一资源定位符(绝对路径)
  • getRemoteHost() 获取客户端IP地址
  • getHeader() 获取请求头
  • getParameter() 获取请求参数
  • getParameterValues() 获取请求参数(多个)
  • getMethod() 获取请求方式
  • setAttribute(k,v) 设置域数据
  • getAttribute(k) 获取域数据
  • getRequestDispatcher() 获取请求转发对象


Java程序

package com.example.web02;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * 测试HttpServletRequest常用方法
 */
@WebServlet(name="HSRAPI",value = "/hsrAPI")
public class HSRAPI extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);
//        - getRequestURI()      获取请求的资源路径
        System.out.println(req.getRequestURI());
//        - getRequestURL()     获取请求的统一资源定位符(绝对路径)
        System.out.println((req.getRequestURL()+""));
//        - getRemoteHost()     获取客户端IP地址
        System.out.println(req.getRemoteHost());
//        - getHeader()              获取请求头
        System.out.println(req.getHeader("User-Agent"));//请求头UA内容
//        - getMethod()              获取请求方式
        System.out.println(req.getMethod());
//        - setAttribute(k,v)        设置域数据
        req.setAttribute("name","Anna");
//        - getAttribute(k)           获取域数据
        System.out.println(req.getAttribute("name")+"");
//        - getParameter()            获取参数值
        System.out.println(req.getParameter("username"));
//        - getParameterValues()     获取多个参数值(多选框情况)
        System.out.println(Arrays.toString(req.getParameterValues("ctrl")));
    }

}


webapp目录下HSRAPI.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>API测试</title>
</head>
<body>
    <!-- form默认GET方式提交,POST提交添加属性 method="post" -->
    <!--<form action="http://localhost:8080/web02/hsrAPI" method="post">-->
    <form action="http://localhost:8080/web02/hsrAPI">
        <label>
            <input type="text" name="username" placeholder="输入姓名">
        </label>
        <br>
        <label>
            <input type="password" name="password" placeholder="输入密码">
        </label>
        <br>
        <label>
            爱好:
            <input type="checkbox" name="ctrl" value="sing">唱歌
            <input type="checkbox" name="ctrl" value="jump">跳舞
            <input type="checkbox" name="ctrl" value="rap">饶舌
            <input type="checkbox" name="ctrl" value="basketball">篮球
        </label>
        <br>
        <input type="submit" value="提交">
    </form>
</body>
</html>

解决POST请求中文乱码, 设置请求字符集为UTF-8 req.setCharacterEncoding(“utf-8”)

需要在获取参数之前调用才有效



请求转发

package com.example.web02;

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

/**
 * 本类用于测试请求转发
 */
@WebServlet(name = "servlet01",value = "/servlet01")
public class servlet01 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);

        Object username = req.getAttribute("username");
        System.out.println("需要username =>"+username);
        if (username == null){
            req.setAttribute("key","servlet01");
            System.out.println("缺少username,去servlet02获取");
            // 请求转发以 "/" 开头 ,表示为 http://ip:port/工程名/ 映射webapp目录
            RequestDispatcher dispatcher = req.getRequestDispatcher("/servlet02");
            dispatcher.forward(req,resp);
        }

        // 页面打印
        resp.getWriter().println("servlet01 get param success");
    }
}
package com.example.web02;

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

/**
 * 本类用于测试请求转发
 */
@WebServlet(name = "servlet02",value = "/servlet02")
public class servlet02 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);

        Object key = req.getAttribute("key");
        if (key != null){
            req.setAttribute("username","小明");
            System.out.println("在servlet02获得username =>"+req.getAttribute("username"));
        }
        System.out.println("完成业务servlet02,返回servlet01");
        RequestDispatcher dispatcher = req.getRequestDispatcher("/servlet01");
        dispatcher.forward(req,resp);
    }
}



补充

http协议



版权声明:本文为qq_45084064原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。