Servlet
Servlet简介
- Servlet是sun公司开发动态web的一门技术
- Sun公司在这些API中提供了一个接口叫做Servlet,如果你想开发一个Servlet程序,只需要完成两个小步骤
- 编写一个类,实现Servlet接口
- 把开发好的java类部署到web服务器中
- 把实现了Servlet接口的java程序,叫做Servlet。
HelloServlet
HelloServlet.java
package edu.cqupt.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.print("<h1>Hello Servlet!</h1>");
System.out.println("----------------------------------");
System.out.println("The First Servlet is running.");
System.out.println("-----------------------------------");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
配置web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<servlet>
<servlet-name>home</servlet-name>
<servlet-class>edu.cqupt.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
</web-app>
Servlet原理
Mapping问题
- 一个Servlet可以指定一个映射路径
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
- 一个Servlet可以指定多个映射路径
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/home2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/home3</url-pattern>
</servlet-mapping>
- 一个Servlet可以指定通用映射路径
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/home/*</url-pattern>
</servlet-mapping>
- 一个Servlet可以指定默认映射路径(一般将默认的映射路径设置为404页面,找不到就走到默认路径)
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
- 一个Servlet可以指定一些后缀或者前缀等...
<!-- *前面不能加任何项目映射-->
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>*.qingjiang</url-pattern>
</servlet-mapping>
- 优先级
- 指定固有的映射路径优先级最高,找不到,就会走默认的处理请求
ServletContext
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;
共享数据
- 在一个Servlet中,可以在另一个Servlet中拿到,实现了Servlet之间的通信
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Hello");
//this.getInitParameter() 初始化参数
//this.getServletConfig() Servlet配置
//this.getServletContext() Servlet上下文
ServletContext context1 = this.getServletContext();
//将一个数据保存到 ServletContext中,名字为:username,值为username
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
String username = "shilin.z";
context1.setAttribute("username",username);
}
@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 {
ServletContext context2 = this.getServletContext();
String username = (String) context2.getAttribute("username");
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().print("s1传输的内容: " + username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>edu.cqupt.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getc</servlet-name>
<servlet-class>edu.cqupt.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getc</servlet-name>
<url-pattern>/getc</url-pattern>
</servlet-mapping>
测试结果:
先 http://localhost:8080/s2/hello, 不然输出为null
获取初始化参数
<!-- 配置一些web应用的初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://local:3306/mybatis</param-value>
</context-param>
<servlet>
<servlet-name>getp</servlet-name>
<servlet-class>edu.cqupt.servlet.Servlet03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getp</servlet-name>
<url-pattern>/getp</url-pattern>
</servlet-mapping>
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
请求转发(不是重定向)
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入了Servlet04");
ServletContext context = this.getServletContext();
//RequestDispatcher requestDispatcher = context.getRequestDispatcher("/getp"); //转发的请求路径
//requestDispatcher.forward(req,resp); //调用forward实现请求转发
context.getRequestDispatcher("/getp").forward(req,resp);
}
<servlet>
<servlet-name>sd4</servlet-name>
<servlet-class>edu.cqupt.servlet.Servlet04</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd4</servlet-name>
<url-pattern>/sd4</url-pattern>
</servlet-mapping>
测试结果:
读取资源文件
- Properties类
- 在java目录下新建properties
- 在resources目录下新建properties
- 发现:都被打包到了同一路径下:classes,我们俗称路径为classpath
需要在本项目的pom.xml中配置resources
<!-- 在bulid中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
需要一个文件流:
Servlet05.java
public class Servlet05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获得文件流
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties prop = new Properties();
prop.load(is);
String user = prop.getProperty("username");
String pwd = prop.getProperty("password");
resp.getWriter().print(user + ":" + pwd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
db.properties
username=root
password=123456
web.xml
<servlet>
<servlet-name>sd5</servlet-name>
<servlet-class>edu.cqupt.servlet.Servlet05</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd5</servlet-name>
<url-pattern>/sd5</url-pattern>
</servlet-mapping>
HttpServletResponse
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,一个代表响应的HttpServletResponse对象;
- 如果要获取客户端请求过来的参数:找HttpServletRequset对象
- 如果要给客户端响应一些信息: 找HttpServletResponse对象
简单分类
负责向浏览器发送数据的方法
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头的方法**
void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long 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);
void addIntHeader(String var1, int var2);
响应的状态码
int SC_CONTINUE = 100;
int SC_OK = 200;
int SC_MULTIPLE_CHOICES = 300;
int SC_NOT_FOUND = 404;
int SC_INTERNAL_SERVER_ERROR = 500;
.....
常见应用
向浏览器输出消息
(resp.getwriter().print())
下载文件
- 获取下载文件的路径
- 下载的文件名
- 设置想办法让浏览器能够支持下载我们需要的东西
- 获取下载文件的输入流
- 创建缓冲区
- 获取OutputStream对象
- 将FileOutputStream流写入到buffer缓冲区
- 使用OutputStream将缓冲区中的数据输出到客户端
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.获取下载文件的路径
//String realPath = this.getServletContext().getRealPath("/dali.jpg");
String realPath = "E:\CodePlace\Java\idea\狂神说Java\Maven\javawebMaven\javaweb\servlet-03-response\target\classes\dali.jpg";
System.out.println("下载文件的路径为:" + realPath);
// 2.下载的文件名
String filename = realPath.substring(realPath.lastIndexOf("\") + 1);
// 3.设置想办法让浏览器能够支持下载我们需要的东西
resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename,"UTF-8"));
// 4.获取下载文件的输入流
FileInputStream in = new FileInputStream(realPath);
// 5.创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
// 6.获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
// 7.将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端
while((len=in.read(buffer))!=-1){
out.write(buffer,0,len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
验证码功能
验证怎么来的?
- 前端实现
- 后端实现,需要用到 java 的图片类,生成一个图片
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 如何让浏览器3秒自动刷新一次;
resp.setHeader("refresh","3");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_3BYTE_BGR);
//得到图片
Graphics2D g = (Graphics2D)image.getGraphics();
// 设置图片的背景颜色
g.setColor(Color.white);
g.fillRect(0,0,80,20);
//给图片写数据
g.setColor(Color.blue);
g.setFont(new Font("宋体",Font.BOLD,20));
g.drawString(makeNum(),0,20);
// 告诉浏览器,这个请求用图片的方式打开
resp.setContentType("image/jpeg");
//网站存在缓存,不让浏览器缓存
resp.setDateHeader("expires", -1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
// 把图片写给浏览器
boolean write = ImageIO.write(image, "jpg",resp.getOutputStream());
}
//生产随机数
private String makeNum(){
Random random = new Random();
String num = random.nextInt(9999999) + "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 7 - num.length() ; i++) { //保证生成的随机数只有7位
sb.append("0"); //不足7位用0填充
}
num = sb.toString() + num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>img</servlet-name>
<servlet-class>edu.cqupt.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>img</servlet-name>
<url-pattern>/img</url-pattern>
</servlet-mapping>
实现重定向
B一个web资源收到客户端请求后,他会通知客户端去访问另外一个web资源,这个过程叫重定向。
** 常见场景:**
- 用户登录:登录成功,跳转到另外的页面。
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setHeader("Location", "/s3/img");
// resp.setStatus(302);
resp.sendRedirect("/s3/img");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
面试题:请求和重定向的区别?
- 相同点
- 页面都会跳转
- 不同点
- 请求转发,url地址不会发生变化 307
- 重定向,url地址会发生变化 302
public class RequestTestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入这个请求了----");
// 处理请求
String username = req.getParameter("username");
String pwd = req.getParameter("password");
System.out.println(username + ":" + pwd);
// 重定向一定要注意,路径问题,否则就会404
resp.sendRedirect("/s3/home.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1> Success ! </h1>
</body>
</html>
HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,Http请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest方法,获得客户端的所有信息。
获取前端传递的参数和请求转发
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
req.setCharacterEncoding("utf-8");
//获取前端传递参数
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobbies");
System.out.println("---------------");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbies));
System.out.println("---------------");
//重定向
// resp.sendRedirect("/s4/success.jsp");
//通过请求转发
System.out.println(req.getContextPath());
//这里的/代表当前的web应用
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}