目录
resp.setContentType("text/html");
resp.setContentType("text/plain");
resp.setContentType("application/json")
resp.setContentType("image/jpeg")
resp.setContentType("image/gif")
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
servletContext.getInitParameter("key")
servletContext.getInitParameterNames()
servletContext.setAttribute("key",ObjectValue)
servletContext.getAttribute("key")
servletContext.removeAttribute("key")
servletConfig.getInitParameter("key")
servletConfig.getInitParameterNames()
Tomcat有各种对象,处理请求的HttpServletRequest对象,产生响应的HttpServletResponse对象,全局的ServletContext对象,获取配置信息的ServletConfig对象
req.getRequestURL()
返回客户端浏览器发出请求时的完整URL。
req.getRequestURI()
返回请求行中指定资源部分。
req.getRemoteAddr()
返回发出请求的客户机的IP地址。
req.getLocalAddr()
返回WEB服务器的IP地址。
req.getLocalPort()
返回WEB服务器处理Http协议的连接器所监听的端口。
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- resp.setContentType("text/plain;charset=utf-8");
-
- //获取请求信息
- //返回客户端发出请求时的URI
- String uri = req.getRequestURI();
- //返回客户端发出请求的URL
- StringBuffer url = req.getRequestURL();
- //返回服务端的监听端口
- int port = req.getLocalPort();
- //返回服务端的IP地址
- String localAddr = req.getLocalAddr();
- //返回客户端的IP地址
- String remoteAddr = req.getRemoteAddr();
-
- PrintWriter pw = resp.getWriter();
- pw.println("返回客户端发出请求时的URI:"+uri);
- pw.println("返回客户端发出请求的URL:"+url);
- pw.println("返回服务端的监听端口:"+port);
- pw.println("返回服务端的IP地址:"+localAddr);
- pw.println("返回客户端的IP地址:"+remoteAddr);
-
- pw.flush();
- pw.close();
- }
注意:编写完Servlet过后一定要在web.xml文件中对Servlet和URL的绑定
编写Servlet获取表单数据
- public class TestRequest extends HttpServlet {
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置请求编码
- req.setCharacterEncoding("utf-8");
- //设置响应编码
- resp.setContentType("text/plain;charset=utf-8");
-
- //获取表单数据
- String un = req.getParameter("username");
- String pwd = req.getParameter("password");
-
- PrintWriter pw = resp.getWriter();
- pw.println("username:"+un);
- pw.println("password:"+pwd);
- }
- }
我们这里通过addUser.html来演示表单数据
通过访问addUser.html提交数据给url:testUser.do绑定的Servlet


通过getParameter("name")这个方法,一个name只能获取一个value,那么如果是复选框的话有多个value数据,此时就需要使用getParameterValues("name")方法获取name对应的所有value
- public class TestRequest extends HttpServlet {
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置请求编码
- req.setCharacterEncoding("utf-8");
- //设置响应编码
- resp.setContentType("text/plain;charset=utf-8");
-
- PrintWriter pw = resp.getWriter();
-
- //获取复选框数据
- String[] userlike = req.getParameterValues("userlike");
-
- pw.println("userlike:"+Arrays.toString(userlike));
-
- pw.flush();
- pw.close();
- }
- }
我们还是使用addUser.html文件进行测试



以上都是通过一个name对应一个value或多个value,那么如果有多个name,如何获取呢?
通过getParameterNames()方法获取所有name
- public class TestRequest extends HttpServlet {
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置请求编码
- req.setCharacterEncoding("utf-8");
- //设置响应编码
- resp.setContentType("text/plain;charset=utf-8");
-
- PrintWriter pw = resp.getWriter();
-
- //获取所有name
- Enumeration
enumeration = req.getParameterNames(); - while(enumeration.hasMoreElements()){
- String name = enumeration.nextElement();
- if ("userlike".equals(name)){
- String[] value = req.getParameterValues(name);
- pw.println(name+":"+Arrays.toString(value));
- }
- else {
- String value = req.getParameter(name);
- pw.println(name+":"+value);
- }
- }
- }
- }
我们还是使用addUser.html文件进行测试



看了上面如何获取请求数据,大家可能会有一些疑问,因为最上面一直都有两行代码,一个是设置请求编码,一个是设置响应编码,我们这里先讲一下请求编码,响应编码在讲HttpServletResponse对象的时候讲
通过HttpServletRequest对象的setCharacterEncoding("编码")方法设置编码
代码我就不演示了,这里讲一下为什么要设置请求编码:
因为Tomcat在获取请求数据时,通过ISO8859-1的方式将请求数据字节转为字符,而ISO8859-1只支持英文和数字,如果此时请求数据中有中文的话,那么中文通过ISO8859-1的方式将字节转为字符此时就会出现乱码的问题
所以需要通过HttpServletRequest对象下的setCharacterEncoding("编码")的方法,给定编码格式,告诉Tomcat,请求数据该由什么编码的格式转换
通过请求头中的key获取对应的value
请求头中有很多的信息,我们这里获取Accept-Language获取对应的value

- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置请求编码
- req.setCharacterEncoding("utf-8");
- //设置响应编码
- resp.setContentType("text/plain;charset=utf-8");
-
- PrintWriter pw = resp.getWriter();
-
- //通过请求头中的key获取对应的value
- String language = req.getHeader("Accept-Language");
- pw.println("Accept-language:" + language);
- pw.flush();
- pw.close();
- }
我们还是使用addUser.html文件进行测试



学完了如何使用HttpServletRequest获取请求信息,获取表单数据,获取多选框数据,获取所有提交的数据,设置请求编码,获取请求信息
那么我们也需要了解一下该对象的生命周期,通过生命周期更加深刻的了解该对象
当有请求到达Tomcat时,Tomcat会创建HttpServletRequest对象,并将该对象通过参数的方式传递到我们的Servlet中,当请求处理完毕并产生响应过后该对象的生命周期结束
该方法可通过MIME-Type设置响应类型。
| Type | Meaning |
| application/msword | Microsoft Word document |
| application/octet-stream | Unrecognized or binary data |
| application/pdf | Acrobat (.pdf) file |
| application/postscript | PostScript file |
| application/vnd.lotus-notes | Lotus Notes file |
| application/vnd.ms-excel | Excel spreadsheet |
| application/vnd.ms-powerpoint | PowerPoint presentation |
| application/x-gzip | Gzip archive |
| application/x-java-archive | JAR file |
| application/x-java-serialized-object | Serialized Java object |
| application/x-java-vm | Java bytecode (.class) file |
| application/zip | Zip archive |
| application/json | JSON |
| audio/basic | Sound file in .au or .snd format |
| audio/midi | MIDI sound file |
| audio/x-aiff | AIFF sound file |
| audio/x-wav | Microsoft Windows sound file |
| image/gif | GIF image |
| image/jpeg | JPEG image |
| image/png | PNG image |
| image/tiff | TIFF image |
| image/x-xbitmap | X Windows bitmap image |
| text/css | HTML cascading style sheet |
| text/html | HTML document |
| text/plain | Plain text |
| text/xml | XML |
| video/mpeg | MPEG video clip |
| video/quicktime | QuickTime video clip |
MIME对象有很多但是常用的只有那么几种,所有我们通过字符型响应和字节型响应记忆常用的MIME类型
设置响应类型为文本型,内容还有html字符串,是浏览器默认的响应类型(浏览器可识别html和文本)
- public class TestRequest extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- this.doPost(req,resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置请求编码
- req.setCharacterEncoding("utf-8");
- //设置响应编码
- resp.setContentType("text/html;charset=utf-8");
-
- PrintWriter pw = resp.getWriter();
- pw.println("");
- pw.println("");
- pw.println("");
- pw.println("");
- pw.println("
Document "); - pw.println("");
- pw.println("");
- pw.println("Hello World");
- pw.println("");
- pw.println("");
-
- pw.flush();
- pw.close();
- }
- }
通过地址栏直接访问该servlet,大家可以发现这个hello world拥有了css样式,说明设置响应类型成功了

设置响应类型为文本型,内容是普通文本
还是上面那个例子,如果将响应类型改为文本型的话,浏览器就不会识别html标签,而是以文本的方式展现出来
设置响应类型为JSON格式的字符串
前面响应的测试忘记换类了,现在换一个TestResponse类,抱歉抱歉
常见的字节型响应:
设置响应类型为图片类型,图片类型为jpeg或jpg格式。
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置请求编码
- req.setCharacterEncoding("utf-8");
- //设置响应编码
- resp.setContentType("image/jpeg;charset=utf-8");
-
- //读取图片
- FileInputStream fis = new FileInputStream("C:\\Users\\27645\\IdeaProjects\\ServletDemo\\web\\image\\t.jpg");
- byte[] bytes = new byte[1024];
- //获取响应流
- OutputStream os = resp.getOutputStream();
- //读取文件,一次读取1024个字节
- while(fis.read(bytes) != -1){
- os.write(bytes);
- }
- os.flush();
- os.close();
- }

设置响应类型为图片类型,图片类型为gif格式。
前面的请求编码讲过,Tomcat在接收数据的时候会通过ISO8859-1的编码格式将字节转为字符,而ISO8859-1只支持英文和数字,所以如果有中文的话需要设置请求编码
但是Tomcat在接收请求时将数据以ISO8859-1的编码格式将字节转为字符,而在响应时Tomcat也是默认使用ISO8859-1的方式响应给客户端,而如果我们有中文需要响应给客户端,此时就需要设置响应编码,告诉Tomcat该以什么编码格式将字符转为字节
设置响应编码有两种方式
不仅发送到浏览器的内容会使用UTF-8编码,而且还通知浏览器使用UTF-8编码方式进行显示。所以总能正常显示中文
仅仅是发送的浏览器的内容是UTF-8编码的,至于浏览器是用哪种编码方式显示不管。 所以当浏览器的显示编码方式不是UTF-8的时候,就会看到乱码,需要手动指定浏览器编码。
重定向响应会在响应头中的Location设置给定的URL。客户端浏览器在解析响应头后发现状态码为302时,自动向Location中的URL发送请求。
- public class TestResponse extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- this.doPost(req,resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置请求编码
- req.setCharacterEncoding("utf-8");
- //设置响应编码
- resp.setContentType("text/html;charset=utf-8");
-
- //设置重定向响应
- resp.sendRedirect("http://www.baidu.com");
-
-
- }
- }

看似我们只有一次请求一次响应,其实是有两次请求两次响应的

在实现文件下载时,我们需要在响应头中添加附加信息。
以key,value的方式添加
response.addHeader("Content-Disposition", "attachment; filename="+文件名);
attachment就是附件的意思,filename需要给定文件名
- public class TestResponse extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- this.doPost(req,resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置请求编码
- req.setCharacterEncoding("utf-8");
- //设置响应编码
- resp.setContentType("text/html;charset=utf-8");
-
- File file = new File("C:\\Users\\27645\\IdeaProjects\\ServletDemo\\web\\image\\t.jpg");
- //文件下载
- resp.addHeader("Content-Disposition","attachment;filename="+file.getName());
-
- FileInputStream fis = new FileInputStream(file);
- byte[] bytes = new byte[1024];
- OutputStream os = resp.getOutputStream();
- //文件读取与响应
- while(fis.read(bytes) != -1){
- os.write(bytes);
- }
- os.flush();
- os.close();
-
- }
- }
访问该url后浏览器会直接下载附件

在响应头中设置文件下载时,需要给定文件名,如果该文件名是中文的,那么就会出现乱码的问题因为我们的是“gbk”编码,而Tomcat在传输时会基于“iso8859-1”的方式将字符转为字节,那么此时中文就是乱码
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置请求编码
- req.setCharacterEncoding("utf-8");
- //设置响应编码
- resp.setContentType("text/html;charset=utf-8");
-
- File file = new File("C:\\Users\\27645\\IdeaProjects\\ServletDemo\\web\\image\\小熊.jpg");
- //文件下载
- resp.addHeader("Content-Disposition","attachment;filename="+file.getName());
-
- FileInputStream fis = new FileInputStream(file);
- byte[] bytes = new byte[1024];
- OutputStream os = resp.getOutputStream();
- //文件读取与响应
- while(fis.read(bytes) != -1){
- os.write(bytes);
- }
- os.flush();
- os.close();
-
- }

所以我们需要通过URLEncoding类下的静态方法encode("文件名","编码格式")将我们的文件名以指定编码格式编码
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置请求编码
- req.setCharacterEncoding("utf-8");
- //设置响应编码
- resp.setContentType("text/html;charset=utf-8");
-
- File file = new File("C:\\Users\\27645\\IdeaProjects\\ServletDemo\\web\\image\\小熊.jpg");
- //文件下载
- resp.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(file.getName(),"utf-8"));
-
- FileInputStream fis = new FileInputStream(file);
- byte[] bytes = new byte[1024];
- OutputStream os = resp.getOutputStream();
- //文件读取与响应
- while(fis.read(bytes) != -1){
- os.write(bytes);
- }
- os.flush();
- os.close();
-
- }

ServletContext官方叫Servlet上下文。服务器会为每一个Web应用创建一个ServletContext对象。这个对象全局唯一,而且Web应用中的所有Servlet都共享这个对象。所以叫全局应用程序共享对象。
ServletContext对象的作用
GenericServlet有一个方法叫getServletContext(),通过该方法可获取ServletContext对象
但是你的类必须继承或者间接继承该抽象类

Java的特点就是跨平台,而当我们需要某个文件的路径名时,如果在window系统中,这个文件在某个盘符下是可以正常访问的,但是如果在linux系统中是没有盘符的概念的,所以我们需要使用相对的路径转为绝对路径这种方法,解决跨平台的问题
ServletContext对象下有一个getRealPath("相对路径")
该方法可以将相对路径转为绝对路径,但是该路径对应的文件必须为web目录下或者在web目录的子目录中,但是不能放在WEB-INF目录
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置请求编码
- req.setCharacterEncoding("utf-8");
- //设置响应编码
- resp.setContentType("image/jpeg;charset=utf-8");
-
- //获取ServletContext对象
- ServletContext sc = this.getServletContext();
- String absolute = sc.getRealPath("image/小熊.jpg");
- FileInputStream fis = new FileInputStream(absolute);
- byte[] bytes = new byte[1024];
-
- OutputStream os = resp.getOutputStream();
- while(fis.read(bytes) != -1){
- os.write(bytes);
- }
- os.flush();
- os.close();
-
- }

servletContext.getServerInfo()
返回Servlet容器的名称和版本号
servletContext.getMajorVersion()
返回Servlet容器所支持Servlet的主版本号。
servletContext.getMinorVersion()
返回Servlet容器所支持Servlet的副版本号。
获取web.xml文件中的信息
该方法可以读取web.xml文件中标签中的配置信息。(value)
该方法可以读取web.xml文件中所有param-name标签中的值。(name)
注意:context-param必须在web-app下面

向全局容器中存放数据。
从全局容器中获取数据。
根据key删除全局容器中的value。
例子:

ServletConfig对象对应web.xml文件中的节点。当Tomcat初始化一个Servlet时,会将该Servlet的配置信息,封装到一个ServletConfig对象中。我们可以通过该对象读取节点中的配置信息
该方法可以读取web.xml文件中标签中标签中的配置信息。(value)
该方法可以读取web.xml文件中当前标签中所有标签中的值。(name)