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应用的路径
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
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
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输出流中字符的编码方式,它的优先权最低,在已经使用前两种方法中的一个设置了编码方式以后,它将被覆盖而不再起作用。
- response.setCharacterEncoding("UTF-8");
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××:由服务器引发的错误
状态码 | 说明 |
---|---|
400 | Bad Request :错误请求 |
401 | Unauthorized:未经授权 |
404 | Not Found :找不到文件或目录,URL错误 |
405 | Method Not Allowed :表示这个特定的资源不允许该请求方法 |
500 | Unsupported Media Type:服务器内部错误 |
501 | Not Implemented :服务器不支持能够满足该请求的功能 |
503 | Service Unavailable:服务不可用 |
5.4.3向客户端输出信息
MIME类型,
类型/子类型 | 扩展名 |
---|---|
application/envoy | evy |
application/fractals | fif |
application/futuresplash | spl |
application/hta | hta |
application/internet-property-stream | acx |
application/mac-binhex40 | hqx |
application/msword | doc |
application/msword | dot |
application/octet-stream | * |
application/octet-stream | bin |
application/octet-stream | class |
application/octet-stream | dms |
application/octet-stream | exe |
application/octet-stream | lha |
application/octet-stream | lzh |
application/oda | oda |
application/olescript | axs |
application/pdf | |
application/pics-rules | prf |
application/pkcs10 | p10 |
application/pkix-crl | crl |
application/postscript | ai |
application/postscript | eps |
application/postscript | ps |
application/rtf | rtf |
application/set-payment-initiation | setpay |
application/set-registration-initiation | setreg |
application/vnd.ms-excel | xla |
application/vnd.ms-excel | xlc |
application/vnd.ms-excel | xlm |
application/vnd.ms-excel | xls |
application/vnd.ms-excel | xlt |
application/vnd.ms-excel | xlw |
application/vnd.ms-outlook | msg |
application/vnd.ms-pkicertstore | sst |
application/vnd.ms-pkiseccat | cat |
application/vnd.ms-pkistl | stl |
application/vnd.ms-powerpoint | pot |
application/vnd.ms-powerpoint | pps |
application/vnd.ms-powerpoint | ppt |
application/vnd.ms-project | mpp |
application/vnd.ms-works | wcm |
application/vnd.ms-works | wdb |
application/vnd.ms-works | wks |
application/vnd.ms-works | wps |
application/winhlp | hlp |
application/x-bcpio | bcpio |
application/x-cdf | cdf |
application/x-compress | z |
application/x-compressed | tgz |
application/x-cpio | cpio |
application/x-csh | csh |
application/x-director | dcr |
application/x-director | dir |
application/x-director | dxr |
application/x-dvi | dvi |
application/x-gtar | gtar |
application/x-gzip | gz |
application/x-hdf | hdf |
application/x-internet-signup | ins |
application/x-internet-signup | isp |
application/x-iphone | iii |
application/x-javascript | js |
application/x-latex | latex |
application/x-msaccess | mdb |
application/x-mscardfile | crd |
application/x-msclip | clp |
application/x-msdownload | dll |
application/x-msmediaview | m13 |
application/x-msmediaview | m14 |
application/x-msmediaview | mvb |
application/x-msmetafile | wmf |
application/x-msmoney | mny |
application/x-mspublisher | pub |
application/x-msschedule | scd |
application/x-msterminal | trm |
application/x-mswrite | wri |
application/x-netcdf | cdf |
application/x-netcdf | nc |
application/x-perfmon | pma |
application/x-perfmon | pmc |
application/x-perfmon | pml |
application/x-perfmon | pmr |
application/x-perfmon | pmw |
application/x-pkcs12 | p12 |
application/x-pkcs12 | pfx |
application/x-pkcs7-certificates | p7b |
application/x-pkcs7-certificates | spc |
application/x-pkcs7-certreqresp | p7r |
application/x-pkcs7-mime | p7c |
application/x-pkcs7-mime | p7m |
application/x-pkcs7-signature | p7s |
application/x-sh | sh |
application/x-shar | shar |
application/x-shockwave-flash | swf |
application/x-stuffit | sit |
application/x-sv4cpio | sv4cpio |
application/x-sv4crc | sv4crc |
application/x-tar | tar |
application/x-tcl | tcl |
application/x-tex | tex |
application/x-texinfo | texi |
application/x-texinfo | texinfo |
application/x-troff | roff |
application/x-troff | t |
application/x-troff | tr |
application/x-troff-man | man |
application/x-troff-me | me |
application/x-troff-ms | ms |
application/x-ustar | ustar |
application/x-wais-source | src |
application/x-x509-ca-cert | cer |
application/x-x509-ca-cert | crt |
application/x-x509-ca-cert | der |
application/ynd.ms-pkipko | pko |
application/zip | zip |
audio/basic | au |
audio/basic | snd |
audio/mid | mid |
audio/mid | rmi |
audio/mpeg | mp3 |
audio/x-aiff | aif |
audio/x-aiff | aifc |
audio/x-aiff | aiff |
audio/x-mpegurl | m3u |
audio/x-pn-realaudio | ra |
audio/x-pn-realaudio | ram |
audio/x-wav | wav |
image/bmp | bmp |
image/cis-cod | cod |
image/gif | gif |
image/ief | ief |
image/jpeg | jpe |
image/jpeg | jpeg |
image/jpeg | jpg |
image/pipeg | jfif |
image/svg+xml | svg |
image/tiff | tif |
image/tiff | tiff |
image/x-cmu-raster | ras |
image/x-cmx | cmx |
image/x-icon | ico |
image/x-portable-anymap | pnm |
image/x-portable-bitmap | pbm |
image/x-portable-graymap | pgm |
image/x-portable-pixmap | ppm |
image/x-rgb | rgb |
image/x-xbitmap | xbm |
image/x-xpixmap | xpm |
image/x-xwindowdump | xwd |
message/rfc822 | mht |
message/rfc822 | mhtml |
message/rfc822 | nws |
text/css | css |
text/h323 | 323 |
text/html | htm |
text/html | html |
text/html | stm |
text/iuls | uls |
text/plain | bas |
text/plain | c |
text/plain | h |
text/plain | txt |
text/richtext | rtx |
text/scriptlet | sct |
text/tab-separated-values | tsv |
text/webviewhtml | htt |
text/x-component | htc |
text/x-setext | etx |
text/x-vcard | vcf |
video/mpeg | mp2 |
video/mpeg | mpa |
video/mpeg | mpe |
video/mpeg | mpeg |
video/mpeg | mpg |
video/mpeg | mpv2 |
video/quicktime | mov |
video/quicktime | qt |
video/x-la-asf | lsf |
video/x-la-asf | lsx |
video/x-ms-asf | asf |
video/x-ms-asf | asr |
video/x-ms-asf | asx |
video/x-msvideo | avi |
video/x-sgi-movie | movie |
x-world/x-vrml | flr |
x-world/x-vrml | vrml |
x-world/x-vrml | wrl |
x-world/x-vrml | wrz |
x-world/x-vrml | xaf |
x-world/x-vrml | xof |
渲染普通文本
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
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);
}
}
输出文件
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);
}
}
