6.Servlet
6.Servlet简介
- servlet就是sun公司开发动态web的一门技术
- sun在这些API中提供一个接口叫做:Servlet,如果想开发一个servlet程序,只需完成两个小步骤:
- 编写一个类,实现servlet接口
- 把开发好的Java类部署到web服务器中
把实现了servlet接口的Java程序叫做,servlet
6.2 Hello Servlet
servlet接口sun公司有两个默认的实现类:HttpServlet
1.建立Maven
构建一个普通的Maven项目,删掉里面的src目录,在这个项目里建立moudel;这个空的工程就是Maven主工程;
2.Maven父子工程
关于Maven父子工程的理解:
? 父项目中会有
<modules>
<module>servlet01</module>
</modules>
3.Maven 环境优化
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
</web-app>
4.编写一个servlet程序
? 1.编写一个普通类
? 2.实现Service接口,直接继承HttpService
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.print("hello,servlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
5.编写servlet映射
? 为什么需要映射:写的是Java程序,但是需要通过浏览器访问,而浏览器需要连接web服务器,所以需要在web服务中注册写的servlet,还需要给他一个浏览器能够访问的路径。
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.par.servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>hello</url-pattern>
</servlet-mapping>
6.配置Tomcat
? 见5.6
? 注意:配置项目发布的路径就可以了
7.启动测试
6.3 servlet原理
servlet是由web服务器调用,web服务器在收到浏览器请求之后,会:
6.4 Mapping问题
1.一个Servlet可以指定一个映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
2.一个Servlet可以指定多个映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello3</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello4</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello5</url-pattern>
</servlet-mapping>
3.一个Servlet可以指定通用映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
4.默认请求路径(少用)
//默认请求路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
5.可以指定一些后缀或者前缀
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
6.优先级问题
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求路径;
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>com.par.servlet.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
6.5 ServletContext
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用
1.共享数据
我在这个servlet中保存的数据,可以在另一个servle中拿到;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username="大学";
context.setAttribute("username",username);
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = (String) context.getAttribute("username");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print("名字:"+username);
}
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.par.servlet.Servlet01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>get</servlet-name>
<servlet-class>com.par.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>get</servlet-name>
<url-pattern>/get</url-pattern>
</servlet-mapping>
2.获取初始化参数
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3066</param-value>
</context-param>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
3.请求转发
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
4.读取资源文件
Properties
-
在Java目录下创建Properties -
在recourse目录下创建Properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath;
思路:需要一个文件流
6.6 HttpServletResponse
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表相应的一个HttpServletResponse对象;
- 如果要获取客户端请求过来的参数:找HttpServletRequest
- 如果要给客户端一些信息:找HttpServletResponse
1.常见应用
- 向浏览器输出消息
- 下载文件
- 要获取下载文件的路径
- 下载文件名
- 设置想办法让浏览器支持下载需要的东西
- 获取下载文件的输入流
- 创建缓冲区
- 获取OutputStream
- 将FileOutputStream流写入到buffer缓冲区
- 使用OutputStream将缓冲区的数据输出到客户端!
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String realPath = "E:\\IDEAA\\javaweb-02-servlet\\response\\src\\main\\resources\\1.png";
System.out.println("下载文件的路径:"+realPath);
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
resp.setHeader("Content-Disposition","attachment;filename"+fileName);
FileInputStream in = new FileInputStream(realPath);
int len =0;
byte[] buffer = new byte[1024];
ServletOutputStream out = resp.getOutputStream();
while ((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
2.※验证码功能
验证码怎么来的?
- 前端实现
- 后端实现,需要用到Java的图片类,生产一个图片
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("refresh","3");
BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_BGR);
Graphics2D g = (Graphics2D) image.getGraphics();
g.setColor(Color.green);
g.fillRect(0,0,80,20);
g.setColor(Color.blue);
g.setFont(new Font(null,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");
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++) {
sb.append("0");
}
String s = sb.toString() + num;
return num;
}
3.☆实现重定向
一个web资源收到客户端请求后,它会通知客户端去访问另外一个web资源,这个过程叫重定向。
void sendRedirect(String varl)throws IOException;
测试:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/re/img");
}
面试题:重定向和转发的区别?
相同点:
不同点:
- 请求转发的时候,url不会产生变化
- 重定向的时候,url地址栏会发生变化;
用户登录
<form action="${pageContext.request.getContextPath()}/login" method="get">
用户名: <input type="text" name="username"><br>
密码: <input type="password" name="password"><br>
<input type="submit">
</form>
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username+":"+password);
resp.sendRedirect("/re/suc.jsp");
}
<head>
<title>Title</title>
</head>
<body>
<h1>success!</h1>
</body>
6.7 HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息;
1.获取前端传递参数,请求转发
@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[] hobbys = req.getParameterValues("hobbys");
System.out.println("*******************************");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbys));
System.out.println("*******************************");
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
面试题:重定向和转发的区别?
相同点:
不同点:
- 请求转发的时候,url不会产生变化 307
- 重定向的时候,url地址栏会发生变化; 302
|