JavaWeb笔记

it2024-11-05  6

JavaWeb

1.HelloWorld

1.1.导入包

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency>

1.2.测试类

package com.mashiro.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 Hello extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // 相应类型: html response.setContentType("text/html"); // 设置字符集编码 response.setCharacterEncoding("UTF-8"); // 获得相应的输出流 PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>com.mashiro.servlet.Hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello Servlet World!</h1>"); out.println("</body>"); out.println("</html>"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }

1.3.配置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 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"> <!-- web.xml中是配置我们web的核心应用--> <!-- 注册Servlet--> <servlet> <servlet-name>helloServlet</servlet-name> <servlet-class>com.mashiro.servlet.Hello</servlet-class> </servlet> <!-- 一个servlet对应一个mapping映射--> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <!-- 请求路径--> <url-pattern>/mashiro</url-pattern> </servlet-mapping> </web-app>

1.4.启动测试

http://localhost:8080/javaweb_01_maven_war/mashiro

2.HelloServlet

2.1.新建项目,导入包

<dependencies> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> </dependencies>

2.2.新建子项目,将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 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"> </web-app>

2.3.搭建好包结构,编写Servlet类

package com.mashiro.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("Hello,Servlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

2.4.在web.xml编写Servlet映射

<servlet> <servlet-name>helloServlet</servlet-name> <servlet-class>com.mashiro.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>/helloServlet</url-pattern> </servlet-mapping>

2.5.配置Tomcat

配置项目路径

2.6.启动

http://localhost:8080/servlet01/helloServlet

3.ServletContext

3.1.共享数据

HelloServer类 package com.mashiro.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 HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); context.setAttribute("username","Mashiro"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } Servlet02类 package com.mashiro.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 Servlet02 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); resp.setCharacterEncoding("UTF-8"); ServletContext context = this.getServletContext(); String username = (String) context.getAttribute("username"); PrintWriter writer = resp.getWriter(); writer.print("Name = "+ username); } @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 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"> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.mashiro.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>ser2</servlet-name> <servlet-class>com.mashiro.servlet.Servlet02</servlet-class> </servlet> <servlet-mapping> <servlet-name>ser2</servlet-name> <url-pattern>/ser2</url-pattern> </servlet-mapping> </web-app> 启动

1.先打开Ser2

Name = null

2.先打开hello 后打开Ser2

Name = Mashiro

3.2.获取初始化配置信息

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 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"> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/mybatis</param-value> </context-param> <servlet> <servlet-name>gp</servlet-name> <servlet-class>com.mashiro.servlet.ServletDemo03</servlet-class> </servlet> <servlet-mapping> <servlet-name>gp</servlet-name> <url-pattern>/gp</url-pattern> </servlet-mapping> </web-app> ServletDemo03类 package com.mashiro.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 ServletDemo03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = getServletContext(); String initParameter = context.getInitParameter("url"); resp.getWriter().write(initParameter); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } 输出结果

jdbc:mysql://localhost:3306/mybatis

3.3.请求转发

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 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"> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/mybatis</param-value> </context-param> <servlet> <servlet-name>gp</servlet-name> <servlet-class>com.mashiro.servlet.ServletDemo03</servlet-class> </servlet> <servlet-mapping> <servlet-name>gp</servlet-name> <url-pattern>/gp</url-pattern> </servlet-mapping> <servlet> <servlet-name>sd4</servlet-name> <servlet-class>com.mashiro.servlet.ServletDemo04</servlet-class> </servlet> <servlet-mapping> <servlet-name>sd4</servlet-name> <url-pattern>/sd4</url-pattern> </servlet-mapping> </web-app> ServletDemo04 package com.mashiro.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; public class ServletDemo04 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = getServletContext(); // RequestDispatcher namedDispatcher = context.getNamedDispatcher("/gp"); // namedDispatcher.forward(req,resp); context.getRequestDispatcher("/gp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } 结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NB8bIcau-1603267336458)(C:\Users\25716\AppData\Roaming\Typora\typora-user-images\image-20200925001002584.png)]

3.4.读取资源文件(properties)

ServletDemo05 package com.mashiro.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; public class ServletDemo05 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = getServletContext(); InputStream is = context.getResourceAsStream("/WEB-INF/classes/dp.properties"); Properties prop = new Properties(); prop.load(is); String username = prop.getProperty("username"); String password = prop.getProperty("password"); PrintWriter writer = resp.getWriter(); writer.print(username + ":" + password); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

dp.properties

username=root password=123456

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 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"> <servlet> <servlet-name>dpServlet</servlet-name> <servlet-class>com.mashiro.servlet.ServletDemo05</servlet-class> </servlet> <servlet-mapping> <servlet-name>dpServlet</servlet-name> <url-pattern>/dp</url-pattern> </servlet-mapping> </web-app> 运行结果

http://localhost:8080/s2/dp

root:123456

3.5.HttpServletResponse

3.5.1.向浏览器发送数据的方法

ServletOutputStream getOutputStream() throws IOException; PrintWriter getWriter() throws IOException;

3.5.2.向浏览器发送响应头的方法

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);

3.5.3.状态码

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; // 3xx:请求重定向 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; // 4xx:资源错误 int SC_BAD_REQUEST = 400; int SC_UNAUTHORIZED = 401; int SC_PAYMENT_REQUIRED = 402; int SC_FORBIDDEN = 403; // 未找到资源:404 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; // 5xx: 服务器错误 int SC_INTERNAL_SERVER_ERROR = 500; int SC_NOT_IMPLEMENTED = 501; // 网管错误:502 int SC_BAD_GATEWAY = 502; int SC_SERVICE_UNAVAILABLE = 503; int SC_GATEWAY_TIMEOUT = 504; int SC_HTTP_VERSION_NOT_SUPPORTED = 505;

3.5.4.常见应用-下载文件

向浏览器输出消息

下载文件

1.获取下载文件的路径

2.下载的文件名称

3.设置让浏览器能够支持下载我们需要的文件

4.获取下载文件的输入流

5.创建缓冲区

6.获取OutputStream对象

7.将FileOutputStream流写入到buffer缓冲区

8.使用OutputStream将缓冲区中的数据输出到客户端

代码实现

FileServler package com.mashiro.servlet; 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; public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //- 1.获取下载文件的路径 String realPath = "C:\\Users\\25716\\IdeaProjects\\javaweb-01-maven\\javaweb-02-Servlet\\response-01\\src\\main\\resources\\0.png"; //- 2.下载的文件名称 int index = realPath.lastIndexOf("\\")+1; String fileName = realPath.substring(index); //- 3.设置让浏览器能够支持下载我们需要的文件。 // 当文件名为中文时,‘+’后面可以带上URLEncoder.encode(fileName,"UTF-8")。,否则可能会乱码 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缓冲区 //- 8.使用OutputStream将缓冲区中的数据输出到客户端 while ((len =in.read(buffer)) > 0 ){ out.write(buffer,0,len); } //- 9.释放资源 in.close(); out.close(); } @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 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"> <servlet> <servlet-name>file</servlet-name> <servlet-class>com.mashiro.servlet.FileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>file</servlet-name> <url-pattern>/file</url-pattern> </servlet-mapping> </web-app>

3.5.5.常见应用-动态验证码实现

验证码生成方法 /** * 生成随机数 * @return 返回随机数字符串 */ 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(); return s + num; } ImageServlet package com.mashiro.servlet; 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.nio.Buffer; import java.util.Random; public class ImageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 设置浏览器三秒一次刷新 resp.setHeader("refresh","3"); // 在内存中创建一个图片 BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB); // 得到图片 Graphics2D g = image.createGraphics(); // 设置图片背景颜色 g.setBackground(Color.white); g.fillRect(0,0,80,20); // 给图片写数据 g.setColor(Color.BLACK); g.setFont(new Font(null,Font.BOLD,20)); g.drawString(makeNum(),0,20); // 告诉浏览器,此请求通过图片的形式打开 resp.setContentType("image/png"); // 浏览器存在缓存,不让浏览器缓存 resp.setDateHeader("expires",-1); resp.setHeader("Cache-Control","no-cache"); resp.setHeader("Pragma","no-cache"); // 向浏览器写入图片 ImageIO.write(image,"png",resp.getOutputStream()); } /** * 生成随机数 * @return 返回随机数字符串 */ 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(); return s + num; } @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 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"> <servlet> <servlet-name>png</servlet-name> <servlet-class>com.mashiro.servlet.ImageServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>png</servlet-name> <url-pattern>/png</url-pattern> </servlet-mapping> </web-app>

3.5.6.Response重定向

package com.mashiro.servlet; 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 RedirectServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /* resp.setHeader("Location","/response_01_war/png"); resp.setStatus(302);// resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); */ resp.sendRedirect("/response_01_war/png"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

3.5.7.重定向应用

在jps最上面加上<%@ page contentType=“text/html;charset=UTF-8” language=“java” %> 就不会乱码了

RequestTest package com.mashiro.servlet; 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 RequestTest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("进入了RequestTest请求"); String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println(username+":"+password); resp.sendRedirect("/response_01_war/success.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } index.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <body> <h2>Hello World!</h2> <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 <%-- Created by IntelliJ IDEA. User: 25716 Date: 2020/10/1 Time: 23:45 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Success</title> </head> <body> <h1>Login Success</h1> </body> </html>

3.6.HttpServletRequest

3.6.1.获取前端传入的参数 & 请求转发

Request请求转发 package com.mashiro.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.util.Arrays; public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 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("==========================================="); // 请求转发 req.getRequestDispatcher("/success.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } Tips:

请求转发:URL不会产生变化 307

重定向:URL会产生变化 302

4.Cookie

4.1.保存会话的两种技术

Cookie : 客户端技术(响应,请求)Session: 服务器技术(保存用户的会话信息)

4.2.CookieDemo01(lastLoginTime)

package com.mashiro.servlet; import javax.servlet.ServletException; import javax.servlet.http.Cookie; 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.Date; public class CookieDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 解决中文乱码 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); // 获取writer PrintWriter out = resp.getWriter(); Cookie[] cookies = req.getCookies(); if (cookies != null){ for (int i = 0;i < cookies.length;i++){ Cookie cookie = cookies[i]; if (cookie.getName().equals("lastLoginTime")){ Long lastLoginTime = Long.parseLong(cookie.getValue()); Date date = new Date(lastLoginTime); out.write(date.toLocaleString()); } } }else { out.write("这是你第一次访问本站"); } // 给客户端发放cookie Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+""); // cookie有效期为一天 cookie.setMaxAge(24*60*60); resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

4.3.CookieDemo01(删除cookie)

package com.mashiro.servlet; import javax.servlet.ServletException; import javax.servlet.http.Cookie; 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.Date; public class CookieDemo02 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 新建一个cookie Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+""); // 将cookie的有效期设置为0 即立马失效 cookie.setMaxAge(0); resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

4.4.CookieDemo01(cookie存储中文乱码 [解码&转码])

package com.mashiro.servlet; import javax.servlet.ServletException; import javax.servlet.http.Cookie; 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.net.URLDecoder; import java.net.URLEncoder; import java.util.Date; public class CookieDemo03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 解决中文乱码 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); // 获取writer PrintWriter out = resp.getWriter(); Cookie[] cookies = req.getCookies(); if (cookies != null){ for (int i = 0;i < cookies.length;i++){ Cookie cookie = cookies[i]; if (cookie.getName().equals("name")){ // 解码 out.write(URLDecoder.decode(cookie.getValue(),"utf-8")); } } }else { out.write("这是你第一次访问本站"); } // 转码 Cookie cookie = new Cookie("name", URLEncoder.encode("新天地","utf-8")); resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

5.Session

5.1.给session写入数据

package com.mashiro.servlet; import com.mashiro.pojo.Student; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class SessionDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 解决中文乱码问题 req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); // 获得session HttpSession session = req.getSession(); // 给session写入数据 session.setAttribute("student",new Student("Mashiro",1)); if (session.isNew()){ resp.getWriter().write("Session create success,Session ID ="+session.getId()); } else { resp.getWriter().write("Session is exist,Session ID ="+session.getId()); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

5.2.读取Session数据

package com.mashiro.servlet; import com.mashiro.pojo.Student; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class SessionDemo02 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 解决中文乱码问题 req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); // 获得session HttpSession session = req.getSession(); // 读取Session数据 Student student = (Student) session.getAttribute("student"); System.out.println(student.toString()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

5.3.注销Session

手动注销Session package com.mashiro.servlet; import com.mashiro.pojo.Student; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class SessionDemo03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 解决中文乱码问题 req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); // 获得session HttpSession session = req.getSession(); // 移除student Session session.removeAttribute("student"); // 注销掉sessionID 之后会产生一个新的id // 手动注销Session session.invalidate(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } web.xml中配置自动注销Session <session-config> <!-- 设置Session有效时间,单位为min --> <session-timeout>1</session-timeout> </session-config>

5.4.Session和Cookie的区别

Cookie是把用户的数据写给用户的客户端,由浏览器保存(可保存多个)Session把用户的数据写到用户独占的Session中,由服务器保存(用于保存重要信息,减少服务器资源浪费)Session对象由服务器创建

6. JSP

6.1.JSP所需的依赖

<dependencies> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/taglibs/standard --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies>

6.2.JSP基本语法

<%--JSP表达式--%> <%= new java.util.Date()%> <hr/> <%--JSP脚本片段--%> <% int sum = 0; for (int i = 1; i <= 100; i++) { sum += i ; } out.println("<h1>Sum="+sum+"</h1>"); %> <hr/> <%--脚本片段再实现1--%> <% int x = 10; out.println(x); %> <p>这是一个JSP文档</p> <% int y = 20; out.println(y); %> <hr/> <%--脚本片段再实现2--%> <% for (int i = 0; i < 5; i++) { %> <h1>Hello World! <%=i%></h1> <% } %>

6.3.JSP声明 (更高作用域 || 全局)

<%! private int number = 0; static{ System.out.println("Hello world!"); } public void mashiro(){ System.out.println("Good morning!"); } %> 声明 和 表达式的区别 声明的语句位于 public final class index_jsp 下表达式的语句位于 public void _jspServiceHttpServletRequest request,HttpServletResponse response) 下

6.4.JSP指令

错误页面跳转 [方式1] <%@ page errorPage="error/500.jsp" %> > 错误页面跳转 [方式2] <!--web.xml--> <error-page> <error-code>404</error-code> <location>/error/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/error/500.jsp</location> </error-page> 导包 <%@ page import="java.util.Date" %> 包含(用于公共页) <%-- Created by IntelliJ IDEA. User: 25716 Date: 2020/10/6 Time: 23:14 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%-- 讲两个页面合二为一了,单个页面 --%> <%@ include file="public/header.jsp"%> <h1>This is body</h1> <%@ include file="public/footer.jsp"%> <hr/> <%-- 拼接页面,多个页面,更加常用 --%> <jsp:include page="/public/header.jsp"/> <h1>This is body</h1> <jsp:include page="/public/footer.jsp"/> </body> </html>

6.5. JSP 9个内置类 && 作用域

pageContextrequestresponsesessionpageconfigoutapplicationexception <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>pageContestDemo01</title> </head> <body> <% <%--数据只在一个页面中有效--%> pageContext.setAttribute("name1","Mashiro"); <%--数据只在一次请求中有效,请求转发也会携带此数据--%> request.setAttribute("name2","Nagisa"); <%--数据只在一次会话中有效,即从浏览器打开 到 浏览器关闭--%> session.setAttribute("name3","Tomoya"); <%--数据在服务器中有效,即从服务器打开 到 服务器关闭--%> application.setAttribute("name4","kotomi"); %> <hr> <% String name1 = (String) pageContext.findAttribute("name1"); String name2 = (String) pageContext.findAttribute("name2"); String name3 = (String) pageContext.findAttribute("name3"); String name4 = (String) pageContext.findAttribute("name4"); String name5 = (String) pageContext.findAttribute("name5"); %> <hr> <h1>取出的值为:</h1> <h3>${name1}</h3> <h3>${name2}</h3> <h3>${name3}</h3> <h3>${name4}</h3> <h3>${name5}</h3> <%--null--%> <h3><%=name5%></h3> </body> </html>

6.6.pageContext实现请求转发

<%-- Created by IntelliJ IDEA. User: 25716 Date: 2020/10/7 Time: 14:43 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% pageContext.forward("/index.jsp"); // request.getRequestDispatcher("/index.jsp").forward(request,response); %> </body> </html>

7.JavaBean

实体类

必须要一个无参构造属性字段私有化字段有对应的Get/Set方法

一般用来和数据库做映射 ORM(对象关系映射)

<%@ page import="com.mashiro.pojo.stu" %> <%@ page import="java.util.Date" %> <%-- Created by IntelliJ IDEA. User: 25716 Date: 2020/10/8 Time: 22:54 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% // stu stu = new stu(); // Date date = new Date(); %> <jsp:useBean id="stu" class="com.mashiro.pojo.stu" scope="page"/> <jsp:setProperty name="stu" property="id" value="2"/> <jsp:setProperty name="stu" property="name" value="Nagisa"/> <jsp:setProperty name="stu" property="pwd" value="123456"/> <jsp:setProperty name="stu" property="sex" value="男"/> id:<jsp:getProperty name="stu" property="id"/> name:<jsp:getProperty name="stu" property="name"/> pwd:<jsp:getProperty name="stu" property="pwd"/> sex:<jsp:getProperty name="stu" property="sex"/> </body> </html>

8.过滤器(filter)

CharsetEncodingFilter.java package com.mashiro.filter; import javax.servlet.*; import java.io.IOException; public class CharsetEncodingFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { System.out.println("CharsetEncodingFilter初始化"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); System.out.println("doFilter before"); // chain(链): 放行程序,交接request,response。 chain.doFilter(request,response); System.out.println("doFilter after"); } public void destroy() { System.out.println("CharsetEncodingFilter销毁"); } } web.xml <filter> <filter-name>CharsetEncodingFilter</filter-name> <filter-class>com.mashiro.filter.CharsetEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharsetEncodingFilter</filter-name> <url-pattern>/servlet/*</url-pattern> </filter-mapping>

9.监听器(listener)

OnlineCountListener.java package com.mashiro.listener; import javax.servlet.ServletContext; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class OnlineCountListener implements HttpSessionListener { public void sessionCreated(HttpSessionEvent se) { ServletContext stc = se.getSession().getServletContext(); Integer onlineCount = (Integer) stc.getAttribute("onlineCount"); if (onlineCount == null){ onlineCount = new Integer(1); } else { int count = onlineCount.intValue(); onlineCount = new Integer(count+1); } stc.setAttribute("onlineCount",onlineCount); } public void sessionDestroyed(HttpSessionEvent se) { ServletContext stc = se.getSession().getServletContext(); Integer onlineCount = (Integer) stc.getAttribute("onlineCount"); if (onlineCount == null){ onlineCount = new Integer(0); } else { int count = onlineCount.intValue(); onlineCount = new Integer(count-1); } stc.setAttribute("onlineCount",onlineCount); } } web.xml <listener> <listener-class>com.mashiro.listener.OnlineCountListener</listener-class> </listener>

10.实现权限限制

Login.jsp <%-- Created by IntelliJ IDEA. User: 25716 Date: 2020/10/10 Time: 11:51 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="/servlet/login" method="post"> 用户名:<input type="text" name="username"> <input type="submit" name="提交"> </form> </body> </html> LoginServlet.java package com.mashiro.servlet; 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 LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); if (username.equals("admin")){ req.getSession().setAttribute("USER_SESSION",req.getSession().getId()); resp.sendRedirect("/sys/success.jsp"); } else { resp.sendRedirect("/error.jsp"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } success.jsp <%-- Created by IntelliJ IDEA. User: 25716 Date: 2020/10/10 Time: 11:54 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>Main</h1> <p><a href="/servlet/logout">注销</a></p> </body> </html> LoginOutServlet.java package com.mashiro.servlet; 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 LoginOutServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Object user_session = req.getSession().getAttribute("USER_SESSION"); if (user_session != null){ req.getSession().removeAttribute("USER_SESSION"); resp.sendRedirect("/Login.jsp"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } } error.jsp <%-- Created by IntelliJ IDEA. User: 25716 Date: 2020/10/10 Time: 11:54 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>Error</h1> </body> </html> sysFilter.java (过滤器) package com.mashiro.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class sysFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; if (request.getSession().getAttribute("USER_SESSION") == null){ response.sendRedirect("/error.jsp"); } filterChain.doFilter(request,response); } public void destroy() { } } web.xml <?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"> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.mashiro.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/servlet/login</url-pattern> </servlet-mapping> <servlet> <servlet-name>LoginOutServlet</servlet-name> <servlet-class>com.mashiro.servlet.LoginOutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginOutServlet</servlet-name> <url-pattern>/servlet/logout</url-pattern> </servlet-mapping> <filter> <filter-name>sysFilter</filter-name> <filter-class>com.mashiro.filter.sysFilter</filter-class> </filter> <filter-mapping> <filter-name>sysFilter</filter-name> <url-pattern>/sys/*</url-pattern> </filter-mapping> </web-app>

11.JDBC回顾

导入包 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mashiro</groupId> <artifactId>javaweb-jdbc</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.21</version> </dependency> </dependencies> </project> 实验环境搭建 CREATE DATABASE IF NOT EXISTS `jdbc`; USE jdbc; CREATE TABLE IF NOT EXISTS `users` ( `id` INT PRIMARY KEY, `name` VARCHAR(40), `password` VARCHAR(20), `email` VARCHAR(60), `birthday` DATE ); INSERT INTO `users`(id,`name`,`password`,`email`,`birthday`) VALUES (1,'Mashiro','123456','mashiro@qq.com','2000-01-01'), (2,'Syokora','123456','syokora@qq.com','2000-01-01'), (3,'panira','123456','panira@qq.com','2000-01-01'); SELECT * FROM users; 编写程序 (Statement) package com.mashiro.testJdbc; import java.sql.*; public class TestJDBC { public static void main(String[] args) throws SQLException, ClassNotFoundException { TestJDBC tj = new TestJDBC(); tj.testJdbc(); } public void testJdbc() throws ClassNotFoundException, SQLException { // 1.获取jdbc驱动类 Class.forName("com.mysql.cj.jdbc.Driver"); // 2.编写数据库用户信息 String url = "jdbc:mysql://localhost:3306/jdbc? serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false"; String name = "root"; String password = "123456"; // 3.获取数据库连接对象 即连接数据库 Connection connection = DriverManager.getConnection(url, name, password); // 4.操作数据库 编写sql语句 Statement statement = connection.createStatement(); String s = "select * from `users`"; // 5.执行sql语句 获取resultSet字符集 ResultSet resultSet = statement.executeQuery(s); // 6.打印获取的信息 while (resultSet.next()){ System.out.println("id = "+resultSet.getInt("id")); System.out.println("name = "+resultSet.getString("name")); System.out.println("password = "+resultSet.getString("password")); System.out.println("email = "+resultSet.getString("email")); System.out.println("id = "+resultSet.getDate("birthday")); } // 7.释放资源 resultSet.close(); statement.close(); connection.close(); } } 编写程序 (PreparedStatement) package com.mashiro.testJdbc; import java.sql.*; import java.util.Date; public class TestJDBC2 { public static void main(String[] args) throws SQLException, ClassNotFoundException { TestJDBC2 tj = new TestJDBC2(); tj.testJdbc(); } public void testJdbc() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false"; String name = "root"; String password = "123456"; Connection connection = DriverManager.getConnection(url, name, password); String sql = "insert into `users`(id,`name`,`password`,`email`,`birthday`) value (?,?,?,?,?) "; PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(1,5); statement.setString(2,"Nagisa"); statement.setString(3,"123456"); statement.setString(4,"nagisa@qq.com"); statement.setDate(5, new java.sql.Date(new Date().getTime())); int i = statement.executeUpdate(); // 7.释放资源 statement.close(); connection.close(); } }
最新回复(0)