Servlet web.xml配置方式

  • 全路径匹配

/开始 如/a,/aa/bb

localhost:8080/项目名称/aa/bb

  • 路径匹配,前半段匹配

/开始,但是以*结束/a/*,/*

*其实是一个通配符,匹配任意文字

  • 以扩展名匹配

没有/*开始*.扩展名,*.aa,*.bb

ServletContext

每个web工程都只有一个ServletContext对象,说白了也就是不管在哪个servlet里面,获取到的这个类的对象都是同一个

  1. 获取全局配置参数
  2. 获取web工程中的资源
  3. 存取数据,servlet间共享数据 域对象

如何得到对象

ServletContext context = getServletContext();

获取web.xml中的全局配置参数

package com.servlet;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Servlet1 extends HttpServlet{

    public void init() throws ServletException {
        super.init();
        System.out.println("init方法。。。");
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ServletContext context = getServletContext();
        // 可以获取具体的某一个参数
        String address = context.getInitParameter("alladdress");
        System.out.println("alladdress="+address);

        System.out.println("----------------------------------");
        // 获取所有的参数名称
        Enumeration<String> names = context.getInitParameterNames();
        //遍历取出所有的参数名称
        while (names.hasMoreElements()) {
            String key = (String) names.nextElement();
            String value = context.getInitParameter(key);
            // 打印到页面
            resp.getWriter().println("key==="+key + "   value="+value);
            // 打印到控制台
            System.out.println("key==="+key + "   value="+value);
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  • 和其他的读取单个参数和读取全部参数名的方法名一样
  • getInitParameterNames() 读取所有参数名
  • getInitParameter() 读取该名称的参数
  • 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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>ServletWeb</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>
  <!-- 全局参数部分 -->
  <context-param>
    <param-name>alladdress</param-name>
    <param-value>blog.1997sty.com</param-value>
  </context-param>
  <context-param>
    <param-name>allname</param-name>
    <param-value>enderman2</param-value>
  </context-param>
  <servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-class>com.servlet.Servlet1</servlet-class>
    <init-param>
        <param-name>address</param-name>
        <param-value>1997sty</param-value>
    </init-param>
    <init-param>
        <param-name>name</param-name>
        <param-value>enderman1</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/t1</url-pattern>
  </servlet-mapping>
</web-app>

获取Web应用中的资源

getRealPath() 可以看到当前项目在tomcat里面的根目录 目录不要带有中文 getResourceAsStream() 获取资源 流对象 再通过流对象读取数据

package com.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Servlet1 extends HttpServlet{

    public void init() throws ServletException {
        super.init();
        System.out.println("init方法。。。");
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ServletContext context = getServletContext();
        resp.getWriter().println(context.getRealPath(""));
        resp.getWriter().println(context.getRealPath("config.properties"));
        InputStream is = context.getResourceAsStream("config.properties");
        Properties pro = new Properties();
        pro.load(is);
        resp.getWriter().println(pro.getProperty("database"));
        resp.getWriter().println(pro.getProperty("password"));
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}


// 输出结果
// F:\apache-tomcat-7.0.52\wtpwebapps\ServletWeb
// F:\apache-tomcat-7.0.52\wtpwebapps\ServletWeb\config.properties
// test
// 123456

通过getclassloader去获取web工程下的资源

package com.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

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

public class Servlet1 extends HttpServlet{

    public void init() throws ServletException {
        super.init();
        System.out.println("init方法。。。");
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // F:\apache-tomcat-7.0.52\wtpwebapps\ServletWeb\WEB-INF\classes 类加载器当前路径
        // F:\apache-tomcat-7.0.52\wtpwebapps\ServletWeb\config.properties 文件路径
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("../../config.properties");
        Properties pro = new Properties();
        pro.load(is);
        resp.getWriter().println(pro.getProperty("database"));
        resp.getWriter().println(pro.getProperty("password"));
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

ServletContext存取值和重定向

服务器启动的时候,会为托管的每一个web应用程序,创建一个ServletContext对象。从服务器移除托管,或者是关闭服务器。ServletContext只作用在当前的项目。

package com.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Servlet1 extends HttpServlet{

    public void init() throws ServletException {
        super.init();
        System.out.println("init方法。。。");
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = getServletContext();
        Object obj = context.getAttribute("count");
        int num;
        if(obj == null)
        {
            num = 0;
        }
        else
        {
            num = (int)obj;
        }
        context.setAttribute("count", num + 1);
        System.out.println(obj);
        if(obj != null && (int)obj == 3)
        {
            //2. 跳转界面 
            resp.setStatus(302);
            //定位跳转的位置是哪一个页面
            resp.setHeader("Location", "index.html");
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

// 打印结果
// init方法。。。
// null
// 1
// 2

HttpServletRequest

这个对象封装了客户端提交过来的一切数据

读取请求头

package com.servlet;

import java.io.IOException;
import java.util.Enumeration;

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

public class Login extends HttpServlet{

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //得到一个枚举集合
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = (String) headerNames.nextElement();
            String value = req.getHeader(name);
            System.out.println(name+"="+value);
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

读取请求体

package com.servlet;

import java.io.IOException;
import java.util.*;

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

public class Login extends HttpServlet{

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Enumeration<String> enum1 = req.getParameterNames();
        while (enum1.hasMoreElements()) {
            String name = (String) enum1.nextElement();
            String value = req.getParameter(name);
            System.out.println(name+"="+value);
        }
        System.out.println("--------------------");

        Map<String, String[]> map = req.getParameterMap();
        Set<String> keySet = map.keySet();
        Iterator<String> iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            String value = map.get(key)[0];
            System.out.println(key+"="+value);
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("name");
        String password = req.getParameter("pwsd");
        System.out.println("userName="+username+"==password="+password);
    }
}

// 请求参数
// http://localhost:8080/ServletWeb/login?name=qwe&pwsd=123&aa=2123123

// 打印结果
/*
name=qwe
pwsd=123
aa=2123123
--------------------
name=qwe
pwsd=123
aa=2123123
*/

读取表单数据在控制台打印

  • 创建一个表单
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>get测试登录</h2>
    <form action="login" method="get">
        账号:<input type="text" name="name" /><br>
        密码:<input type="password" name="pwsd" /><br>
        <input type="submit" value="登录">
    </form>
    <h2>post测试登录</h2>
    <form action="login" method="post">
        账号:<input type="text" name="name" /><br>
        密码:<input type="password" name="pwsd" /><br>
        <input type="submit" value="登录">
    </form>
</body>
</html>
  • Login类

get请求过来的数据,在url地址栏上就已经经过编码了,所以我们取到的就是乱码,tomcat收到了这批数据,getParameter 默认使用ISO-8859-1去解码,然后再按utf-8组拼字符串

post请求过来的数据可以直接设置编码 request.setCharacterEncoding("UTF-8");

package com.servlet;

import java.io.IOException;

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

public class Login extends HttpServlet{

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("name");
        String password = req.getParameter("pwsd");
        System.out.println(new String(req.getParameter("name").getBytes("ISO-8859-1"),"UTF-8"));
        System.out.println(new String(req.getParameter("pwsd").getBytes("ISO-8859-1"),"UTF-8"));

    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("name");
        String password = req.getParameter("pwsd");
        System.out.println("userName="+username+"==password="+password);
    }
}

HttpServletResponse

负责返回数据给客户端

//以字符流的方式写数据    
resp.getWriter().write("String");

//以字节流的方式写数据 
resp.getOutputStream().write("String".getBytes());

输出中文字符

  • 以字符流输出
// 指定输出到客户端的时候,这些文字使用UTF-8编码
resp.setCharacterEncoding("UTF-8");

// 直接规定浏览器看这份数据的时候,使用什么编码来看。
resp.setHeader("Content-Type", "text/html; charset=UTF-8");

resp.getWriter().write("blog.1997sty.com 中文测试");
  • 以字节流输出
// 指定浏览器看这份数据使用的码表
resp.setHeader("Content-Type", "text/html;charset=UTF-8");

// 指定输出的中文用的码表
resp.getOutputStream().write("blog.1997sty.com 中文测试".getBytes("UTF-8"));
  • 先声明字符集再进行字符或字节输出
resp.setContentType("text/html;charset=UTF-8");
// ...

资源下载

package com.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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


public class download extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String fileName = req.getParameter("filename");
        String path = getServletContext().getRealPath("upload/"+fileName);
        InputStream fis = new FileInputStream(path);
        OutputStream fos = resp.getOutputStream();
        // 添加响应头内容 filename为下载文件时的文件名
        resp.setHeader("Content-Disposition", "attachment; filename="+fileName);
        //定义字节数组,缓冲
        byte[] bytes = new byte[1024*10];
        //读取数组,写入数组
        int len = 0 ; 
        while((len = fis.read(bytes))!=-1){
            fos.write(bytes, 0, len);
        }
        fos.close();
        fis.close();
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}