Skip to content

5.Servlet接口

5.1 servletConfig

5.2 servletContext

5.3.HttpServletRequest

  • ServletRequest接口被定义为用于封装请求的信息,ServletRequest对象由Servlet容器在用户每次请求Servlet时创建并传入Servlet的service()方法中;

  • HttpServletRequest接口继承了ServletRequest接口,是专用于HTTP协议的子接口,用于封装HTTP请求信息;

  • 在HttpServlet类的service()方法中,传入的ServletRequest对象被强制转换为HttpServletRequest对象来进行HTTP请求信息的处理。

  • HttpServletRequest接口提供了具有如下功能类型的方法:

    • 获取请求报文信息(包括请求行、请求头、请求正文)的方法;

    • 获取网络连接信息的方法;

    • 存取请求域属性的方法。

  • HttpServletRequest接口对请求行各部分信息的获取方法

    • getMethod(),获取请求使用的HTTP方法,例如,GET、POST、PUT
    • getRequestURI(),获取请求行中的资源名部分
    • getProtocol(),获取使用的协议及版本号。例如,HTTP/1.1、HTTP/1.0
    • getQueryString(),获取请求URL后面的查询字符串,只对GET有效
    • getServletPath(),获取Servlet所映射的路径
    • getContextPath(),获取请求资源所属于的Web应用的路径
java
package com.neuedu.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Enumeration;
import java.util.Map;

/**
 * 项目:      usermanager
 * 类名:       ${NAME}
 * 创建时间:  2020/12/9  10:42
 * 描述 :     ${dc}
 * 作者 :     张金山
 * QQ :     314649444
 * Site:      https://jshand.gitee.io
 *
 * http://127.0.0.1:8080/mis/req
 */
@WebServlet(name = "RequestServlet",urlPatterns = "/req")
public class RequestServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //请求的http 行方法(客户端)
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String protocol = request.getProtocol();
        String queryString = request.getQueryString();
        String servletPath = request.getServletPath();
        String contextPath = request.getContextPath();

        System.out.println("method:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protocol:"+protocol);
        System.out.println("queryString:"+queryString);
        System.out.println("servletPath:"+servletPath);
        System.out.println("contextPath:"+contextPath);


        System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++");

        //请求头
        Enumeration<String> names = request.getHeaderNames();
        while (names.hasMoreElements()){
            String name = names.nextElement();
            String value = request.getHeader(name);
            System.out.printf("%s:\t%s\r\n",name,value);
        }


        System.out.println("-------------------------------------------------------------");
        String contentType = request.getContentType();
        int contentLength = request.getContentLength();
        System.out.println("contentType:"+contentType);
        System.out.println("contentLength:"+contentLength);


//        System.out.println("-----------------------------------------------------");
//        Reader r = new InputStreamReader(request.getInputStream());
//        BufferedReader br = new BufferedReader(r);
//
//        String line= null;
//        while( (line =br.readLine() ) != null){
//            System.out.println(line);
//        }


        System.out.println("---------------------------------------------");
        Map<String,String[]> paramMap = request.getParameterMap();
        String[] usernames = paramMap.get("username");
        System.out.println(usernames[0]);

    }
}

存储在HttpServletRequest对象中的对象称之为请求域属性,属于同一个请求的多个处理组件之间可以通过请求域属性来传递对象数据。

HttpServletRequest接口提供了如下与请求域属性相关的方法:

  • void setAtrribute(String name,Object value),设定name属性的值为value,保存在request范围内;
  • Object getAttribute(String name),从request范围内获取name属性的值;
  • void removeAttribute(String name),从request范围内移除name属性的值;
  • Enumeration getAttributeNames(),获取所有request范围的属性

UserControllerServlet

java
package com.neuedu.servlet;

import com.neuedu.dao.UserDao;
import com.neuedu.entity.User;

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.List;

/**
 * 项目:      usermanager
 * 类名:       ${NAME}
 * 创建时间:  2020/12/9  13:39
 * 描述 :     ${dc}
 * 作者 :     张金山
 * QQ :     314649444
 * Site:      https://jshand.gitee.io
 */
@WebServlet(name = "UserControllerServlet",urlPatterns = "/usecontroller")
public class UserControllerServlet extends HttpServlet {
    UserDao userDao = new UserDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sql = "select * from user";
        List<User> userList = userDao.list(sql);

        //共享数据
        request.setAttribute("userList",userList);
        request.getRequestDispatcher("userlist").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

UserListServlet

java
package com.neuedu.servlet;

import com.neuedu.entity.User;

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.io.PrintWriter;
import java.util.List;

/**
 * 项目:      usermanager
 * 类名:       ${NAME}
 * 创建时间:  2020/12/9  13:40
 * 描述 :     ${dc}
 * 作者 :     张金山
 * QQ :     314649444
 * Site:      https://jshand.gitee.io
 */
@WebServlet(name = "UserListServlet",urlPatterns = "/userlist")
public class UserListServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        List<User> userList = (List) request.getAttribute("userList");

        //通知浏览器 内容的类型
        response.setContentType("text/html;charset=utf-8");

        StringBuffer html = new StringBuffer();
        html.append(" <a href='user?type=toAdd'>添加</a>");
        html.append(" <table border='1' width='100%'  cellpadding='0' cellspacing='0'>			");
        html.append(" <tr>               ");
        html.append(" 	<td>序号</td>   ");
        html.append(" 	<td>用户名</td> ");
        html.append(" 	<td>昵称</td>   ");
        html.append(" 	<td>密码</td>   ");
        html.append(" 	<td>出生日期</td>   ");
        html.append(" 	<td>性别</td>   ");
        html.append(" 	<td>邮箱 </td>   ");
        html.append(" 	<td>操作 </td>   ");
        html.append(" </tr>              ");

        for (User user : userList) {

            html.append(" <tr>               ");
            html.append(" 	<td>" + user.getId() + "</td>       ");
            html.append(" 	<td>" + user.getUsername() + "</td>       ");
            html.append(" 	<td>" + user.getDisplayname() + "</td>       ");
            html.append(" 	<td>" + user.getPassword() + "</td>       ");
            html.append(" 	<td>" + user.getBirthday() + "</td>       ");
            html.append(" 	<td>" + user.getGender() + "</td>       ");
            html.append(" 	<td>" + user.getEmail() + "</td>       ");
            html.append(" 	<td><a href='user?type=toEdit&id=" + user.getId() + "'>编辑</a>  <a href='user?type=delete&id=" + user.getId() + "'>删除</a></td>       ");
            html.append(" </tr>              ");
        }

        html.append(" </table>           ");

        PrintWriter out = response.getWriter();
        out.print(html.toString());


        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

5.4 HttpServletResponse

5.4.1 响应输出中文乱码问题

设置响应字符集

  • 由于Java程序中的字符文本在内存中以Unicode编码的形式存在,因此PrintWriter对象在输出字符文本时,需要先将它们转换成其他某种字符集编码的字节数组后输出。

  • PrintWriter对象默认使用ISO-8859-1字符集进行Unicode字符串到字节数组的转换,由于ISO-8859-1字符集中没有中文字符,因此Unicode编码的中文字符将被转换成无效的字符编码后输出给客户端,这就是Servlet中文输出乱码问题的原因。

  • ServletResponse接口中定义了三种方等方法来指定getWriter()方法返回的PrintWriter对象所使用的字符集编码。

    • response.setCharacterEncoding("UTF-8");
      • 只能用来设置PrintWriter输出流中字符的编码方式,它的优先权最高。
    • response.setContentType("text/html;charset=UTF-8");
      • 既可以设置PrintWriter输出流中字符的编码方式,也可以设置浏览器接收到这些字符后以什么编码方式来解码,它的优先权低于第一种方法。
    • response.setLocale(new java.util.Locale("zh","CN"));
      • 只能用来设置PrintWriter输出流中字符的编码方式,它的优先权最低,在已经使用前两种方法中的一个设置了编码方式以后,它将被覆盖而不再起作用。
java
package com.neuedu.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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.io.PrintWriter;

/**
 * 项目:      usermanager
 * 类名:       ${NAME}
 * 创建时间:  2020/12/9  14:40
 * 描述 :     ${dc}
 * 作者 :     张金山
 * QQ :     314649444
 * Site:      https://jshand.gitee.io
 */
@WebServlet(name = "ResponseServlet", urlPatterns = "/resp")
public class ResponseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//            response.setStatus();

        response.addHeader("class","java1");
        response.addHeader("Content-Type","text/html;charset=utf-8");

//        response.setContentType("text/html;charset=utf-8");

        PrintWriter writer = response.getWriter();
//        ServletOutputStream out = response.getOutputStream();
        
        //正文
        writer.write("<h1>响应内容</h1>");
        writer.flush();
        writer.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

5.4.2 HTTP响应代码

1××:信息,表示请求收到,继续处理 2××:成功,表示请求成功 3××:重定向,为完成请求客户需进一步细化请求

4××:由客户端引发的错误 5××:由服务器引发的错误

状态码说明
400Bad Request :错误请求
401Unauthorized:未经授权
404Not Found :找不到文件或目录,URL错误
405Method Not Allowed :表示这个特定的资源不允许该请求方法
500Unsupported Media Type:服务器内部错误
501Not Implemented :服务器不支持能够满足该请求的功能
503Service Unavailable:服务不可用

5.4.3向客户端输出信息

MIME类型,

类型/子类型扩展名
application/envoyevy
application/fractalsfif
application/futuresplashspl
application/htahta
application/internet-property-streamacx
application/mac-binhex40hqx
application/msworddoc
application/msworddot
application/octet-stream*
application/octet-streambin
application/octet-streamclass
application/octet-streamdms
application/octet-streamexe
application/octet-streamlha
application/octet-streamlzh
application/odaoda
application/olescriptaxs
application/pdfpdf
application/pics-rulesprf
application/pkcs10p10
application/pkix-crlcrl
application/postscriptai
application/postscripteps
application/postscriptps
application/rtfrtf
application/set-payment-initiationsetpay
application/set-registration-initiationsetreg
application/vnd.ms-excelxla
application/vnd.ms-excelxlc
application/vnd.ms-excelxlm
application/vnd.ms-excelxls
application/vnd.ms-excelxlt
application/vnd.ms-excelxlw
application/vnd.ms-outlookmsg
application/vnd.ms-pkicertstoresst
application/vnd.ms-pkiseccatcat
application/vnd.ms-pkistlstl
application/vnd.ms-powerpointpot
application/vnd.ms-powerpointpps
application/vnd.ms-powerpointppt
application/vnd.ms-projectmpp
application/vnd.ms-workswcm
application/vnd.ms-workswdb
application/vnd.ms-workswks
application/vnd.ms-workswps
application/winhlphlp
application/x-bcpiobcpio
application/x-cdfcdf
application/x-compressz
application/x-compressedtgz
application/x-cpiocpio
application/x-cshcsh
application/x-directordcr
application/x-directordir
application/x-directordxr
application/x-dvidvi
application/x-gtargtar
application/x-gzipgz
application/x-hdfhdf
application/x-internet-signupins
application/x-internet-signupisp
application/x-iphoneiii
application/x-javascriptjs
application/x-latexlatex
application/x-msaccessmdb
application/x-mscardfilecrd
application/x-msclipclp
application/x-msdownloaddll
application/x-msmediaviewm13
application/x-msmediaviewm14
application/x-msmediaviewmvb
application/x-msmetafilewmf
application/x-msmoneymny
application/x-mspublisherpub
application/x-msschedulescd
application/x-msterminaltrm
application/x-mswritewri
application/x-netcdfcdf
application/x-netcdfnc
application/x-perfmonpma
application/x-perfmonpmc
application/x-perfmonpml
application/x-perfmonpmr
application/x-perfmonpmw
application/x-pkcs12p12
application/x-pkcs12pfx
application/x-pkcs7-certificatesp7b
application/x-pkcs7-certificatesspc
application/x-pkcs7-certreqrespp7r
application/x-pkcs7-mimep7c
application/x-pkcs7-mimep7m
application/x-pkcs7-signaturep7s
application/x-shsh
application/x-sharshar
application/x-shockwave-flashswf
application/x-stuffitsit
application/x-sv4cpiosv4cpio
application/x-sv4crcsv4crc
application/x-tartar
application/x-tcltcl
application/x-textex
application/x-texinfotexi
application/x-texinfotexinfo
application/x-troffroff
application/x-trofft
application/x-trofftr
application/x-troff-manman
application/x-troff-meme
application/x-troff-msms
application/x-ustarustar
application/x-wais-sourcesrc
application/x-x509-ca-certcer
application/x-x509-ca-certcrt
application/x-x509-ca-certder
application/ynd.ms-pkipkopko
application/zipzip
audio/basicau
audio/basicsnd
audio/midmid
audio/midrmi
audio/mpegmp3
audio/x-aiffaif
audio/x-aiffaifc
audio/x-aiffaiff
audio/x-mpegurlm3u
audio/x-pn-realaudiora
audio/x-pn-realaudioram
audio/x-wavwav
image/bmpbmp
image/cis-codcod
image/gifgif
image/iefief
image/jpegjpe
image/jpegjpeg
image/jpegjpg
image/pipegjfif
image/svg+xmlsvg
image/tifftif
image/tifftiff
image/x-cmu-rasterras
image/x-cmxcmx
image/x-iconico
image/x-portable-anymappnm
image/x-portable-bitmappbm
image/x-portable-graymappgm
image/x-portable-pixmapppm
image/x-rgbrgb
image/x-xbitmapxbm
image/x-xpixmapxpm
image/x-xwindowdumpxwd
message/rfc822mht
message/rfc822mhtml
message/rfc822nws
text/csscss
text/h323323
text/htmlhtm
text/htmlhtml
text/htmlstm
text/iulsuls
text/plainbas
text/plainc
text/plainh
text/plaintxt
text/richtextrtx
text/scriptletsct
text/tab-separated-valuestsv
text/webviewhtmlhtt
text/x-componenthtc
text/x-setextetx
text/x-vcardvcf
video/mpegmp2
video/mpegmpa
video/mpegmpe
video/mpegmpeg
video/mpegmpg
video/mpegmpv2
video/quicktimemov
video/quicktimeqt
video/x-la-asflsf
video/x-la-asflsx
video/x-ms-asfasf
video/x-ms-asfasr
video/x-ms-asfasx
video/x-msvideoavi
video/x-sgi-moviemovie
x-world/x-vrmlflr
x-world/x-vrmlvrml
x-world/x-vrmlwrl
x-world/x-vrmlwrz
x-world/x-vrmlxaf
x-world/x-vrmlxof

​ 渲染普通文本

java
package com.neuedu.servlet;

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;

/**
 * 
 *   http://127.0.0.1:8080/web05/plain
 * @author Administrator
 *
 */
@WebServlet("/plain")
public class PlainServlet extends HttpServlet {
	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain;charset=utf-8");
		
		//输出内容
		PrintWriter out = response.getWriter();
		
		out.append("<h1>欢迎访问Servlet </h1>");
		out.flush();
		out.close();
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

渲染html

java
package com.neuedu.servlet;

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;

/**
 * 
 *   http://127.0.0.1:8080/web05/html
 * @author Administrator
 *
 */
@WebServlet("/html")
public class HtmlServlet extends HttpServlet {
	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		
		//输出内容
		PrintWriter out = response.getWriter();
		out.append("<h1>欢迎访问Servlet </h1>");
		out.flush();
		out.close();
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

输出文件

java
package com.neuedu.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

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

/**
 * 
 *   http://127.0.0.1:8080/web05/doc
 * @author Administrator
 *
 */
@WebServlet("/doc")
public class DocServlet extends HttpServlet {
	
//	 html  文本也好,浏览器能直接打开,直接打开打不开的 提示让你下载
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//告诉浏览器下载文件的时候 文件名字叫啥
		response.setContentType("application/msword");
		response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("下载文件.doc","utf-8") +"");
		
		
		
		
		//发送文件
		//1 读取文件
		ServletOutputStream out = response.getOutputStream();//浏览器的输出流
		FileInputStream fis = new FileInputStream("D:\\a.doc");
		byte[] bts = new byte[1024];
		int len = -1;
		while(  (len = fis.read(bts)) != -1) {//将读取的doc文件 输出到浏览器
			
			out.write(bts,0,len);
			out.flush();
			
		}
		fis.close();
		out.close();
				
		
		//2 发送给 客户端
		//输出内容
		
		
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Released under the MIT License.