JavaWeb入门

项目结构

web.xml文件的初始配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
  5. http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  6. version="4.0"
  7. metadata-complete="true">
  8. </web-app>

pom.xml文件的配置解读

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <!-- 创建项目时选择的信息-->
  6. <groupId>com.william</groupId>
  7. <artifactId>javaweb-maven-01</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <!-- 项目的打包方式:
  10. jar: java项目
  11. war: javaweb项目
  12. -->
  13. <packaging>war</packaging>
  14. <name>javaweb-maven-01 Maven Webapp</name>
  15. <!-- FIXME change it to the project's website -->
  16. <url>http://www.example.com</url>
  17. <!-- 配置-->
  18. <properties>
  19. <!-- 项目的默认构建编码-->
  20. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  21. <!-- 编码版本-->
  22. <maven.compiler.source>1.7</maven.compiler.source>
  23. <maven.compiler.target>1.7</maven.compiler.target>
  24. </properties>
  25. <!-- 项目依赖 从仓库中下载jar包的信息-->
  26. <dependencies>
  27. <dependency>
  28. <groupId>junit</groupId>
  29. <artifactId>junit</artifactId>
  30. <version>4.11</version>
  31. <scope>test</scope>
  32. </dependency>
  33. </dependencies>
  34. <!-- 项目构建的信息-->
  35. <build>
  36. <finalName>javaweb-maven-01</finalName>
  37. <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
  38. <plugins>
  39. <plugin>
  40. <artifactId>maven-clean-plugin</artifactId>
  41. <version>3.1.0</version>
  42. </plugin>
  43. <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
  44. <plugin>
  45. <artifactId>maven-resources-plugin</artifactId>
  46. <version>3.0.2</version>
  47. </plugin>
  48. <plugin>
  49. <artifactId>maven-compiler-plugin</artifactId>
  50. <version>3.8.0</version>
  51. </plugin>
  52. <plugin>
  53. <artifactId>maven-surefire-plugin</artifactId>
  54. <version>2.22.1</version>
  55. </plugin>
  56. <plugin>
  57. <artifactId>maven-war-plugin</artifactId>
  58. <version>3.2.2</version>
  59. </plugin>
  60. <plugin>
  61. <artifactId>maven-install-plugin</artifactId>
  62. <version>2.5.2</version>
  63. </plugin>
  64. <plugin>
  65. <artifactId>maven-deploy-plugin</artifactId>
  66. <version>2.8.2</version>
  67. </plugin>
  68. </plugins>
  69. </pluginManagement>
  70. </build>
  71. </project>

Servlet

mapping

  1. <!-- 注册servlet-->
  2. <servlet>
  3. <servlet-name>hello</servlet-name>
  4. <servlet-class>com.william.servlet.HelloServlet</servlet-class>
  5. </servlet>
  6. <!-- servlet请求的映射名和请求路径-->
  7. <servlet-mapping>
  8. <servlet-name>hello</servlet-name>
  9. <url-pattern>/hello</url-pattern>
  10. </servlet-mapping>

ServletContext

  1. // GetContext.class
  2. public class GetContext extends HttpServlet {
  3. @Override
  4. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  5. ServletContext context = this.getServletContext();
  6. String username = (String) context.getAttribute("username");
  7. resp.setContentType("text/html");
  8. resp.setCharacterEncoding("utf-8");
  9. resp.getWriter().print("名字:" +username);
  10. }
  11. @Override
  12. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  13. doGet(req, resp);
  14. }
  15. }
  16. // HelloServlet.class
  17. public class HelloServlet extends HttpServlet {
  18. @Override
  19. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  20. ServletContext context = this.getServletContext();
  21. String username = "william";
  22. context.setAttribute("username", username);
  23. }
  24. @Override
  25. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  26. doPost(req, resp);
  27. }
  28. }

HttpServletReponse

负责向浏览器发送数据的方法

  1. ServletOutputStream getOutputStream() throws IOException;
  2. PrintWriter getWriter() throws IOException;

负责向浏览器发送响应头的方法

  1. void setCharacterEncoding(String var1);
  2. void setContentLength(int var1);
  3. void setContentLengthLong(long var1);
  4. void setContentType(String var1);
  5. void setBufferSize(int var1);

常用响应的状态码

  1. int SC_OK = 200;
  2. int SC_MULTIPLE_CHOICES = 300; // 重定向
  3. int SC_NOT_FOUND = 404;
  4. int SC_BAD_GATEWAY = 502; // 网关错误

常见应用

  1. 向浏览器发送消息

  2. 下载文件

    1. public class FileServlet extends HttpServlet {
    2. @Override
    3. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    4. //1.获取文件的下载路径
    5. // String realPath = this.getServletContext().getRealPath("/1.png"); 这个路径是web服务器(Tomcat)下的路径,找不到目标文件
    6. String realPath = "D:\\MyProject\\javeweb-servlet-01\\response\\target\\classes\\1.png";
    7. System.out.println("文件的下载路径是" + realPath);
    8. //2.下载的文件名
    9. String fileName = realPath.substring(realPath.lastIndexOf("//") + 1);
    10. /* 小技巧: 用lastIndexOf找出文件路径最后一个/的下标+1后
    11. 得到文件名第一个字的下标后使用substring得出文件名*/
    12. //3.设置浏览器响应头
    13. resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8"));
    14. //4.获取文件的输入流
    15. FileInputStream in = new FileInputStream(realPath);
    16. //5.创建缓冲区
    17. int len = 0;
    18. byte[] buffer = new byte[1024];
    19. //6.获取OutputStream对象
    20. ServletOutputStream out = resp.getOutputStream();
    21. //7.将FileInputStream流写入缓冲区,使用ServletOutputStream将缓冲区数据输出到客户端
    22. while ((len = in.read(buffer)) > 0) {
    23. out.write(buffer, 0, len);
    24. }
    25. //9.关闭流
    26. out.close();
    27. in.close();
    28. }
    29. @Override
    30. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    31. doGet(req, resp);
    32. }
    33. }

应用:生成验证码图片

  1. public class ImageServlet extends HttpServlet {
  2. @Override
  3. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  4. //设置浏览器自动刷新
  5. resp.setHeader("refresh","5");
  6. //在内存中创建一个图片对象
  7. BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
  8. //得到笔
  9. Graphics2D graphics = (Graphics2D) image.getGraphics();
  10. //设置笔的颜色,填充图片背景
  11. graphics.setColor(Color.WHITE);
  12. graphics.fillRect(0,0,80,20);
  13. //写字
  14. graphics.setColor(Color.BLACK);
  15. graphics.setFont(new Font(null, Font.BOLD,20));
  16. graphics.drawString(makeNum(), 0, 20);
  17. //设置浏览器
  18. resp.setContentType("image/jpeg");
  19. resp.setDateHeader("expires",-1);
  20. resp.setHeader("Cache-Control", "no-cache");
  21. resp.setHeader("pragma", "no-cache");
  22. //把图片写给浏览器
  23. ImageIO.write(image, "jpeg", resp.getOutputStream());
  24. }
  25. @Override
  26. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  27. doGet(req, resp);
  28. }
  29. /*生成随机数*/
  30. private String makeNum() {
  31. Random random = new Random();
  32. String num = random.nextInt(9999999) + "";
  33. StringBuffer stringBuffer = new StringBuffer();
  34. //保证返回的字符串是7位
  35. for (int i = 0; i < 7 - num.length(); i++) {
  36. stringBuffer.append("0");
  37. }
  38. num = stringBuffer.toString() + num;
  39. return num;
  40. }
  41. }

重定向

  1. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  2. resp.sendRedirect("/response_war/image");
  3. /*
  4. 相当于
  5. resp.setHeader("Location","/response_war/image");
  6. resp.setStatus(HttpServletResponse.SC_FOUND);
  7. */
  8. }

重定向和转发的区别

相同

  • 页面都会实现跳转

不同点

  • 请求转发时,URL不会变 307
  • 重定向,URL会改变 302

HttpServletRequest

  1. package com.william.servlet;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.http.HttpServlet;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import java.io.IOException;
  7. import java.util.Arrays;
  8. public class LoginServlet extends HttpServlet {
  9. @Override
  10. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  11. //防止中文乱码
  12. req.setCharacterEncoding("utf-8");
  13. resp.setCharacterEncoding("utf-8");
  14. String username = req.getParameter("username");
  15. String password = req.getParameter("password");
  16. //多个属性用getParameterValues()获取
  17. String[] hobbies = req.getParameterValues("hobbies");
  18. System.out.println("================================");
  19. System.out.println("username = " + username);
  20. System.out.println("password = " + password);
  21. System.out.println("hobbies = " + Arrays.toString(hobbies));
  22. System.out.println("================================");
  23. //通过请求转发实现跳转
  24. // /代表当前web应用
  25. req.getRequestDispatcher("/success.jsp").forward(req, resp);
  26. }
  27. @Override
  28. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  29. doGet(req, resp);
  30. }
  31. }

Cookie Session

保存会话的两种技术

Cookie

  • 客户端技术

Session

  • 服务器技术
  1. package com.william;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.http.Cookie;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import java.io.IOException;
  8. import java.io.PrintWriter;
  9. import java.util.Date;
  10. //保存用户上一次登录的时间
  11. public class CookieDemo01 extends HttpServlet {
  12. @Override
  13. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  14. //解决中文乱码
  15. req.setCharacterEncoding("utf-8");
  16. resp.setCharacterEncoding("utf-8");
  17. PrintWriter out = resp.getWriter();
  18. //服务端从客户端获取cookie
  19. Cookie[] cookies = req.getCookies();
  20. //判断cookie是否为空
  21. if (cookies != null) {
  22. out.print("last login time: ");
  23. for (Cookie cookie : cookies) {
  24. if (cookie.getName().equals("last_time")) {
  25. String value = cookie.getValue();
  26. // cookie值转换为时间输出
  27. long l = Long.parseLong(value);
  28. Date date = new Date(l);
  29. out.print(date.toString());
  30. }
  31. }
  32. } else {
  33. out.print("this is your first time for login");
  34. }
  35. // 第一次访问则服务器给客户端一个cookie
  36. // 不是第一次也更新cookie
  37. Cookie cookie = new Cookie("last_time", System.currentTimeMillis() + "");
  38. //设置cookie有效期
  39. cookie.setMaxAge(24 * 60 * 60);
  40. //设置有效期为0则删除
  41. resp.addCookie(cookie);
  42. }
  43. @Override
  44. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  45. doGet(req, resp);
  46. }
  47. }

JSP

基本语法

  1. <%--JSP表达式用于将程序的输出输出至客户端--%>
  2. <%= new java.util.Date()%>
  3. <%--JSP脚本片段--%>
  4. <%
  5. int sum = 0;
  6. for (int i = 0; i < 10; i++) {
  7. sum += i;
  8. }
  9. out.print("<h1>sum=" + sum + "</h1>");
  10. %>

JSP声明

会将代码转换为生成的类中.

其他的会生成到_jspService方法中

  1. <%!
  2. static {
  3. System.out.println("entry servlet");
  4. }
  5. %>

Filter过滤器

  1. 导包

  2. 编写过滤器

    1. 实现接口
    2. 重写方法
  3. 在web.xml中注册

Listener监听器

与过滤器类似