JavaWeb(三)Servlet
2021/7/15 14:41:00
本文主要是介绍JavaWeb(三)Servlet,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1、servlet简介
- Servlet是sun公司开发动态web的一门技术
- sun公司提供了一个接口叫做Servlet,如果你想开发一个Servlet程序,只需要完成两个步骤:
- 编写一个类,继承HttpServlet类
- 把开发好的Java类部署到web服务器中
把实现了Servlet接口的Java程序叫做Servlet
2、HelloServlet
2.1 编写servlet
package com.zjb.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("HelloServlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
2.2 编写servlet映射
我们写的是java程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务中注册我们写的servlet,还需要给他一个浏览器能够访问的路径。
<!--注册servlet--> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.zjb.servlet.HelloServlet</servlet-class> </servlet> <!--servlet的请求路径--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>helloServlet</url-pattern> </servlet-mapping>
3.servlet原理
Servlet是由web服务器调用,web在收到浏览器请求之后,
4. Mapping问题
4.1、 一个Servlet可以指定一个映射路径
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/helloServlet</url-pattern> </servlet-mapping>
4.2、一个Servlet可以指定多个映射路径
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/helloServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/helloServlet1</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/helloServlet2</url-pattern> </servlet-mapping>
4.3、一个Servlet可以指定通用映射路径
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/helloServlet/*</url-pattern> </servlet-mapping>
4.4、 默认请求路径
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
4.5、指定一些后缀或者前缀等等
<!--使用自定义后缀实现请求映射 注意点:*前面不能加项目映射的路径--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
4.6.优先级问题
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求;
做个验证:
<?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_3_1.xsd" version="3.1" metadata-complete="true"> <!--注册servlet--> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.zjb.servlet.HelloServlet</servlet-class> </servlet> <servlet> <servlet-name>error</servlet-name> <servlet-class>com.zjb.servlet.ErrorServlet</servlet-class> </servlet> <!--servlet的请求路径--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/helloServlet</url-pattern> </servlet-mapping> <!--404 : 映射路径给默认的映射路径--> <servlet-mapping> <servlet-name>error</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
package com.zjb.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 ErrorServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); PrintWriter writer = resp.getWriter(); writer.print("<h1>404</h1>"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
启动访问,发现当访问路径是/helloServlet时,依然可以正常访问。
5.ServletContext对象(获取上下文)
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用。
5.1.共享数据
在一个servlet中保存的数据,可以在另外一个servlet中拿到。
package com.zjb.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class ServletContextServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取Servlet上下文 ServletContext servletContext = this.getServletContext(); String username = "上下文"; servletContext.setAttribute("username",username); System.out.println("向ServletContext对象中存入用户名:"+username); } }
package com.zjb.servlet; import javax.servlet.ServletContext; 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 GetServletContextServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = this.getServletContext(); String username = (String)servletContext.getAttribute("username"); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); PrintWriter writer = resp.getWriter(); writer.print("<h1>用户名:"+username+"</h1>"); } }
<?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_3_1.xsd" version="3.1" metadata-complete="true"> <!--注册servlet--> <servlet> <servlet-name>setContext</servlet-name> <servlet-class>com.zjb.servlet.ServletContextServlet</servlet-class> </servlet> <servlet> <servlet-name>getContext</servlet-name> <servlet-class>com.zjb.servlet.GetServletContextServlet</servlet-class> </servlet> <!--servlet的请求路径--> <servlet-mapping> <servlet-name>setContext</servlet-name> <url-pattern>/setC</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>getContext</servlet-name> <url-pattern>/getC</url-pattern> </servlet-mapping> </web-app>
启动并访问
5.2. 获取初始化参数
<!--配置一些web应用的初始化参数--> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/demo</param-value> </context-param>
package com.zjb.servlet; import javax.servlet.ServletContext; 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 GetInitParamServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = this.getServletContext(); String url = servletContext.getInitParameter("url"); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); PrintWriter writer = resp.getWriter(); writer.print("<h1>数据库连接路径:"+url+"</h1>"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
5.3.请求转发
package com.zjb.servlet; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * ServletContext 实现请求转发 */ public class GetRequestDispatcherServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = this.getServletContext(); //转发的路径 RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/getIp"); //调用forward方法实现请求转发 requestDispatcher.forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
转发的时候路径是不会发生改变的。
5.4.读取资源文件
Properties
- Servle在java目录下新建properties文件
- 在resources目录下新建properties文件
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为类路径classpath;
package com.zjb.servlet; import javax.servlet.ServletContext; 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.InputStream; import java.io.PrintWriter; import java.util.Properties; /*** * ServletContext 实现读取资源文件 */ public class GetResourceServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = this.getServletContext(); InputStream resourceAsStream = servletContext.getResourceAsStream("/WEB-INF/classes/db.properties"); Properties properties = new Properties(); properties.load(resourceAsStream); String username = properties.getProperty("username"); String password = properties.getProperty("password"); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); PrintWriter writer = resp.getWriter(); writer.print("<h1>用户名:"+username+",密码:"+password+"</h1>"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
6.HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过http协议访问服务器,http请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息。
6.1 获取前端传递的参数
String getParameter(String var1); String[] getParameterValues(String var1);
6.2 请求转发
package com.zjb.request; 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.util.Arrays; /** * HttpServletRequest 请求转发 */ public class GetParamServlet extends HttpServlet { @Override protected void doGet(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"); System.out.println(username+":"+password); String[] hobbies = req.getParameterValues("hobbies"); System.out.println("hobbies:"+Arrays.toString(hobbies)); //请求转发 req.getRequestDispatcher("/success.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
7.httpServletResponse
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应一个HttpServletResponse;
- 如果要获取客户端请求过来的参数:找HttpServletRequest
- 如果要获取客户端响应的一些信息:找HttpServletResponse
7.1. 简单分类
负责向浏览器发送数据的方法
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);
负责向浏览器发送响应状态码的方法
void setStatus(int var1);
响应状态码的常量
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;
7.2 常见应用
1. 向浏览器输出信息
2.下载文件
package com.zjb.response; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder; /** * HttpServletResponse 实现下载文件 * 实现步骤: * 1.要获取下载文件的路径 * 2.下载的文件名是什么 * 3.想办法设置让浏览器能够支持下载我们需要的东西 * 4.获取下载文件的输入流 * 5.创建缓冲区 * 6.获取OutPutStream对象 * 7.将FileOutPutStream流写入到buffer缓冲区,使用OutPutStream将缓冲区中的数据输出到客户端 */ public class DownloadResponseServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取要下载的文件路径 String realPath = "C:\\lesson\\learn-javaweb\\servlet-01\\target\\classes\\1.jpg"; System.out.println("下载文件的路径:"+realPath); //下载文件的文件名 String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1); System.out.println("文件名:"+fileName); //设置让浏览器能够支持下载我们需要的东西,使用URLEncoder.encode来解决文件名是中文乱码 resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")); //获取下载文件的输入流 FileInputStream fileInputStream = new FileInputStream(realPath); //创建缓冲区 int len = 0; byte[] buffer = new byte[1024]; //获取OutPutStream对象 ServletOutputStream outputStream = resp.getOutputStream(); //将FileOutPutStream流写入到buffer缓冲区,使用OutPutStream将缓冲区中的数据输出到客户端 while((len = fileInputStream.read(buffer))>0){ outputStream.write(buffer,0,len); } fileInputStream.close(); outputStream.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
3. 验证码功能
package com.zjb.response; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; /** * HttpServletResponse 实现验证码功能 */ public class ImageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //如何让浏览器3秒自动刷新一次 resp.setHeader("refresh","3"); //在内存中创建一个图片 BufferedImage bufferedImage = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB); //得到一个2D画笔 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.BOLD,20)); graphics.drawString(makeRandomNum(),0,20); //告诉浏览器,这个请求用图片的方式打开 resp.setContentType("image/jpeg"); //网站存在缓存,不让浏览器缓存 resp.setDateHeader("expires",-1); resp.setHeader("Cache-Control","no-cache"); resp.setHeader("Prama","no-cache"); //把图片写给浏览器 ImageIO.write(bufferedImage,"jpg",resp.getOutputStream()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } public String makeRandomNum(){ Random random = new Random(); String num = String.valueOf(random.nextInt(99999999)); StringBuffer sb = new StringBuffer(); for (int i = 0; i < 7-num.length(); i++) { sb.append("0"); } return sb.toString() + num; } }
4.response重定向(重点)
一个web资源收到客户端请求后,他会通知客户端去访问另外一个web资源,这个过程叫重定向。
void sendRedirect(String var1) throws IOException;
package com.zjb.response; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * HttpServletResponse 实现重定向 */ public class RedirectServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("进入重定向方法"); /** * 重定向的原理: * resp.setHeader("location","/servlet/image"); * resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); * 就等价于 resp.sendRedirect("/servlet/image") */ //重定向的时候一定要注意路径问题 resp.sendRedirect(req.getContextPath()+"/image"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
我们发现路径发生了改变,并且状态码是302 。
面试题:请你聊聊重定向和转发的区别。
相同点:页面都会实现跳转
不同点:
- 请求转发的时候,url不会产生变化
- 重定向的时候,url地址栏会发生变化
常见场景:
- 用户登录
package com.zjb.response; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class LoginDemoServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("进入到该登录方法"); String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println(username+":"+password); //重定向 resp.sendRedirect("/servlet/success.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
index.jsp
<html> <body> <h2>Hello World!</h2> <%-- ${pageContext.request.contextPath} 代表当前的项目--%> <form action="${pageContext.request.contextPath}/login" method="get"> 用户名:<input type="text" name="username"/> <br> 密码; <input type="password" name="password"/><br> <input type="submit"/> </form> </body> </html>
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>Success</h1> </body> </html>
这篇关于JavaWeb(三)Servlet的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-05并查集详解与实现教程
- 2024-11-05大厂数据结构与算法入门指南
- 2024-11-05大厂算法与数据结构入门指南
- 2024-11-05二叉树入门教程:轻松掌握基础概念与操作
- 2024-11-05红黑树入门教程:从零开始理解红黑树
- 2024-11-05初学者必备:链表基础知识详解
- 2024-11-05平衡树入门教程:理解、构建与应用
- 2024-11-05数据结构入门教程:轻松掌握基础知识
- 2024-11-05数据结构与算法入门教程
- 2024-11-05优先队列入门教程:理解与实现