Servlet学习总结
1. Servlet
1.1 Servlet 简介
- servlet是sun公司开发动态web的一门技术
- sun公司在这些api中提供了一个接口叫做:servlet,如果想要开发一个servlet程序,只需要完成两步
- 编写好一个类实现servlet接口
- 把开发好的java类部署到web服务器中
- 有两个默认实现接口(GenericServlet、HttpServlet)
把实现的servlet接口的java程序叫做,servlet
1.2 Helloservlet
-
构建一个maven项目,删掉src目录
-
关于父子工程理解:
父工程中会有:
<modules> <module>servlet-01</module> </modules>
子工程中会有:
<parent> <artifactId>hello</artifactId> <groupId>org.example</groupId> <version>1.0-SNAPSHOT</version> </parent>
父项目的jar包,子项目可以直接使用类似于多态
-
maven环境优化
- 修改web.xml为最新版
- 将maven的结构搭建完整
-
编写一个Servlet程序
-
编写一个普通类
-
实现servlet接口
public class HelloServlet extends HttpServlet { // 由于get或者post只是请求的不同方式所以可以相互调用,业务逻辑都一样 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // ServletOutputStream outputStream = resp.getOutputStream(); PrintWriter writer = resp.getWriter(); // 响应流 writer.println("hello servlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
-
-
编写Servlet的映射
为什么需要映射:我们写的的java程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务中注册我们写的Servlet, 还需要给他一个浏览器能够访问的路径
<!-- 注册servlet--> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>com.zhang.servlet.HelloServlet</servlet-class> </servlet> <!-- servlet请求路径--> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/zhang</url-pattern> </servlet-mapping> </web-a
-
配置tomcat(需添加子项目工件)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OrngFONr-1656168398302)(C:\Users\Administrator\Desktop\s1.png)]
- 启动测试
1.3 Servlet原理
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EpPfRuhm-1656168398303)(C:\Users\Administrator\Desktop\servlet.png)]
1.4 mapping
1. 一个servlet指定一个映射路径
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<!-- 一个servlet对应一个mapping:映射-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<!-- 映射的请求路径-->
<url-pattern>/zhangxin</url-pattern>
- 一个servlet指定多个映射路径
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<!-- 一个servlet对应一个mapping:映射-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<!-- 映射的请求路径-->
<url-pattern>/zhangxin</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<!-- 映射的请求路径-->
<url-pattern>/zhangxin2</url-pattern>
</servlet-mapping>
- 一个servlet指定通用路径
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<!-- 映射的请求路径-->
<url-pattern>/*</url-pattern>
</servlet-mapping>
此时不会进入默认的index界面, 可以将<url-pattern>/*</url-pattern>改为<url-pattern>/XXX/*</url-pattern>
- 指定特定后缀等
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<!-- 映射的请求路径-->
<url-pattern>*.zx</url-pattern>
</servlet-mapping>
1.5 ServletContext
web容器在启动的时候, 它会为每个web程序都创建一个ServletContext对象, 它代表了当前的web应用;
1. 共享数据
我在这个Servlet中保存的数据可以在另外一个servlet中拿到;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
// this.getInitParameter(); 初始化参数
// this.getServletConfig(); servlet配置
// this.getServletContext(); 上下文
ServletContext servletContext = this.getServletContext();
String username = "zx";
servletContext.setAttribute("username", username); // 将一个数据保存在servletContext中
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
ServletContext servletContext = this.getServletContext();
// Object username = servletContext.getAttribute("username"); 将Object强制转换为 String
String username = (String) servletContext.getAttribute("username");
resp.getWriter().println("姓名:"+ username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2. 获取初始化参数
<!-- demo:配置web应用初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
ServletContext servletContext = this.getServletContext();
// resp.setCharacterEncoding("utf-8");
// resp.setContentType("text/html");
String initParameter = servletContext.getInitParameter("url"); // 获取web.xml初始化参数中的URL
resp.getWriter().println(initParameter);
}
3. 请求转发
public class Servlet4 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
// RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/gp"); // 转发的请求路径
// requestDispatcher.forward(req, resp); // 调用forward实现请求转发
servletContext.getRequestDispatcher("/gp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
4. 读取资源文件
Properties
1. 在java目录下新建properties
1. 在resources目录下新建properties
发现: 都被打包到同一个路径下(classes), 我们俗称这个路径为classpath
思路: 需要一个文件流
username = root
password = 000000
public class Servlet5 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); // getResourceAsStream将文件转化成流
Properties prop = new Properties();
prop.load(is);
String user = prop.getProperty("username"); // 获取属性
String pwd = prop.getProperty("password"); // 获取属性
resp.getWriter().println("username:" + user + "\n" + "password:" + pwd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
1.6 HttpServletResponse
web服务器接收到客户端的http请求, 针对这个请求, 分别创建一个代表请求的HttpServletRequest对象和一个代表响的HttpServletResponse
- 如果要获取客户端请求过来的参数: 找HttpServletRequest
- 如果要获取客户端响应的信息: 找HttpServletResponse
1、简单分类
负责向浏览器发送数据的方法
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头的方法
void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentType(String var1);
void setDateHeader(String var1, long var2);
void addDateHeader(String var1, long var2);
void setHeader(String var1, String var2);
void addHeader(String var1, String var2);
void setIntHeader(String var1, int var2);
响应的状态码
int SC_CONTINUE = 100;
int SC_SWITCHING_PROTOCOLS = 101;
int SC_OK = 200;
int SC_CREATED = 201;
int SC_ACCEPTED = 202;
int SC_NON_AUTHORITATIVE_INFORMATION = 203;
int SC_NO_CONTENT = 204;
int SC_RESET_CONTENT = 205;
int SC_PARTIAL_CONTENT = 206;
int SC_MULTIPLE_CHOICES = 300;
int SC_MOVED_PERMANENTLY = 301;
int SC_MOVED_TEMPORARILY = 302;
int SC_FOUND = 302;
int SC_SEE_OTHER = 303;
int SC_NOT_MODIFIED = 304;
int SC_USE_PROXY = 305;
int SC_TEMPORARY_REDIRECT = 307;
int SC_BAD_REQUEST = 400;
int SC_UNAUTHORIZED = 401;
int SC_PAYMENT_REQUIRED = 402;
int SC_FORBIDDEN = 403;
int SC_NOT_FOUND = 404;
int SC_METHOD_NOT_ALLOWED = 405;
int SC_NOT_ACCEPTABLE = 406;
int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
int SC_REQUEST_TIMEOUT = 408;
int SC_CONFLICT = 409;
int SC_GONE = 410;
int SC_LENGTH_REQUIRED = 411;
int SC_PRECONDITION_FAILED = 412;
int SC_REQUEST_ENTITY_TOO_LARGE = 413;
int SC_REQUEST_URI_TOO_LONG = 414;
int SC_UNSUPPORTED_MEDIA_TYPE = 415;
int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
int SC_EXPECTATION_FAILED = 417;
int SC_INTERNAL_SERVER_ERROR = 500;
int SC_NOT_IMPLEMENTED = 501;
int SC_BAD_GATEWAY = 502;
int SC_SERVICE_UNAVAILABLE = 503;
int SC_GATEWAY_TIMEOUT = 504;
int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
2、常见应用
1. 向浏览器输出消息(文档前部分内容)
2. 下载文件
1. 获取下载文件路径
2. 下载的文件名
3. 让浏览器能够支持下载我们需要的东西
4. 获取下载文件的输入流
5. 创建缓冲区
6. 获取OutputStream
7. 将FileOutputStream写入到缓冲区
8. 使用OutputStream将缓冲区的数据输出到客户端
```java
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. 获取下载文件路径
String realPath = "C:\\Users\\Administrator\\Desktop\\demo2\\hello\\out\\artifacts\\response_Web_exploded\\WEB-INF\\classes\\saber.jpg";
System.out.println("下载文件的路径" + realPath);
// 2. 下载的文件名
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
// 3. 让浏览器能够支持(Content-Disposition)下载我们需要的东西, 中文文件名用URLEncoder.encode, 否则有可能乱码
// resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName ,"utf-8"));
// 4. 获取下载文件的输入流
FileInputStream fileInputStream = new FileInputStream(realPath);
// 5. 创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
// 6. 获取OutputStream
ServletOutputStream outputStream = resp.getOutputStream();
// 7. 将FileOutputStream写入到缓冲区
while ((len = fileInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
outputStream.close();
fileInputStream.close();
// 8. 使用OutputStream将缓冲区的数据输出到客户端
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3、验证码功能
验证码怎么来的?
- 前端实现
- 后端实现,需要用到java的图片类, 生成一个图片
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 如何让浏览器5秒自动刷新一次;
resp.setHeader("refresh", "5");
// 在内存中创建一个图片
BufferedImage bufferedImage = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
// 得到图片
Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
// 设置图片背景颜色
graphics.setColor(Color.white);
graphics.fillRect(0, 0, 80, 20);
// 给图片写入数据
graphics.setColor(Color.blue);
graphics.setFont(new Font(null, Font.ITALIC,20));
graphics.drawString(makeNum(),0,20);
// 告诉浏览器, 这个请求的打开方式
resp.setContentType("image/jpg");
// 网站存在缓存, 不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache"); // no-Cache不缓存
resp.setHeader("Pragma","no-cache");
// 把图片写给浏览器
ImageIO.write(bufferedImage,"jpg",resp.getOutputStream());
}
// 生成随机数
private String makeNum() {
Random random = new Random();
String num = random.nextInt(9999) + ""; // 加入空格让生成随机数变成字符串
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4- num.length(); i++) { // 保证字符串一定是四位(补零)
sb.append("0");
}
String s = sb.toString() + num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
4、实现重定向
一个web资源收到客户端请求之后, 它会通知客户端去访问另外一个web资源, 这个过程叫做重定向
常见常见:
- 用户登录
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/resp/img");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
重定向与转发区别?
相同点:
- 页面发生跳转
不同点:
- 请求转发的时候URL不会产生变化,重定向的时候会发生变化 。转发 307,重定向 302
1.7 HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器, Http请求的所有信息会被封装到HttpServletRequest中,通过HttpServletRequest获取客户端的所有信息
1、获取前端传递参数
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NcEzJVfF-1656168398304)(C:\Users\Administrator\Desktop\getParameter.png)]
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobby = req.getParameterValues("hobby");
System.out.println("--------------------------");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobby));
System.out.println("--------------------------");
// 通过请求转发
// req.getRequestDispatcher(req.getContextPath()+"/success.jsp").forward(req,resp);
req.getRequestDispatcher("/success.jsp").forward(req,resp); // 请求转发不需要带项目名字
// forward()该方法用于将请求从一个 Servlet 传递给另一个 Web 资源。在 Servlet 中,可以对请求做一个初步处理,然后通过调用这个方法,
// 将请求传递给其他资源进行响应。需要注意的是,该方法必须在响应提交给客户端之前被调用,否则将抛出 IllegalStateException 异常
}
}