JavaWeb 学习

本文最后更新于:1 年前

JavaWeb 学习

1, Tomcat

JavaWeb第1天

date: 2020.11.22

1.1 安装

tomcat官网: Apache Tomcat® - Welcome!

image-20201122174747037

下载完之后,解压至你想要安装的目录

1.2 Tomcat的启动和配置

  1. 文件夹的作用
    image-20201122170613953

  2. 启动和关闭Tomcat
    tomcat启动和关闭

  3. 访问测试:

1.3 配置

image-20201122175818558

  • 可以配置启动的端口号

    • tomcat的默认端口号为: 8080

    • mysql: 3306

    • http: 80

    • https: 443

      <Connector port="8080" protocol="HTTP/1.1"
                 connectionTimeout="20000"
                 redirectPort="8443" />
  • 可以配置主机的名称

    • 默认的主机名为: localhost - > 127.0.0.1
    • 默认的网站应用存放的位置: webapps
    <Host name="localhost"  appBase="webapps"
          unpackWARs="true" autoDeploy="true">
  • 可以配置一下环境变量

    题外话: 网站是如何进行访问的
    1. 输入一个域名; 回车

    2. 检查本机的 C:\Windows\System32\drivers\etc\hosts配置文件下有没有这个域名映射;

      1. 有: 直接返回对应的ip地址,这个地址中,有我们需要访问的web程序,可以直接访问 127.0.0.1 www.baidu.com
      2. 没有: 去DNS服务器找,找到的话就返回,找不到就返回找不到
        image-20201123000028908

1.4 发布一个Web网站

将自己写发网站,放到服务器(Tomcat)中指定的web应用的文件夹(webapps)下,就可以访问网站应该有的结构

---webapps : Tomcat服务器的web目录
	-ROOT
	-Study
	-WEB-INF
			-Classes: java程序
			-lib: web应用所依赖的jar包
		-index.html 默认的首页
		-static
			-css
				-style.css
			-js
			-img
		-...

HTTP协议: 面试

Maven: 构建工具

  • Maven安装包

    Servlet 入门

  • HelloWorld!

  • Servlet配置

  • 原理

2, HTTP

JavaWeb第2天

date: 2020.11.24

2.1 是什么http

HTTP(超文本传输协议)是一个简单的请求-响应协议,它通常运行在TCP之上

  • 文本: html, 字符串 …
  • 超文本: 图片, 音乐, 视频, 定位, 地图 …

Https: 安全的

  • 443

2.2 两个时代

  • http1.0
    • HTTP/1.0: 客户端与web服务器连接后,只能获取一个web资源,断开连接
  • http2.0
    • HTTP/1.1: 客户端与web服务器连接后, 可以获取多个web资源

2.3 Http请求

  • 客户端—发请求(Request)— 服务器

百度:

Request URL: https://www.baidu.com	请求地址
Request Method: GET		get方法/post方法
Status Code: 200 OK		状态码: 200
Remote Address: 14.215.177.38:443	远程地址
Accept: text/html
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Cache-Control:max-age=0
Connection: keep-alive

1, 请求行

  • 请求行的请求方式: GET
  • 请求方式: GET, POST, HEAD, DELETE, TRACT
    • get: 请求能够携带的参数比较少,大小有限制,会在浏览器的URL地址栏显示数据内容,不安全,但高效
    • post: 请求能够携带的参数没有限制,大小没有限制,不会在浏览器的URL地址栏显示数据内容,安全,但不高效

2, 消息头

Accept: 告诉浏览器,它所支持的数据类型
Accept-Encoding: 支持哪种编码格式 GBK UTF-8 GB2312 ISO8859-1
Accept-Language: 告诉浏览器,它的语言环境
Cache-Control:max-age=0: 缓存控制
Connection: 告诉浏览器,请求完成是断开还是保持连接
Host: 主机

2.4 http响应

  • 服务器—响应— 客户端

百度:

Cache-Control: private	缓存控制
Connection: keep-alive	连接
Content-Encoding: gzip	编码类型
Content-Type:text/html	类型

1, 响应体

Accept: 告诉浏览器,它所支持的数据类型
Accept-Encoding: 支持哪种编码格式 GBK UTF-8 GB2312 ISO8859-1
Accept-Language: 告诉浏览器,它的语言环境
Cache-Control:max-age=0: 缓存控制
Connection: 告诉浏览器,请求完成是断开还是保持连接
Host: 主机
Refrush: 告诉客户端,多久刷新一次
Location: 让网页重新定位

2, 响应状态码

200: 请求响应成功 200

3**: 请求重定向

  • 重定向: 你重新到我给你的新位置去

4xx: 找不到资源 404

  • 资源不存在

5xx: 服务器代码错 500 502: 网关错误

常见面试题

当你的浏览器中地址栏输入并回车的一瞬间到页面能够展示回来,经历了什么?

3, Maven

JavaWeb第3天

date: 2020.11.26

我为什么要学习这个技术

  1. 在Java web开发中,需要使用大量的jar包,我们手动去导入;
  2. 如何能够让一个东西自动帮我导入和配置这个jar包.
    由此,Maven诞生了

3.1 Maven项目架构管理工具

我们目前用来就是方便的导入jar包!

Maven的核心思想: 约定大于配置

  • 有约束,不要去违反

Maven会规定好你如何去编写我们的Java代码,必须要按照这个规范;

3.2 下载安装Maven

官网: Maven – Welcome to Apache Maven

image-20201126124710642

下载完成后,解压即可

电脑上的环境,最后都放在一个文件夹里

3.3 配置环境变量

在我们的系统环境变量中

配置如下配置:

  • M2_HOME maven目录下的bin目录
  • MAVEN_HOME maven目录

image-20201126125928904

测试Maven是否安装成功,保证必须配置完毕!

3.4 阿里云镜像

  • 镜像: mirrors
    • 作用: 加速我们的下载
  • 国内建议使用阿里云的镜像
<mirror>
    <id>nexus-aliyun</id>
    <mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf>
    <name>Nexus aliyun</name>
                                			<url>http://maven.aliyun.com/nexus/content/groups/public</url> 
</mirror>

3.5 本地仓库

在本地的仓库,运程仓库;

建立一个本地仓库: localRepository

<localRepository>D:\PNCA\environment\apache-maven-3.6.3\maven_repo</localRepository>

3.6 在IDEA中使用Maven

JavaWeb第4天

date: 2020.11.27

  1. 启动IDEA
  2. 创建一个Maven项目
    image-20201127145100090

image-20201127145306228

image-20201127145626430

  1. 等待项目初始化完毕

  2. 观察Maven仓库多了什么东西?

  3. IDEA中Maven设置
    注意: IDEA项目创建成功后,看一眼Maven的配置,

    image-20201127170603154

  4. 到这里,Maven在IDEA中的配置和使用就OK了!

3.7 创建一个普通的Maven项目

image-20201127175143915

这个只有在Web应用下才有1

image-20201127175510963

3.8 标记文件夹功能

image-20201127175908458

image-20201127180238889

3.9 在IDEA中配置Tomcat

JavaWeb第5天

date: 2020.11.29

image-20201127180621196

image-20201127180711490

image-20201127181610015

解决警告问题
必须要配置: 为什么会有这个问题: 我们访问一个网站,需要指定一个文件夹名字;

image-20201127181728157

image-20201127182350573

image-20201127182613164

image-20201127235920783

3.10 pom文件

pom.xml是Maven的核心配置文件

image-20201128210845128

由于在IDEA的Maven项目中新建一个模块,它的Language Level总是自动变到5,所以可以在pom.xml加入下面的

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
<!--                    下面的source和target的版本要跟自己的jdk版本一样-->
                    <source>14</source>
                    <target>14</target>
                </configuration>
            </plugin>
        </plugins>
<build>
<!--项目构建用的东西-->
<build>
  <finalName>javaWeb_01_Maven</finalName>
  <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
    <plugins>
      <plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <version>3.1.0</version>
      </plugin>
      <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
      <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <version>3.0.2</version>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
      </plugin>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.22.1</version>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.2</version>
      </plugin>
      <plugin>
        <artifactId>maven-install-plugin</artifactId>
        <version>2.5.2</version>
      </plugin>
      <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.8.2</version>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <!--下面的source和target的版本要跟自己的jdk版本一样-->
          <source>11</source>
          <target>11</target>
        </configuration>
      </plugin>

    </plugins>
  </pluginManagement>
</build>

image-20201128220121858

maven由于他的约定大于配置,我们之后可能遇到我们写的配置文件,无法被导出或者生效的问题,解决方案:

    <!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <excludes>
          <exclude>**/*.properties</exclude>
          <exclude>**/*.xml</exclude>
        </excludes>
        <filtering>true</filtering>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
    </resources>
  </build>

3.12 IDEA操作

image-20201129132913845

3.13 解决遇到的问题

JavaWeb第6天

date: 2020.12.1

  1. Maven 3.6.2 不能导包

  2. Tomcat闪退

  3. IDEA中每次都要重复Maven

    • 在IDEA中全局默认配置中去配置

      image-20201201163402800

  4. Maven项目中Tomcat无法配置

  5. Maven项目Web项目中的web.xml版本问题
    image-20201201164251107

  6. 替换为webapps4.0版本和tomcat一致

    <?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>

Maven Repository: servlet api (mvnrepository.com)

image-20201201170540169

image-20201201170637660

4, Servlet

4.1, Servlet简介

  • Servlet就是Sun公司开发动态web的一种技术
  • Sun在这些API中提供了一个接口叫做: Servlet, 如果你想开发一个Servlet程序,只需要完成两个小步骤:
    • 编一个类, 实现Servlet接口
    • 把开发好的Java类部署到web服务器中.

把实现了Servlet接口的java程序叫做,Servlet

4.2 HelloServlet

Servlet接口Sun公司有两个默认的实现类: HttpServlet

  1. 构建一个普通的Maven项目,删掉里面的src目录,以后我们的学习就在这个项目里面建立Moudel;这个空工程就是Maven的主工程

  2. 关于Maven父子工程的理解;
    父母项目会有

    <modules>
    	<module>servlet_01</module>
    </modules>

    子项目会有

    <parent>
        <artifactId>javaWeb_02_servlet</artifactId>
        <groupId>com.pnca</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    父项目中的java子项目可以直接使用

  3. Maven环境优化

    1. 修改web.xml为最新的
    2. 将maven的结构搭建完整
  4. 编写一个Servlet程序

    1. 编写一个普通类

    2. 实现Servlet接口,这里我们直接继承HttpServlet

      public class HelloServlet extends HttpServlet {
      
         // 由于get和post只是请求实现的不同方式,可以互相调用,业务逻辑都一样
         @Override
         protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            PrintWriter writer = resp.getWriter();
            writer.print("Hello,Servlet");
            super.doGet(req, resp);
         }
      
         @Override
         protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            super.doPost(req, resp);
         }
      }
  5. 编写Servlet的映射
    为什么需要映射: 我们写的是Java程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务器中注册我们的Servlet,还需要给他一个浏览器能够访问的路径

    <!--注册Servlet-->
    <servlet>
       <servlet-name>hello</servlet-name>
       <servlet-class>com.pnca.servlet.HelloServlet</servlet-class>
    </servlet>
    <!--Servlet的请求路径-->
    <servlet-mapping>
       <servlet-name>hello</servlet-name>
        <!--url-pattern要加/-->-->
       <url-pattern>/hello</url-pattern>
    </servlet-mapping>
  6. 配置tomcat
    注意: 配置项目发布的路径,以及删除父类构造函数

  7. 启动测试

4.3, Servlet原理

JavaWeb第7天

date: 2020.12.4

Servlet是由Web服务器调用,web服务器在收到浏览器请求之后,会:

image-20201204151036212

4.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>/hello2</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
       <servlet-name>hello</servlet-name>
       <url-pattern>/hello3</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. 指定一些后缀或者前缀…

    <!--可以自定义后缀实现请求映射
    注意点,*前面并不能加项目映射的路径
    hello/saifsf.pnca-->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>*.pnca</url-pattern>
    </servlet-mapping>
  6. 优先级
    指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求;

    <!--404-->
    <servlet>
    	<servlet-name>error</servlet-name>
    	<servlet-class>com.pnca.servlet.ErrorServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>error</servlet-name>
    	<url-pattern>/*</url-pattern>
    </servlet-mapping>

4.5, ServletContext

JavaWeb第8天

date: 2020.12.6

web容器在启动的时候,它会为每个web程序都创建一个对应的Servlet对象,他代表了当前的web应用;

1. 共享数据

我在这个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 servletContext = this.getServletContext();
		String username = "pncalbl";    // 数据
		servletContext.setAttribute("username", username); //将一个数据保存ServletContext中,名字为username
	}
}
public class GetServlet extends HttpServlet {
   @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      doGet(req, resp);
   }

   @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");
      resp.getWriter().print("名字" + username);
   }
}
<servlet>
   <servlet-name>getc</servlet-name>
   <servlet-class>com.pnca.servlet.GetServlet</servlet-class>
</servlet>

<servlet-mapping>
   <servlet-name>getc</servlet-name>
   <url-pattern>/getc</url-pattern>
</servlet-mapping>
  • 测试访问结果;

    注意,先执行/hello,存入数据.然后执行/getc,获取数据

    image-20201205173037189

2, 获取初始化参数

<!--配置一些web应用初始化参数-->
<context-param>
   <param-name>url</param-name>
   <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   ServletContext servletContext = this.getServletContext();

   String url = servletContext.getInitParameter("url");
   resp.getWriter().print(url);
}

3, 请求转发

    @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      System.out.println("进入了方法ServletDemo04");
      ServletContext servletContext = this.getServletContext();
//    RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/gp");   // 转发的请求路径
//    requestDispatcher.forward(req, resp);   // 调用forward方法实现请求转发
      servletContext.getRequestDispatcher("/gp").forward(req, resp);
   }

4, 读取资源文件

properties

  • 在java目录下新建properties
  • 在resource目录下新建properties

发现: 都被打包到同一个路径下: classes,我们俗称这个路径为classespath

思路: 需要一个文件流

username=root566
password=123456thhh
@Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      ServletContext servletContext = this.getServletContext();
//    InputStream resourceAsStream = servletContext.getResourceAsStream("/WEB-INF/classes/db.properties");
      InputStream resourceAsStream = servletContext.getResourceAsStream("/WEB-INF/classes/com/pnca/servlet/aa.properties");
      Properties properties = new Properties();
      properties.load(resourceAsStream);
      String user = properties.getProperty("username");
      String pwd = properties.getProperty("password");
      resp.getWriter().print(user + ": " + pwd);
   }

访问测试,即可

image-20201206173710672

4.6, HttpServletResponce

JavaWeb第9天

date: 2020.12.8

web服务器接收到客户端的http请求时,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse对象;

  • 如果要获取客户端请求过来的参数: 找ServletRequest
  • 如果要给客户端响应一些信息: 找HttpResponse

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

响应的状态码

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;

2, 下载文件

1.向浏览器输出消息

2.下载文件

1.要获取下载文件的路径
2.下载的文件名
3.设置想办法让浏览器能够支持下载我们需要的东西
4.获取下载文件的输入流
5.创建缓冲区
6.获取OutPutStream对象
7.将FileOutPutStream流写入到Buffer缓冲区,使用OutPutStream将缓冲区中的数据输出到客户端
8.关闭流对象
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //1.  要获取下载文件的路径
    String realPath = "D:\\PNCA\\Project\\Java_Project\\JavaWeb\\javaweb_02_servlet\\response\\src\\main\\resources\\1.png";
    //    String realPath = this.getServletContext().getRealPath("/1.png");
    System.out.println("获取下载文件的路径: " + realPath);
    //2.  下载的文件名
    String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
    //3.  设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名,设置utf-8编码
    resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.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)) > 0) {
        out.write(buffer, 0, len);
    }
    //8.  关闭流对象
    in.close();
    out.close();
}

3, 验证码

public class ImageServlet extends HttpServlet {
   @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      // 如何让浏览器3秒刷新一次
      resp.setHeader("refresh" , "3");

      // 在内存中创建一个图片
      BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);

      // 得到图片
      Graphics2D graphics = (Graphics2D) image.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(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());
   }

   @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      doGet(req, resp);
	}

   // 生成随机数
   private String makeNum() {
      Random random = new Random();
      String num = random.nextInt(999999) + "";
      StringBuffer stringBuffer = new StringBuffer();

      for (int i = 0; i < 7 - num.length(); i++) { // 保证七位数
         stringBuffer.append("0");
      }
      return stringBuffer.toString() + num;
   }
}

注意,在web.xml中注册

4, 实现重定向

image-20201211145312620

B一个web资源收到客户端A的请求后,B会通知A客户端去访问另一个web资源,这个过程叫重定向

常见场景:

  • 用户登录
void sendRedirect(String var1) throws IOException;

测试

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   /*resp.setHeader("Location", "/rs/img");
   resp.setStatus(302);*/
   resp.sendRedirect("/rs/img");   // 重定向
}

面试题,请你聊聊重定向和转发的区别?

相同点

  • 页面都会实现跳转

不同的

  • 请求转发的时候,url不会发生变化
  • 重定向的时候,url地址栏会发生变化

4.7 , HttpServletRequest

JavaWeb第10天

date: 2020.12.12

HttpServletRequest代表客户端的请求,用户通过http协议访问服务器,HTTP请求中的所有信息会被封装到HttpRequest,通过这个HttpRequest的方法,获得客户端的所有信息。

1, 获取前端传递的参数

image-20201212150125276

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("==========================");

2, 请求转发

req.getRequestDispatcher("/success.jsp").forward(req, resp);

面试题,请你聊聊重定向和转发的区别?

相同点

  • 页面都会实现跳转

不同的

  • 请求转发的时候,url不会发生变化 307
  • 重定向的时候,url地址栏会发生变化 302

JavaWeb第11天

date: 2020.12.14

5.1, 会话

会话: 用户打开一个浏览器,点击了很多的超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话.

有状态会话:

一个网站,怎么证明你来过?

​ 客户端 服务端

  1. 服务端给客户端一个信件,客户端下次访问服务器带上信件就可以; cookie
  2. 服务器登记你来过了,下次你来的时候我来匹配你; session

5.2, 保存会话的两种技术

cookie

  • 客户端技术(响应, 请求)

session

  • 服务器技术,利用这个技术,可以保存会话的信息,我们可以把信息或者数据放在Session
  1. 从请求中拿到cookie信息
  2. 服务器响应给客户端cookie
Cookie[] cookies = req.getCookies();	// 获得Cookie
cookie.getName();	// 获得cookie中的key
cookie.getValue();	// 获得cookie中的value
new Cookie("LastLoginTime", System.currentTimeMillis() + "");	// 新建一个cookie
cookie.setMaxAge(24 * 60 * 60);	// 设置cookie的有效期
resp.addCookie(cookie);	// 响应给客户端一个cookie

cookie: 一般会保存在本地的用户目录下 AppData中;

一个网站Cookie是否存在上限;

  • 一个Cookie只能保存一个信息
  • 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie
  • Cookie大小有限制,例如4kb
  • 游览器有300个cookie上限

删除Cookie

  • 不设置有效期,关闭浏览器,自动失效
  • 设置有效期时间为0

编码, 解码

URLEncoder.encode("年后", StandardCharsets.UTF_8)
URLDecoder.decode(cookie.getValue(), StandardCharsets.UTF_8)

5.4 Session (重点)

JavaWeb第12天

date: 2020.12.15

什么是Session:

  • 服务器会给每个用户(浏览器),创建一个Session对象

  • 一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就存在

  • 用户登录之后,整个网站都可以访问.

image-20201215212325644

Session和Cookie的区别

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

使用场景:

  • 保存一个用户的登录信息
  • 购物车信息
  • 在整个网站中,经常会使用的数据,我们将它保存在Sesson中
public class SessionDemo01 extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// 解决乱码问题
		req.setCharacterEncoding("utf-16");
		resp.setCharacterEncoding("utf-16");
		resp.setContentType("text/html;charset=utf-8");

		// 得到Session对象
		HttpSession session = req.getSession();

		// 给Session存东西
		session.setAttribute("name", new Person("PNCALBL", 10));

		// 获取Session的ID
		String sessionId = session.getId();

		// 判断Session是不是新创建
		if (session.isNew()) {
			resp.getWriter().write("session创建成功,ID: " + sessionId);
		}else{
			resp.getWriter().write("session已经在服务器中存在了,ID: " + sessionId);
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// 解决乱码问题
		req.setCharacterEncoding("utf-16");
		resp.setCharacterEncoding("utf-16");
		resp.setContentType("text/html;charset=utf-8");

		// 得到Session对象
		HttpSession session = req.getSession();

		Person person = (Person) session.getAttribute("name");

		System.out.println(person);
	}
@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// 解决乱码问题
		req.setCharacterEncoding("utf-16");
		resp.setCharacterEncoding("utf-16");
		resp.setContentType("text/html;charset=utf-8");

		// 得到Session对象
		HttpSession session = req.getSession();
		session.removeAttribute("name");
		session.invalidate();
	}

会话自动过期: web.xml配置

<!--设置Session默认失效时间-->
<session-config>
    <!--1分钟后session失效,以分钟为单位-->
    <session-timeout>1</session-timeout>
</session-config>

6, JSP

JavaWeb第13天

date: 2020.12.17

6.1, 什么是jsp

Java Server Pages : Java服务器端页面,也和Servlet一样,用于动态web技术!

最大的特点:

  • 写JSP就像在写HTML
  • 区别:
    • HTML只给用户提供数据
    • jsp页面可以嵌入Java代码, 为用户提供动态数据

6.2, JSP原理

思路: JSP到底怎么执行的!

  • 代码层面没有任何问题

  • 服务器内部工作

    tomcat中有一个work目录

    IDEA中使用Tomcat的话,会在IDEA的Tomcat中产生一个work目录

image-20201217202017270

image-20201217202109882

发现了java程序!

浏览器向服务器发送请求,不管访问什么,其实都是在访问Servlet!

JSP最终也会被转换成一个java类

JSP本质上还是一个Servlet

// 初始化
public void _jspInit() {
}
// 销毁
public void _jspDestroy() {
}
// JSPService
public void _jspService(HttpServletRequest request, HttpServletResponse response){}
  1. 判断请求

  2. 内置了一些对象

    final javax.servlet.jsp.PageContext pageContext; // 页面上下文
    javax.servlet.http.HttpSession session = null; // session
    final javax.servlet.ServletContext application; // applicationContext
    final javax.servlet.ServletConfig config; // config
    javax.servlet.jsp.JspWriter out = null; // out
    final java.lang.Object page = this; // page 当前
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;
  3. 输出页面前增加的代码

    response.setContentType("text/html;charset=UTF-8"); // 设置响应的页面类型
    pageContext = _jspxFactory.getPageContext(this, request, response,null, true, 8192, true);
    _jspx_page_context = pageContext;
    application = pageContext.getServletContext();
    config = pageContext.getServletConfig();
    session = pageContext.getSession();
    out = pageContext.getOut();
    _jspx_out = out;
  4. 以上的这些个对象我们可以直接在JSP页面中使用!

在JSP页面中:

只要是JAVA代码就会原封不东的输出;

如果是HTML代码,就会被转换为

out.write("<html>\r\n");

这样的格式,输出到前端

6.3, JSP的基础语法

JavaWeb第14天

date: 2020.12.22

<dependencies>
		<!--JSP的依赖-->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
		</dependency>
		
		<!--Servlet的依赖-->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
		
		<!--standard标签库-->
		<!-- https://mvnrepository.com/artifact/taglibs/standard -->
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>
		
		<!--JSTL表达式的依赖-->
		<!-- 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>
	</dependencies>

任何语言都有自己的语法,jsp作为java的技术的一种应用,它拥有一些自己扩充的语法,它支持所有的java语法.

JSP表达式

<%--JSP表达式
作用: 用来将程序的输出,输出到客户端
<%= 变量或者表达式%>
--%>
<%= new java.util.Date()%>

jsp脚本片段

<%--jsp脚本片段--%>
<%
int sum = 0;
for (int i = 0; i < 100; i++) {
    sum += i;
}
out.println("<h1>Sum=" + sum + "</h1>");
%>

脚本呢片段的再实现

<%
  int x = 10;
  out.println(x);
%>
<p>这是一个JSP文档</p>
<%
  int y = 2;
  out.println(y);
%>

<hr>

<%--在代码中嵌入HTML元素--%>
<%
  for (int i = 0; i < 5; i++) {
%>
<h1>HeLLo, World <%=i%></h1>
<%
  }
%>

JSP声明

<%!
  static {
    System.out.println("Loading Servlet!");
  }
  private final int globalVar = 0;
  public void pnca() {
    System.out.println("进入了方法pnca");
  }
%>

JSP声明: 会被编译到JSP生成的Java类中!其他的,就会被生成到_jspService()方法中!

在JSP中,嵌入java代码即可!

JSP的注释,不会在客户端显示,HTML的就会!

6.4, JSP指令

<%@page args .... %>
<%@include "%>

6.5,九大内置对象

JavaWeb第15天

date: 2020.12.24

  • PageContext
  • Request
  • Response
  • Session
  • Application 【ServletContext】
  • config 【ServletConfig】
  • out
  • page
  • exception
pageContext.setAttribute("name1", "pnca1"); // 保存的数据只能在一个页面中有效
	request.setAttribute("name2", "pnca2"); // 保存的数据只能在一次请求中有效,请求转发会携带这个数据
	session.setAttribute("name3", "pnca3"); // 保存的数据只能在一次会话中有效,从打开浏览器到关闭浏览器
	application.setAttribute("name4", "pnca4"); // 保存的数据只在服务器中有效,从打开服务器到关闭服务器

6.6, JSP标签, JSTL标签,EL表达式

JavaWeb第16天

date: 2021.01.17

<dependency>
   <groupId>taglibs</groupId>
   <artifactId>standard</artifactId>
   <version>1.1.2</version>
</dependency>

<!--JSTL表达式的依赖-->
<!-- 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>

EL表达式: ${}

  • 获取数据
  • 执行运算
  • 获取web开发的常用对象

JSP标签

<%--
http://localhost:8080/jsptag.jsp?name=pnca&age=18
--%>
<jsp:forward page="/jsptag2.jsp">
   <jsp:param name="name" value="pnca"/>
   <jsp:param name="age" value="18"/>
</jsp:forward>

JSTL标签

JSTL标签的使用就是为了弥补HTML标签的不足; 它自定义了许多标签,可以供我们使用标签的功能和Java代码一样!

核心标签(掌握部分)

格式化标签

SQL标签

XML标签

image-20210117194315738

JSTL标签的使用方法

  • 引入对应的taglib
  • 使用其中的方法
  • 在Tomcat也需要引入jstl的包,否则会报错:JSTL解析错误

c:if

<%--判断如果提交的用户名是管理员,则登录成功--%>
<c:if test="${param.username == 'admin'}" var="isAdmin">
   <c:out value="管理员欢迎您!"/>
</c:if>
<c:out value="${isAdmin}>"/>

c:when

<c:choose>
   <c:when test="${score >= 90}">
      您的成绩为优秀
   </c:when>

   <c:when test="${score >= 80}">
      您的成绩为一般
   </c:when>

   <c:when test="${score >= 70}">
      您的成绩为良好
   </c:when>

   <c:when test="${score >= 60}">
      您的成绩为及格
   </c:when>

   <c:when test="${score < 60}">
      您的成绩为不及格
   </c:when>

</c:choose>

c:foreach

<c:forEach var="people" items="${list}">
   <c:out value="${people}"/> <br>
</c:forEach>

<hr>

<c:forEach var="people" items="${list}" begin="1" end="3" step="2">
   <c:out value="${people}"/> <br>
</c:forEach>

7, JavaBen

实体类

JavaBean有特定的写法:

  • 必须有一个无参构造
  • 属性必须私有化
  • 必须有对应的get/set

一般用来和数据库的字段做关系映射 ORM;

ORM:对象关系映射

  • 表—>类
  • 字段—>属性
  • 行记录—->对象

people表

id name age address
1 pnca1 12 西安
2 pnca2 23 西安
3 pnca3 22 西安
class People {
	private int id;
	private String name;
	private int age;
	private String address;
}

Class A {
	new People(1, "pnca1", 12, "西安")
    new People(1, "pnca1", 12, "西安")
    new People(1, "pnca1", 12, "西安")
}
  • 过滤器
  • 文件上传
  • 邮件发送
  • JDBC复习: 如何使用JDBC, JDBC crud, JDBC事务

8, MVC三层架构

什么是MVC: Mode View Controller 模型,视图,控制器

10.1,早些年

image-20210119202913484

用户直接访问控制层,控制层就可以直接操作数据库;

servlet--CRUD-->数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求,响应,视图跳转,处理JDBC,处理业务代码,处理逻辑代码

架构:没有什么是加一层解决不了的!
JDBC

Mysql Oracle SqlServer

10.2,三层架构

image-20210119203732844

Model

  • 业务处理:业务逻辑(Service)
  • 数据持久层:CRUD(DAO)

View

  • 展示数据
  • 提供链接发起Servlet请求(a, form, img)

Controller(Servlet)

  • 接收用户的请求:(req:请求参数,Session信息)
  • 交给业务层处理对应的代码
  • 控制视图的跳转
登录--->接受用户的登录请求--->处理用户的请求(获取用户登录的参数,username,password)--->交给业务层处理登录业务(判断用户名密码是否正确:事务)--->DAO层查询用户名和密码是否正确--->数据库

9,Filter(重点)

Filter:过滤器,用来过滤网站的数据

  • 处理中文乱码
  • 登录验证

image-20210120201328299

  1. 导包

image-20210120202413131

  1. 编写过滤器,实现Filter接口,重写对应的方法即可
public class CharacterEncodingFilter implements Filter {

	// 初始化: web服务器启动,就已经开始初始化,随时等待过滤对象
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("CharacterEncodingFilter初始化");
	}

	// Chain:链
	/*
	1.过滤器中的所有代码,在过滤特定请求的时候都会被执行
	2.必须让过滤器继续执行
	filterChain.doFilter(servletRequest, servletResponse);
	 */
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		servletRequest.setCharacterEncoding("utf-8");
		servletResponse.setCharacterEncoding("utf-8");
		servletResponse.setContentType("text/html;charset=UTF-8");

		System.out.println("CharacterEncodingFilter执行前...");
		filterChain.doFilter(servletRequest, servletResponse); // 让我们的请求继续走,如果不写,程序到这里就会被拦截!
		System.out.println("CharacterEncodingFilter执行后...");
	}

	// 销毁: web服务器关闭,过滤器才会销毁
	@Override
	public void destroy() {
		System.out.println("CharacterEncodingFilter销毁");
	}
}
  1. 在web.xml中,配置Filter
<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>com.pnca.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <!--只要是/servlet的请求,都会经过这个过滤器-->
    <url-pattern>/servlet/*</url-pattern>
    <!--<url-pattern>/*</url-pattern>-->
</filter-mapping>

10,监听器

  1. 实现一个监听器接口

    public class OnlineCountListener implements HttpSessionListener {
    
    	// 创建session监听
    	// 一旦创建Session就会触发一次这个事件
    	@Override
    	public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    
    		ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
    		System.out.println(httpSessionEvent.getSession().getId());
    		Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
    		if (onlineCount == null) {
    			onlineCount = 1;
    		}else{
    			int count = onlineCount;
    			onlineCount = count + 1;
    		}
    		servletContext.setAttribute("OnlineCount", onlineCount);
    	}
    
    	// 销毁session监听
    	// 一旦销毁Session就会触发一次这个事件
    	@Override
    	public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    		ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
    		Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
    		if (onlineCount == null) {
    			onlineCount = 0;
    		}else{
    			int count = onlineCount;
    			onlineCount = count - 1;
    		}
    		servletContext.setAttribute("OnlineCount", onlineCount);
    	}
    }
  2. web.xml中注册监听器

    <!--注册监听器-->
    <listener>
        <listener-class>com.pnca.listener.OnlineCountListener</listener-class>
    </listener>
  3. 看情况是否使用

11,过滤器,监听器常见应用

监听器: GUI编程中经常使用

用户登录之后才能进入主页!用户注销后就不能进入主页!

  1. 用户登录之后,向Session中放入用户数据

  2. 进入主页的时候要判断用户是否已经登录;要求: 在过滤器中实现

    @Override
    	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    		HttpServletRequest request = (HttpServletRequest)servletRequest;
    		HttpServletResponse response = (HttpServletResponse)servletResponse;
    
    		if(request.getSession().getAttribute(Constant.USER_SESSION) == null) {
    			response.sendRedirect("/error.jsp");
    		}
    
    		filterChain.doFilter(servletRequest, servletResponse);
    	}

12,JDBC

什么是JDBC:java连接数据库

需要jar包的支持:

  • java.spl
  • javax.sql
  • mysql-conneter-java… 连接驱动(必须要导入)

实验环境搭建

  1. 创建一个测试数据库和一个users表

  2. 导入数据库依赖

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.20</version>
    </dependency>
  3. IDEA中连接数据库,注意要设置时区 [serverTimezone=GMT]

    image-20210124201810440

  4. JDBC一般步骤

    // 配置信息
    String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT"; // 注意点
    String username = "****";
    String password = "****";
    
    // 1,加载驱动
    Class.forName("com.mysql.cj.jdbc.Driver");
    // 2,连接数据库
    Connection connection = DriverManager.getConnection(url, username, password);
    // 3,向数据库发送SQL对象的Statement : CRUD
    Statement statement = connection.createStatement();
    // 4.编写sql
    String sql = "select * from users";
    // 5,执行查询sql,返回resultSet结果集
    ResultSet resultSet = statement.executeQuery(sql);
    
    while (resultSet.next()){
        System.out.println("id=" + resultSet.getObject("id"));
        System.out.println("name=" + resultSet.getObject("name"));
        System.out.println("password=" + resultSet.getObject("password"));
        System.out.println("email=" + resultSet.getObject("email"));
        System.out.println("birthday=" + resultSet.getObject("birthday"));
        System.out.println();
    }
    
    // 6,关闭连接,释放资源,掀开的后关
    resultSet.close();
    statement.close();
    connection.close();
    

事务

要么都成功,要么都失败!

ACID: 保证数据的安全。

  • 开启事务
  • 事务提交:commit()
  • 事务回滚:rollback()
  • 关闭事务

Junit测试

image-20210125200341950

image-20210125200414496

搭建一个环境,测试事务

13,SMBMS订单管理系统

1 架构

image-20210126210811332

2 数据库

image-20210126210835622

SQL语句

CREATE DATABASE `smbms`;

USE `smbms`;

DROP TABLE IF EXISTS `smbms_address`;

CREATE TABLE `smbms_address` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `contact` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '联系人姓名',
  `addressDesc` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '收货地址明细',
  `postCode` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '邮编',
  `tel` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '联系人电话',
  `createdBy` BIGINT(20) DEFAULT NULL COMMENT '创建者',
  `creationDate` DATETIME DEFAULT NULL COMMENT '创建时间',
  `modifyBy` BIGINT(20) DEFAULT NULL COMMENT '修改者',
  `modifyDate` DATETIME DEFAULT NULL COMMENT '修改时间',
  `userId` BIGINT(20) DEFAULT NULL COMMENT '用户ID',
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


INSERT  INTO `smbms_address`(`id`,`contact`,`addressDesc`,`postCode`,`tel`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`,`userId`) VALUES (1,'王丽','北京市东城区东交民巷44号','100010','13678789999',1,'2016-04-13 00:00:00',NULL,NULL,1),(2,'张红丽','北京市海淀区丹棱街3号','100000','18567672312',1,'2016-04-13 00:00:00',NULL,NULL,1),(3,'任志强','北京市东城区美术馆后街23号','100021','13387906742',1,'2016-04-13 00:00:00',NULL,NULL,1),(4,'曹颖','北京市朝阳区朝阳门南大街14号','100053','13568902323',1,'2016-04-13 00:00:00',NULL,NULL,2),(5,'李慧','北京市西城区三里河路南三巷3号','100032','18032356666',1,'2016-04-13 00:00:00',NULL,NULL,3),(6,'王国强','北京市顺义区高丽营镇金马工业区18号','100061','13787882222',1,'2016-04-13 00:00:00',NULL,NULL,3);


DROP TABLE IF EXISTS `smbms_bill`;

CREATE TABLE `smbms_bill` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `billCode` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '账单编码',
  `productName` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '商品名称',
  `productDesc` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '商品描述',
  `productUnit` VARCHAR(10) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '商品单位',
  `productCount` DECIMAL(20,2) DEFAULT NULL COMMENT '商品数量',
  `totalPrice` DECIMAL(20,2) DEFAULT NULL COMMENT '商品总额',
  `isPayment` INT(10) DEFAULT NULL COMMENT '是否支付(1:未支付 2:已支付)',
  `createdBy` BIGINT(20) DEFAULT NULL COMMENT '创建者(userId)',
  `creationDate` DATETIME DEFAULT NULL COMMENT '创建时间',
  `modifyBy` BIGINT(20) DEFAULT NULL COMMENT '更新者(userId)',
  `modifyDate` DATETIME DEFAULT NULL COMMENT '更新时间',
  `providerId` BIGINT(20) DEFAULT NULL COMMENT '供应商ID',
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


INSERT  INTO `smbms_bill`(`id`,`billCode`,`productName`,`productDesc`,`productUnit`,`productCount`,`totalPrice`,`isPayment`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`,`providerId`) VALUES (2,'BILL2016_002','香皂、肥皂、药皂','日用品-皂类','块','1000.00','10000.00',2,1,'2016-03-23 04:20:40',NULL,NULL,13),(3,'BILL2016_003','大豆油','食品-食用油','斤','300.00','5890.00',2,1,'2014-12-14 13:02:03',NULL,NULL,6),(4,'BILL2016_004','橄榄油','食品-进口食用油','斤','200.00','9800.00',2,1,'2013-10-10 03:12:13',NULL,NULL,7),(5,'BILL2016_005','洗洁精','日用品-厨房清洁','瓶','500.00','7000.00',2,1,'2014-12-14 13:02:03',NULL,NULL,9),(6,'BILL2016_006','美国大杏仁','食品-坚果','袋','300.00','5000.00',2,1,'2016-04-14 06:08:09',NULL,NULL,4),(7,'BILL2016_007','沐浴液、精油','日用品-沐浴类','瓶','500.00','23000.00',1,1,'2016-07-22 10:10:22',NULL,NULL,14),(8,'BILL2016_008','不锈钢盘碗','日用品-厨房用具','个','600.00','6000.00',2,1,'2016-04-14 05:12:13',NULL,NULL,14),(9,'BILL2016_009','塑料杯','日用品-杯子','个','350.00','1750.00',2,1,'2016-02-04 11:40:20',NULL,NULL,14),(10,'BILL2016_010','豆瓣酱','食品-调料','瓶','200.00','2000.00',2,1,'2013-10-29 05:07:03',NULL,NULL,8),(11,'BILL2016_011','海之蓝','饮料-国酒','瓶','50.00','10000.00',1,1,'2016-04-14 16:16:00',NULL,NULL,1),(12,'BILL2016_012','芝华士','饮料-洋酒','瓶','20.00','6000.00',1,1,'2016-09-09 17:00:00',NULL,NULL,1),(13,'BILL2016_013','长城红葡萄酒','饮料-红酒','瓶','60.00','800.00',2,1,'2016-11-14 15:23:00',NULL,NULL,1),(14,'BILL2016_014','泰国香米','食品-大米','斤','400.00','5000.00',2,1,'2016-10-09 15:20:00',NULL,NULL,3),(15,'BILL2016_015','东北大米','食品-大米','斤','600.00','4000.00',2,1,'2016-11-14 14:00:00',NULL,NULL,3),(16,'BILL2016_016','可口可乐','饮料','瓶','2000.00','6000.00',2,1,'2012-03-27 13:03:01',NULL,NULL,2),(17,'BILL2016_017','脉动','饮料','瓶','1500.00','4500.00',2,1,'2016-05-10 12:00:00',NULL,NULL,2),(18,'BILL2016_018','哇哈哈','饮料','瓶','2000.00','4000.00',2,1,'2015-11-24 15:12:03',NULL,NULL,2);

DROP TABLE IF EXISTS `smbms_provider`;

CREATE TABLE `smbms_provider` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `proCode` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '供应商编码',
  `proName` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '供应商名称',
  `proDesc` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '供应商详细描述',
  `proContact` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '供应商联系人',
  `proPhone` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '联系电话',
  `proAddress` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '地址',
  `proFax` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '传真',
  `createdBy` BIGINT(20) DEFAULT NULL COMMENT '创建者(userId)',
  `creationDate` DATETIME DEFAULT NULL COMMENT '创建时间',
  `modifyDate` DATETIME DEFAULT NULL COMMENT '更新时间',
  `modifyBy` BIGINT(20) DEFAULT NULL COMMENT '更新者(userId)',
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


INSERT  INTO `smbms_provider`(`id`,`proCode`,`proName`,`proDesc`,`proContact`,`proPhone`,`proAddress`,`proFax`,`createdBy`,`creationDate`,`modifyDate`,`modifyBy`) VALUES (1,'BJ_GYS001','北京三木堂商贸有限公司','长期合作伙伴,主营产品:茅台、五粮液、郎酒、酒鬼酒、泸州老窖、赖茅酒、法国红酒等','张国强','13566667777','北京市丰台区育芳园北路','010-58858787',1,'2013-03-21 16:52:07',NULL,NULL),(2,'HB_GYS001','石家庄帅益食品贸易有限公司','长期合作伙伴,主营产品:饮料、水饮料、植物蛋白饮料、休闲食品、果汁饮料、功能饮料等','王军','13309094212','河北省石家庄新华区','0311-67738876',1,'2016-04-13 04:20:40',NULL,NULL),(3,'GZ_GYS001','深圳市泰香米业有限公司','初次合作伙伴,主营产品:良记金轮米,龙轮香米等','郑程瀚','13402013312','广东省深圳市福田区深南大道6006华丰大厦','0755-67776212',1,'2014-03-21 16:56:07',NULL,NULL),(4,'GZ_GYS002','深圳市喜来客商贸有限公司','长期合作伙伴,主营产品:坚果炒货.果脯蜜饯.天然花茶.营养豆豆.特色美食.进口食品.海味零食.肉脯肉','林妮','18599897645','广东省深圳市福龙工业区B2栋3楼西','0755-67772341',1,'2013-03-22 16:52:07',NULL,NULL),(5,'JS_GYS001','兴化佳美调味品厂','长期合作伙伴,主营产品:天然香辛料、鸡精、复合调味料','徐国洋','13754444221','江苏省兴化市林湖工业区','0523-21299098',1,'2015-11-22 16:52:07',NULL,NULL),(6,'BJ_GYS002','北京纳福尔食用油有限公司','长期合作伙伴,主营产品:山茶油、大豆油、花生油、橄榄油等','马莺','13422235678','北京市朝阳区珠江帝景1号楼','010-588634233',1,'2012-03-21 17:52:07',NULL,NULL),(7,'BJ_GYS003','北京国粮食用油有限公司','初次合作伙伴,主营产品:花生油、大豆油、小磨油等','王驰','13344441135','北京大兴青云店开发区','010-588134111',1,'2016-04-13 00:00:00',NULL,NULL),(8,'ZJ_GYS001','慈溪市广和绿色食品厂','长期合作伙伴,主营产品:豆瓣酱、黄豆酱、甜面酱,辣椒,大蒜等农产品','薛圣丹','18099953223','浙江省宁波市慈溪周巷小安村','0574-34449090',1,'2013-11-21 06:02:07',NULL,NULL),(9,'GX_GYS001','优百商贸有限公司','长期合作伙伴,主营产品:日化产品','李立国','13323566543','广西南宁市秀厢大道42-1号','0771-98861134',1,'2013-03-21 19:52:07',NULL,NULL),(10,'JS_GYS002','南京火头军信息技术有限公司','长期合作伙伴,主营产品:不锈钢厨具等','陈女士','13098992113','江苏省南京市浦口区浦口大道1号新城总部大厦A座903室','025-86223345',1,'2013-03-25 16:52:07',NULL,NULL),(11,'GZ_GYS003','广州市白云区美星五金制品厂','长期合作伙伴,主营产品:海绵床垫、坐垫、靠垫、海绵枕头、头枕等','梁天','13562276775','广州市白云区钟落潭镇福龙路20号','020-85542231',1,'2016-12-21 06:12:17',NULL,NULL),(12,'BJ_GYS004','北京隆盛日化科技','长期合作伙伴,主营产品:日化环保清洗剂,家居洗涤专卖、洗涤用品网、墙体除霉剂、墙面霉菌清除剂等','孙欣','13689865678','北京市大兴区旧宫','010-35576786',1,'2014-11-21 12:51:11',NULL,NULL),(13,'SD_GYS001','山东豪克华光联合发展有限公司','长期合作伙伴,主营产品:洗衣皂、洗衣粉、洗衣液、洗洁精、消杀类、香皂等','吴洪转','13245468787','山东济阳济北工业区仁和街21号','0531-53362445',1,'2015-01-28 10:52:07',NULL,NULL),(14,'JS_GYS003','无锡喜源坤商行','长期合作伙伴,主营产品:日化品批销','周一清','18567674532','江苏无锡盛岸西路','0510-32274422',1,'2016-04-23 11:11:11',NULL,NULL),(15,'ZJ_GYS002','乐摆日用品厂','长期合作伙伴,主营产品:各种中、高档塑料杯,塑料乐扣水杯(密封杯)、保鲜杯(保鲜盒)、广告杯、礼品杯','王世杰','13212331567','浙江省金华市义乌市义东路','0579-34452321',1,'2016-08-22 10:01:30',NULL,NULL);


DROP TABLE IF EXISTS `smbms_role`;

CREATE TABLE `smbms_role` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `roleCode` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '角色编码',
  `roleName` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '角色名称',
  `createdBy` BIGINT(20) DEFAULT NULL COMMENT '创建者',
  `creationDate` DATETIME DEFAULT NULL COMMENT '创建时间',
  `modifyBy` BIGINT(20) DEFAULT NULL COMMENT '修改者',
  `modifyDate` DATETIME DEFAULT NULL COMMENT '修改时间',
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


INSERT  INTO `smbms_role`(`id`,`roleCode`,`roleName`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`) VALUES (1,'SMBMS_ADMIN','系统管理员',1,'2016-04-13 00:00:00',NULL,NULL),(2,'SMBMS_MANAGER','经理',1,'2016-04-13 00:00:00',NULL,NULL),(3,'SMBMS_EMPLOYEE','普通员工',1,'2016-04-13 00:00:00',NULL,NULL);


DROP TABLE IF EXISTS `smbms_user`;

CREATE TABLE `smbms_user` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `userCode` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户编码',
  `userName` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户名称',
  `userPassword` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户密码',
  `gender` INT(10) DEFAULT NULL COMMENT '性别(1:女、 2:男)',
  `birthday` DATE DEFAULT NULL COMMENT '出生日期',
  `phone` VARCHAR(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '手机',
  `address` VARCHAR(30) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '地址',
  `userRole` BIGINT(20) DEFAULT NULL COMMENT '用户角色(取自角色表-角色id)',
  `createdBy` BIGINT(20) DEFAULT NULL COMMENT '创建者(userId)',
  `creationDate` DATETIME DEFAULT NULL COMMENT '创建时间',
  `modifyBy` BIGINT(20) DEFAULT NULL COMMENT '更新者(userId)',
  `modifyDate` DATETIME DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT  INTO `smbms_user`(`id`,`userCode`,`userName`,`userPassword`,`gender`,`birthday`,`phone`,`address`,`userRole`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`) VALUES (1,'admin','系统管理员','1234567',1,'1983-10-10','13688889999','北京市海淀区成府路207号',1,1,'2013-03-21 16:52:07',NULL,NULL),(2,'liming','李明','0000000',2,'1983-12-10','13688884457','北京市东城区前门东大街9号',2,1,'2014-12-31 19:52:09',NULL,NULL),(5,'hanlubiao','韩路彪','0000000',2,'1984-06-05','18567542321','北京市朝阳区北辰中心12号',2,1,'2014-12-31 19:52:09',NULL,NULL),(6,'zhanghua','张华','0000000',1,'1983-06-15','13544561111','北京市海淀区学院路61号',3,1,'2013-02-11 10:51:17',NULL,NULL),(7,'wangyang','王洋','0000000',2,'1982-12-31','13444561124','北京市海淀区西二旗辉煌国际16层',3,1,'2014-06-11 19:09:07',NULL,NULL),(8,'zhaoyan','赵燕','0000000',1,'1986-03-07','18098764545','北京市海淀区回龙观小区10号楼',3,1,'2016-04-21 13:54:07',NULL,NULL),(10,'sunlei','孙磊','0000000',2,'1981-01-04','13387676765','北京市朝阳区管庄新月小区12楼',3,1,'2015-05-06 10:52:07',NULL,NULL),(11,'sunxing','孙兴','0000000',2,'1978-03-12','13367890900','北京市朝阳区建国门南大街10号',3,1,'2016-11-09 16:51:17',NULL,NULL),(12,'zhangchen','张晨','0000000',1,'1986-03-28','18098765434','朝阳区管庄路口北柏林爱乐三期13号楼',3,1,'2016-08-09 05:52:37',1,'2016-04-14 14:15:36'),(13,'dengchao','邓超','0000000',2,'1981-11-04','13689674534','北京市海淀区北航家属院10号楼',3,1,'2016-07-11 08:02:47',NULL,NULL),(14,'yangguo','杨过','0000000',2,'1980-01-01','13388886623','北京市朝阳区北苑家园茉莉园20号楼',3,1,'2015-02-01 03:52:07',NULL,NULL),(15,'zhaomin','赵敏','0000000',1,'1987-12-04','18099897657','北京市昌平区天通苑3区12号楼',2,1,'2015-09-12 12:02:12',NULL,NULL);

3 项目搭建

  1. 搭建一个maven web项目

  2. 配置Tomcat

  3. 测试Tomcat服务器能否跑起来

  4. 导入项目中可能遇到的jar包

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
    
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
    
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>
    
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
    
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>
    
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
  5. 创建项目包结构

    image-20210126212615538

  6. 编写实体类

    ORM映射:表-类映射

  7. 编写基础公共类

    1. 数据库配置文件

      driver=com.mysql.cj.jdbc.Driver
      url=jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
      username=root
      password=root
    2. 操作数据库的公共类

      public class BaseDao {
      	private static final String driver;
      	private static final String url;
      	private static final String username;
      	private static final String password;
      
      	// 静态代码块,类加载的时候就初始化了
      	static {
      		Properties properties = new Properties();
      		// 通过类加载器读取对应的资源
      		InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
      		try {
      			properties.load(is);
      			;
      		} catch (IOException e) {
      			e.printStackTrace();
      		}
      
      		driver = properties.getProperty("driver");
      		url = properties.getProperty("url");
      		username = properties.getProperty("username");
      		password = properties.getProperty("password");
      	}
      
      	// 获取数据的连接
      	public static Connection getConnection() {
      		Connection connection = null;
      		try {
      			Class.forName(driver);
      			connection = DriverManager.getConnection(url, username, password);
      		} catch (Exception e) {
      			e.printStackTrace();
      		}
      		return connection;
      	}
      
      	// 编写查询公共方法
      	public static ResultSet execute(Connection connection, String sql, Object[] params, ResultSet resultSet, PreparedStatement preparedStatement) throws SQLException {
      		// 预编译的sql,在后面直接执行就可以了
      		preparedStatement = connection.prepareStatement(sql);
      		for (int i = 0; i < params.length; i++) {
      			// setObject,占位符从1开始,但是我们的数字时从0开始
      			preparedStatement.setObject(i + 1, params[i]);
      		}
      		resultSet = preparedStatement.executeQuery();
      		return resultSet;
      	}
      
      	// 编写增删改公共方法
      	public static int execute(Connection connection, String sql, Object[] params, PreparedStatement preparedStatement) throws SQLException {
      		preparedStatement = connection.prepareStatement(sql);
      		for (int i = 0; i < params.length; i++) {
      			// setObject,占位符从1开始,但是我们的数字时从0开始
      			preparedStatement.setObject(i + 1, params[i]);
      		}
      		return preparedStatement.executeUpdate(); // 返回更新的行数
      	}
      	
      	// 释放资源
      	public static boolean closeResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
      		boolean flag = true;
      
      		if (resultSet != null) {
      			try {
      				resultSet.close();
      				// GC回收
      			} catch (SQLException e) {
      				e.printStackTrace();
      				flag = false;
      			}
      		}
      
      		if (preparedStatement != null) {
      			try {
      				preparedStatement.close();
      				// GC回收
      			} catch (SQLException e) {
      				e.printStackTrace();
      				flag = false;
      			}
      		}
      
      		if (connection != null) {
      			try {
      				connection.close();
      				// GC回收
      			} catch (SQLException e) {
      				e.printStackTrace();
      				flag = false;
      			}
      		}
      		return flag;
      	}
      }
    3. 编写字符编码过滤器

  8. 导入静态资源

4 登录功能的实现

  1. 编写前端页面

  2. 设置首页

    <!--设置欢迎页面-->
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
  3. 编写dao层登录用户登录的接口

    // 得到要登陆的用户
    public User getLoginUser(Connection connection, String userCode) throws SQLException;
  4. 编写dao接口的实现类

    public class UserDaoImpl implements UserDao {
    	@Override
    	public User getLoginUser(Connection connection, String userCode) throws SQLException {
    
    		PreparedStatement pstm = null;
    		ResultSet rs = null;
    		User user = null;
    
    		if (connection != null) {
    			String sql = "select * from smbms_user where userCode=?";
    			Object[] params = {userCode};
    
    			rs = BaseDao.execute(connection, pstm, rs, sql, params);
    
    			if (rs.next()) {
    				user = new User();
    				user.setId(rs.getInt("id"));
    				user.setUserCode(rs.getString("userCode"));
    				user.setUserName(rs.getString("userName"));
    				user.setUserPassword(rs.getString("userPassword"));
    				user.setGender(rs.getInt("gender"));
    				user.setBirthday(rs.getDate("birthday"));
    				user.setPhone(rs.getString("phone"));
    				user.setAddress(rs.getString("address"));
    				user.setUserRole(rs.getInt("userRole"));
    				user.setCreatedBy(rs.getInt("createdBy"));
    				user.setCreationDate(rs.getTimestamp("creationDate"));
    				user.setModifyBy(rs.getInt("modifyBy"));
    				user.setModifyDate(rs.getTimestamp("modifyDate"));
    			}
    			BaseDao.closeResource(null, pstm, rs);
    
    		}
    		return user;
    	}
    }
  5. 业务层接口

    // 用户登录
    public User login(String userCode, String password);
  6. 业务层实现类

    public class UserServiceImpl implements UserService {
    
    	// 业务层都会调用dao层,所以我们要引入Dao层
    	private final UserDao userDao;
    
    	public UserServiceImpl() {
    		userDao = new UserDaoImpl();
    	}
    
    	@Override
    	public User login(String userCode, String password) {
    		Connection connection = null;
    		User user = null;
    
    		try {
    			connection = BaseDao.getConnection();
    			// 通过业务层调用对应的具体的数据库操作
    			user = userDao.getLoginUser(connection, userCode);
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}finally {
    			BaseDao.closeResource(connection, null, null);
    		}
    		return user;
    	}
    	
    }
  7. 编写Servlet

    public class LoginServlet extends HttpServlet {
    
       // Servlet: 控制层,调用业务层代码
    
       @Override
       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          System.out.println("LoginServlet---start....");
    
          // 获取用户名和密码
          String userCode = req.getParameter("userCode");
          String userPassword = req.getParameter("userPassword");
    
          // 和数据库中的密码进行对比,调用业务层
          UserService userService = new UserServiceImpl();
          User user = userService.login(userCode, userPassword);  // 这里已经把登录的人给查出来了
          if (user != null) { // 查由此人,可以登录
             // 将用户的信息放到Session中;
             req.getSession().setAttribute(Constants.USER_SESSION, user);
             // 跳转到主页
             resp.sendRedirect("jsp/frame.jsp");
          }else { // 查无此人,无法登录
             // 转发回登录页面,顺便提示他,用户名或密码错误
             req.getRequestDispatcher("login.jsp").forward(req, resp);
    
          }
       }
    
       @Override
       protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          doGet(req, resp);
       }
    }
  8. 注册Servlet

    <!--Servlet-->
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.pnca.servlet.user.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login.do</url-pattern>
    </servlet-mapping>

5 登录功能优化

  • 注销

    public class LogoutServlet extends HttpServlet {
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		// 移除用户的Constants.USER_SESSION
    		req.getSession().removeAttribute(Constants.USER_SESSION);
    		resp.sendRedirect(req.getContextPath() + "/login.jsp"); // 返回登录页面
    	}
    
    	@Override
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		doGet(req, resp);
    	}
    }
    <servlet>
    		<servlet-name>LogoutServlet</servlet-name>
    		<servlet-class>com.pnca.servlet.user.LogoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LogoutServlet</servlet-name>
        <url-pattern>/jsp/logout.do</url-pattern>
    </servlet-mapping>

登录拦截优化

  • 拦截过滤器

    public class SysFilter implements Filter {
    	@Override
    	public void init(FilterConfig filterConfig) throws ServletException {
    
    	}
    
    	@Override
    	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    		HttpServletRequest request = (HttpServletRequest) servletRequest;
    		HttpServletResponse response = (HttpServletResponse) servletResponse;
    
    		// 过滤器,从Session中获取用户
    		User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
    		if (user == null) { // 已经被移除或者注销了,或者未登录
    			response.sendRedirect("/smbms/error.jsp");
    		}else{
    			filterChain.doFilter(servletRequest, servletResponse);
    		}
    	}
    
    	@Override
    	public void destroy() {
    
    	}
    }
    <!--用户登录过滤器-->
    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.pnca.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/jsp/*</url-pattern>
    </filter-mapping>

6 密码修改

  1. 导入前端素材

  2. 写项目,建议从底层向上写

    image-20210131202002445

  3. UserDao接口

    // 修改当前的用户密码
    public int updatePassword(Connection connection, int id, int password) throws SQLException;
  4. UserDao

    // 修改当前的用户密码
    	@Override
    	public int updatePassword(Connection connection, int id, int password) throws SQLException{
    		PreparedStatement pstm = null;
    		int execute = 0;
    		if (connection != null) {
    			String sql = "update smbms.smbms_user set userPassword = ? where id = ?";
    			Object[] params = {password, id};
    			execute = BaseDao.execute(connection, pstm, sql, params);
    			BaseDao.closeResource(connection, pstm, null);
    		}
    		return execute;
        }
  5. UserService层

    // 根据用户id修改当前的用户密码
    	public boolean updatePassword( int id, int password);
    public boolean updatePassword(int id, int password) {
    		Connection connection = null;
    		boolean flag = false;
    
    		try {
    			connection = BaseDao.getConnection();
    			// 通过业务层调用对应的具体的数据库操作
    			if (userDao.updatePassword(connection, id, password) > 0) {
    				flag = true;
    			}
    		} catch (SQLException e) {
    			e.printStackTrace();
    		} finally {
    			BaseDao.closeResource(connection, null, null);
    		}
    		return flag;
    	}
  6. UserServlet层

    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	// 从Session里面拿id
    	Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
    	boolean flag = false;
    	String newpassword = req.getParameter("newpassword");
    	if (attribute != null && !StringUtils.isNullOrEmpty(newpassword)) {
    		UserService userService = new UserServiceImpl();
    		flag = userService.updatePassword(((User) attribute).getId(), newpassword);
    		if (flag) {
    			req.setAttribute("message", "修改密码成功,请退出,使用新密码登录");
    			// 密码修改成功,移除Session
    			req.getSession().removeAttribute(Constants.USER_SESSION);
    		}else{
    			req.setAttribute("message", "修改密码失败");
    		}
    	} else {
    		req.setAttribute("message", "新密码有问题!");
    	}
    	req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
    }
  7. 记得实现复用,需要提取方法

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		String method = req.getParameter("method");
    		if (method.equals("savepwd")) {
    			this.updatePwd(req, resp);
    		}
    	}

7 用户管理

  1. UserDao接口

    // 查询用户总数
    int getUserCount(Connection connection, String username, int userRole) throws SQLException;
  2. UserDaoImpl

    // 根据用户名或者角色查询用户总数
    	@Override
    	public int getUserCount(Connection connection, String username, int userRole) throws SQLException {
    		PreparedStatement pstm = null;
    		ResultSet rs = null;
    		int count = 0;
    		if (connection != null) {
    			StringBuilder sql = new StringBuilder();
    			sql.append("select count(1) as count from smbms.smbms_user u, smbms.smbms_role r where u.userRole = r.id");
    			ArrayList<Object> list = new ArrayList<>();
    
    			if (!StringUtils.isNullOrEmpty(username)) {
    				sql.append(" and u.userName like ?");
    				list.add("%" + username + "%");
    			}
    
    			if (userRole > 0) {
    				sql.append(" and u.userRole = ?");
    				list.add(userRole);
    			}
    			Object[] params = list.toArray();
    //			System.out.println("UserDaoIml->getUserCount:" + sql.toString());
    			rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);
    			if (rs.next()) {
    				count = rs.getInt("count");
    			}
    			BaseDao.closeResource(null, pstm, rs);
    		}
    		return count;
    	}
  3. UserService层

    // 查询记录数
    	int getUserCount(String username, int userRole);
    @Override
    	public int getUserCount(String username, int userRole) {
    		Connection connection = null;
    		int count = 0;
    
    		try {
    			connection = BaseDao.getConnection();
    			count = userDao.getUserCount(connection, username, userRole);
    		} catch (SQLException e) {
    			e.printStackTrace();
    		} finally {
    			BaseDao.closeResource(connection, null, null);
    		}
    		return count;
    	}
    
  4. UserServlet层

    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	// 从Session里面拿id
    	Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
    	boolean flag = false;
    	String newpassword = req.getParameter("newpassword");
    	if (attribute != null && !StringUtils.isNullOrEmpty(newpassword)) {
    		UserService userService = new UserServiceImpl();
    		flag = userService.updatePassword(((User) attribute).getId(), newpassword);
    		if (flag) {
    			req.setAttribute("message", "修改密码成功,请退出,使用新密码登录");
    			// 密码修改成功,移除Session
    			req.getSession().removeAttribute(Constants.USER_SESSION);
    		}else{
    			req.setAttribute("message", "修改密码失败");
    		}
    	} else {
    		req.setAttribute("message", "新密码有问题!");
    	}
    	req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
    }
  5. 记得实现复用,需要提取方法

14,文件上传


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!