JavaWeb

知行合一

1 Web开发

  • 静态web:html,css
  • 动态web:Servlet/JSP、ASP、PHP

2 Web应用程序

web应用程序编写完毕后,若想提供给外界访问,需要一个服务器统一管理

2.1 组成部分

  • html、css、js

  • jsp、servlet

  • Java程序

  • jar包

  • 配置文件(Properties)

  • Web服务器

  • 静态Web

  • 动态Web

  • 数据库

2.2 Web服务器

服务器用来处理用户的请求和响应信息

  • Request : 请求

  • Response : 响应

  • IIS

微软的:ASP

  • Tomcat

Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,由Apache、Sun 和其他一些公司及个人共同开发而成。由于有了Sun 的参与和支持,最新的Servlet 和JSP 规范总是能在Tomcat 中得到体现,Tomcat 5支持最新的Servlet 2.4 和JSP 2.0 规范。因为Tomcat 技术先进、性能稳定,而且免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为比较流行的Web 应用服务器。

工作三五年,可以尝试手写Tomcat服务器

2.3 动态静态WEB

  • ASP

微软,国内最早,在HTML嵌入VB脚本,维护成本高,页面乱,几千行代码,C#,IIS

  • PHP

PHP开发速度快,跨平台,代码简单(70%,WP),无法承载访问量大的情况

  • JSP/Servlet

B/S《sun公司主推》,C/S,基于java,可以承载三高问问题带来的影响:高并发,高可用,高性能,语法像ASP

  • 动态Web缺点与优点

  • 加入服务器的web出现错误,重新编写后台程序,重新发布

  • 停机维护

  • 可以与数据库交互

  • 可以动态更新,所有用户看到的不是同一个页面

  • 静态Web的缺点

  • 轮播图,点击特效:伪动态

  • JavaScript

  • VBScript

  • 无法与数据库进行交互,数据无法持久化,用户无法交互

3. Tomacat

3.1 基本操作

3.2 文件夹作用

  • bin:启动,关闭的脚本文件
  • conf:配置,核心:server.xml
  • lib:依赖的jar包
  • logs:日志
  • webapps:发存放网站

3.3 配置

  • conf / server.xml 可以配置启动的名称和端口号
1
2
3
<Connector port="8080" protocol="HTTP/1.1" 
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8"/>
  • 默认的主机名为:127.0.0.1/localhost
  • 默认的网站存储位置:webapps
1
2
3
<Host name="localhost"  appBase="webapps"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
  • 可以配置一下环境变量

3.3.1 默认端口号

  • Tomcat :8080
  • mysql:3306
  • http:80
  • https:443

3.3.2 面试题

  • 谈谈一个网站如何运行

  • 客户端:输入一个域名或者ip,

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

  • 有返回对应的IP,这个地址中有我们需要访问的Web程序,可以直接访问,没有,去DNS服务器,找到返回,没有报404

1
127.0.0.1       localhost

3.4 发布一个Web网站

  • 将自己写的网站,放到服务器(Tomcat)中指定的Web应用的文件夹(Webapps)下,就可以访问了

  • 网站应该有的结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
-- webapps : Tomcat服务的Web目录
- ROOT
- xxy : 网站的目录名
- WEB-INF
- classes :java程序
- lib : Web应用所依赖的jar包
- web.xml
- index.html : 默认的首页
- static
- css
- style.css
- js
- img
- ...

4. HTTP

超文本传输协议(Hyper Text Transfer Protocol,HTTP)是一个简单的请求-响应协议,它通常运行在[TCP]之上。它指定了客户端可能发送给服务器什么样的消息以及得到什么样的响应。请求和响应消息的头以[ASCII]形式给出;而消息内容则具有一个类似[MIME]的格式。这个简单模型是早期Web成功的有功之臣,因为它使开发和部署非常地直截了当。

4.1 基础

  • 默认端口:80
  • Https:443 更安全

4.1.1 两个时代

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

4.1.2 HTTP请求

  • 客户端 – 发请求 – 服务器
  • 请求通用:
1
2
3
4
5
Request URL: https://www.baidu.com/ //请求地址
Request Method: GET //get/post方法
Status Code: 200 OK //状态码:200
Remote(远程) Address: 14.215.177.39:443
Referrer Policy: strict-origin-when-cross-origin //第三方协议

(1)请求行

  • 请求行中的请求方式 : GET
  • 请求方式:Get,Post,HEAD,DELETE,PUT,TRACT…
  • Get:请求携带的参数比较少,大小限制,会显示数据内容,不安全,高效
  • Post:请求携带的参数没有限制,大小不限制,不会显示数据内容,安全,不高效

(2)消息头

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Accept:  
//告诉浏览器,它所支持的数据类型
text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br //支持的编码
Accept-Language: zh-CN,zh;q=0.9 //语言环境
Cache-Control: max-age=0 //缓存控制
Connection: keep-alive //告诉浏览器,请求完成是断开还是保持连接
Cookie: BIDUPSID=1142C916CB69356E53A9EE152AC21F23; PSTM=1626077675; BAIDUID=1142C916CB69356E4321E1BE24C3224D:FG=1; __yjs_duid=1_41cb417f65a4f8dbac6d44cde76807851626078324319; BAIDUID_BFESS=1142C916CB69356E4321E1BE24C3224D:FG=1; COOKIE_SESSION=1827474_0_9_9_2_8_1_0_9_7_2_1_1276549_0_0_0_1627960958_0_1629788426%7C9%2310315_10_1626240902%7C7; BD_UPN=12314753; BD_HOME=1; H_PS_PSSID=34442_34068_31253_34584_34505_34871_26350_34761_34825; BA_HECTOR=a40g848k20ah8g80pc1gn4s5j0q
Host: www.baidu.com //主机
sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36

4.1.3 HTTP响应

  • 服务器 – 响应 – 客户端

  • 响应头:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Bdpagetype: 1
Bdqid: 0xb2e001630001bd3b
Cache-Control: private //缓存控制
Connection: keep-alive //连接
Content-Encoding: gzip //编码
Content-Type: text/html;charset=utf-8 //类型
Date: Fri, 22 Oct 2021 08:05:19 GMT
Expires: Fri, 22 Oct 2021 08:05:13 GMT
Server: BWS/1.1
Set-Cookie: BDSVRTM=0; path=/
Set-Cookie: BD_HOME=1; path=/
Set-Cookie: H_PS_PSSID=34442_34068_31253_34584_34505_34871_26350_34761_34825; path=/; domain=.baidu.com
Strict-Transport-Security: max-age=172800
Traceid: 1634889919043977575412889303658247863611
Transfer-Encoding: chunked
X-Frame-Options: sameorigin
X-Ua-Compatible: IE=Edge,chrome=1

(1)响应体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Accept:  
//告诉浏览器,它所支持的数据类型
text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br //支持的编码
Accept-Language: zh-CN,zh;q=0.9 //语言环境
Cache-Control: max-age=0 //缓存控制
Connection: keep-alive //告诉浏览器,请求完成是断开还是保持连接
Cookie: BIDUPSID=1142C916CB69356E53A9EE152AC21F23; PSTM=1626077675; BAIDUID=1142C916CB69356E4321E1BE24C3224D:FG=1; __yjs_duid=1_41cb417f65a4f8dbac6d44cde76807851626078324319; BAIDUID_BFESS=1142C916CB69356E4321E1BE24C3224D:FG=1; COOKIE_SESSION=1827474_0_9_9_2_8_1_0_9_7_2_1_1276549_0_0_0_1627960958_0_1629788426%7C9%2310315_10_1626240902%7C7; BD_UPN=12314753; BD_HOME=1; H_PS_PSSID=34442_34068_31253_34584_34505_34871_26350_34761_34825; BA_HECTOR=a40g848k20ah8g80pc1gn4s5j0q
Host: www.baidu.com //主机
sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36
Refresh: //告诉客户端,多久刷新一次
Location: //让网页重新定位

(2)响应状态码

200: 请求响应成功

3**:请求重定向

4**:找不到资源 404

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

5. Maven

目前是管理Jar包自动导入和配置,对java代码有约束,不要违反

5.1 Maven项目架构管理工具

  • 核心思想:约定大于配置

5.2 下载安装配置

  • maven官网

  • 可以使用镜像下载,下载后解压,所有环境都放入一个文件夹里面

  • 下载安装maven的博主

  • 配置环境变量

  • MAVEN_HOME maven的目录

  • M2_HOME maven目录下的bin的目录

  • Path配置 %MAVEN_HOME%\bin

1
2
# 检查
mvn -version
  • maven 安装目录的 conf/settings.xml
  • 修改配置,阿里云镜像
  • 官网
1
2
3
4
5
6
<mirror>
<id>aliyunmaven</id>
<mirrorOf>*</mirrorOf>
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
  • 自己学习
1
2
3
4
5
6
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf>
<name>Nexus aliyun</name>
<url>https://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
  • 如果想使用其它代理仓库,可在节点中加入对应的仓库使用地址。以使用 spring 代理仓为例:
1
2
3
4
5
6
7
8
9
10
11
<repository>
<id>spring</id>
<url>https://maven.aliyun.com/repository/spring</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>

  • 本地仓库 远程仓库
1
<localRepository>D:\install\apache-maven-3.8.3-bin\apache-maven-3.8.3\maven-repo</localRepository>

5.3 IDEA中使用Maven注意点

  • create from archetype 使用模板;可以不使用
  • 选择Maven-archetype-webapp
  • GroupId 组Id 一般用公司域名倒称com.xxy
  • ArtifactId 项目名
  • maven地址配置 seting
  • 配置项目地址
  • 加载包,出现build success,表示成功
  • IDEA项目构建完成,看Maven配置,MavenHome要注意地址,可能会被改为默认的
  • Maven junit版本报错 将版本改为4.12
  • 标记新建文件夹 java 为 sources root,test为 testsources Root,resources为Resources Root
  • Maven生命周期(lifecycle)命令

clean

validate

compile

test

package

verify

install

site

deploy

  • Maven Plugins
  • Maven Dependencies
  • pom文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?xml version="1.0" encoding="UTF-8"?>
<!--这里是maven的版本号和头文件-->
<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>

<!-- 这是刚刚配置的GAV-->
<groupId>cn.xxy</groupId>
<artifactId>Demo01</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- java应用:jar包
javaWeb应用 :war包-->
<packaging>war</packaging>

<name>Demo01 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<!--配置-->
<properties>
<!-- 默认构建编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--编码版本-->
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<!--项目依赖-->
<dependencies>
<!--具体依赖的jar包和文件-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>

<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.1.1.RELEASE</version>
<scope>compile</scope>
</dependency>-->

</dependencies>
<!--项目构建用的东西-->
<build>
<finalName>Demo01</finalName>
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
</excludes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<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>
</plugins>
</pluginManagement>
</build>
</project>
  • mavne约定大于配置,会帮我导入这个包所依赖的jar包,资源导出可能会失败或无法生效
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    <!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
  • 注意:maven 3.6.2及以上 和jdk8不兼容
  • Maven父子项目
  • 父项目会有
1
2
3
<modules>
<module>MavenTest02</module>
</modules>
  • 子项目会有
1
2
3
4
5
<parent>
<artifactId>MavenTest01</artifactId>
<groupId>cn.xxy</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
  • 父项目的东西子项目可以直接使用
1
son extends parent

5.4 IDEA中配置Tomcat注意点

  • 我们访问一个网站,必须需要配置一个文件夹名字,因为名字映射的是一个文件

  • 当点击+没有发现出现 artifacts 选项的时候 可以 File—setting–build,Execution,deployment—maven —-importing—选择import maven projects automatically–>apply–ok

  • Tomcat乱码

    本质原因就一个:字节流解码为字符串时,使用了错误的字符集\(和编码所用字符集不一致)

    解决方案:将conf\logging.properties文件修改

1
java.util.logging.ConsoleHandler.encoding = GBK
  • Maven中Tomcat无法配置

    原因:Web项目中Web.xml版本问题

    解决方案:替换为Tomcat里面的Web.xml

5.5 Maven 仓库的使用

  • pom.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?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>cn.xxy</groupId>
<artifactId>MavenTest01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<name>MavenTest01 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>

<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-api -->
<!-- <dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp.jsp-api</artifactId>
<version>2.3.3</version>
&lt;!&ndash;<scope>provided</scope>&ndash;&gt;
</dependency>-->



<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>

</dependencies>

<build>
<finalName>MavenTest01</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>
</plugins>
</pluginManagement>
</build>
</project>

  • HelloServlet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package cn.xxy;

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 {
/**
* @param req
* @param resp
* @throws ServletException
* @throws IOException
* @autor xxy
* @date 2021-11-03
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 响应的类型
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
// 获取响应的输出流
try {
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("<h2>你好</h2>");
out.println("</body>");
out.println("</html>");
out.close();
} catch (Exception ex) {
throw ex;
}
}

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

  • web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!--web.xml 是我们的核心配置-->
<!-- 注册servlet-->
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>cn.xxy.HelloServlet</servlet-class>
</servlet>
<!-- 一个servelt对应一个mapping映射-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<!-- 请求路径-->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

6. Servelt

Sun在API提供了一个接口叫Servelt,动态web的一门技术

6.1 建立Servlet步骤

  • 新建maven父子工程
  • 新建一个note.md保存最新的web.xml
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">

</web-app>

  • 编写一个servlet类,继承HttpServlet,HttpServlet继承GenericServlet,GenericServlet实现Servlet接口
  • doGet和doPost只是是实现的方式不同,可以相互调用
  • 编写Servlet映射,Java程序想要浏览器访问需要一个连接Web服务器和一个浏览器能够解析的地址,所以我们需要注册Servlet和映射
1
2
3
4
5
6
7
8
9
10
11
12
 <!--web.xml 是我们的核心配置-->
<!-- 注册servlet-->
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>cn.xxy.servlet.HelloServlet</servlet-class>
</servlet>
<!-- 一个servelt对应一个mapping映射-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<!-- 请求路径-->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
  • 配置Tomcat,启动测试

6.2 Servlet原理

  • 浏览器发送请求
  • Web容器首次访问Servlet
  • Web将请求的信息(请求头等等)给Servlet接口
  • 调用Servlet接口的方法
1
2
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException;
  • 返回Servlet的响应信息
  • Web容器读取响应的信息
  • 返回浏览器

6.3 Mapping问题

  • 一个Servlet映射可以指定一个、多个、通用、自定义、默认映射路径
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!--  注册servlet-->
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>cn.xxy.servlet.HelloServlet</servlet-class>
</servlet>
<!-- 一个servelt对应一个mapping映射-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<!-- 请求路径-->
<url-pattern>/hello</url-pattern>
</servlet-mapping>

<!-- 一个servelt对应通用映射-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>

<!--注意自定义后缀*前面不能加/-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>*.xxy</url-pattern>
</servlet-mapping>

<!--自定义前缀 -->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>hello/dgjdj.ui</url-pattern>
</servlet-mapping>

<!--默认 少用-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
  • 指定了固有的映射路径优先级最高,如果找不到就会走默认的映射路径

7. Servlet Context

Web容器在启动的时候,为每个Web程序都创建一个对应的ServletContext对象,代表当前Web应用

7.1 共享数据

尽量少用,用ssession和cookie代替

  • 栗子
  • HelloServlet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package cn.xxy.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 {
// this.getInitParameter(); 初始化参数
// this.getServletConfig(); 配置
// this.getServletContext(); 上下文
ServletContext servletContext = this.getServletContext();
String username = "xxy";
servletContext.setAttribute("username",username);
// System.out.println("hello world");
}

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

  • GetC.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package cn.xxy.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 GetC extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String username = (String) servletContext.getAttribute("username");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
resp.getWriter().print("名字" + username);

}

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

  • Web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>cn.xxy.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/helloServlet</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>getC</servlet-name>
<servlet-class>cn.xxy.servlet.GetC</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getC</servlet-name>
<url-pattern>/getC</url-pattern>
</servlet-mapping>


</web-app>

7.2 获取初始化参数与请求转发

请求转发:转发的路径不变,它是什么路径就是什么路径,一次请求;重定向:路径会变,两次请求

  • 栗子
  • HelloServlet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package cn.xxy.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 servletContext = this.getServletContext();
String url = servletContext.getInitParameter("url");
resp.getWriter().println(url);
}

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

  • ServletDemo01.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package cn.xxy.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 ServletDemo01 extends HttpServlet {
//请求转发
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
//转发的请求路径
// RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/helloservlet");
// requestDispatcher.forward(req,resp);
servletContext.getRequestDispatcher("/helloservlet").forward(req,resp);

}

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

  • web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>cn.xxy.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/helloservlet</url-pattern>
</servlet-mapping>
</web-app>

  • pom.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?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>cn.xxy</groupId>
<artifactId>MavenTest04</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<parent>
<artifactId>Demo01</artifactId>
<groupId>cn.xxy</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<name>MavenTest04 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<finalName>MavenTest04</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>
</plugins>
</pluginManagement>
</build>
</project>

7.3 读取资源文件

  • 可以放置的位置

在java你目录下

在resources目录下

都能打包到同一路径:classes

  • db.properties
1
2
3
4
# 编译后在classes里面
url =jdbc:mysql://localhost:3306/mybatis
username = root
password = root
  • PropertiesServlet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package cn.xxy.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesServlet extends HelloServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
// InputStream is1 = this.getServletContext().getResourceAsStream("/WEB-INF/classes/aa.properties");
Properties prop = new Properties();
prop.load(is);
// prop.load(is1);
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
resp.getWriter().println(url + ":" + username + ":" + password);
}

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

  • pom.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?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>cn.xxy</groupId>
<artifactId>MavenTest04</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<parent>
<artifactId>Demo01</artifactId>
<groupId>cn.xxy</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<name>MavenTest04 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<finalName>MavenTest04</finalName>
<!--在build中配置resources,来防止我们资源导出失败的问题-->

<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>

<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->

</pluginManagement>
</build>
</project>

  • web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>

<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>cn.xxy.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/helloservlet</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>servletDemo01</servlet-name>
<servlet-class>cn.xxy.servlet.ServletDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletDemo01</servlet-name>
<url-pattern>/servletDemo01</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>propertiesServlet</servlet-name>
<servlet-class>cn.xxy.servlet.PropertiesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>propertiesServlet</servlet-name>
<url-pattern>/propertiesServlet</url-pattern>
</servlet-mapping>
</web-app>

8. HttpServletRequest

HttpServletRequest请求代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中所有信息都会封装到HttpServletRequest,通过这个方法,可以获取客户端的所有信息

8.1 获取前端传过来的参数和请求转发

  • index.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>cyyzm</title>

<script type="text/javascript">
function change(obj) {
/* 给服务器传递一个时间戳(参数),每一个时刻点击的时候都会发送不同的参数,这样就会骗过服务器一直重新做加载,而不会加载缓存。 做到每点击一次就刷新一次显示的图片*/
obj.src = "/CheckCodeServlet?time=" + new Date().getTime();
}
</script>

</head>
<body>
<h2>Hello World!</h2>
<form action="/RegistServlet" method="post">
用户名 : <input name="username" type="text" > </br>
密码 : <input name="password" type="password"> </br>
爱好 :
<input type="checkbox" name="hobbies" value="美"> 美
<input type="checkbox" name="hobbies" value="音"> 音
<input type="checkbox" name="hobbies" value="体"> 体
<input type="checkbox" name="hobbies" value="文"> 文 </br>

<input type="text" placeholder="请输入验证码..." name = "code"> <img src="/CheckCodeServlet" onclick="change(this)"> <br /><br />

<input type="submit" value="注册">
</form>
</body>

</html>

  • RegistServlet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package cn.xxy.servlet;

import java.io.IOException;
import java.util.Arrays;
import javax.servlet.ServletException;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.jsp.PageContext;


//@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

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

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置字符集
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Content-Encoding","utf-8");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
//接收请求参数
String code = request.getParameter("code");
String userName = request.getParameter("username");
String password = request.getParameter("password");
String[] hobbies = request.getParameterValues("hobbies");
System.out.println(Arrays.toString(hobbies));

//将输入的文字转换为utf-8编码形式
//byte[] bytes = code.getBytes("ISO8859-1");
// byte[] bytes = code.getBytes("ISO8859-1");
// code = new String(bytes,"UTF-8");
System.out.println(code);
System.out.println(userName + " " + password);

//取出一开始存放 的word 成语绘图处理界面在绘制图片的时候已经将所绘制的文字存放到了ServerletContext域当中了
String word = (String)this.getServletContext().getAttribute("checkCode");



//两个做对比
if (!code.equals(word)) {
response.getWriter().write("验证码错误 ");
response.setHeader("refresh","3;url= /index.jsp");
} else {
// response.getWriter().write("注册 成功 ");
// 重定向
// response.sendRedirect("/success.jsp");
// 请求转发
// '/'代表当前根目录 相当于request.getContextPath()
request.getRequestDispatcher(request.getContextPath() + "/success.jsp").forward(request,response);
}
}



}

9.HttpServletResponse

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

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

9.1 简单分类

  • 负责向浏览器发送数据的方法
1
2
3
ServletOutputStream getOutputStream() throws IOException;

PrintWriter getWriter() throws IOException;
  • 负责向浏览器发送响应头的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void setCharacterEncoding(String var1);

void setContentLength(int var1);

void setContentType(String var1);

void setBufferSize(int 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);
  • 响应的状态码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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;

9.2 向浏览器输出消息和下载文件

  • 下载文件
  • 要获取下载文件的路径
  • 下载的文件名叫什么
  • 设置想办法让浏览器能够支持下载我们需要的东西
  • 获取下载为文件的输入流
  • 创建缓冲区
  • 获取OutputStream对象
  • 将FileOutputStream流写入到buffer缓冲区
  • 使用OutputStream将缓冲区中的数据输出到客户端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package cn.xxy.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 {
// - 要获取下载文件的路径
// String realPath = this.getServletContext().getRealPath("/1.png");
String realPath = "D:\\ideawork\\Demo01\\MavenTest04\\src\\main\\resources\\你好.png";
System.out.println("下载文件的路径:" + realPath);
// - 下载的文件名叫什么
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
// - 设置想办法让浏览器能够支持下载我们需要的东西 中文文件名URLEncoder.encode编码,否则有可能乱码
resp.setHeader("Content-Disposition","attachment;fileName = " + URLEncoder.encode(fileName,"utf-8"));
// - 获取下载为文件的输入流
FileInputStream in = new FileInputStream(realPath);
// - 创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
// - 获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
// - 将FileOutputStream流写入到buffer缓冲区 - 使用OutputStream将缓冲区中的数据输出到客户端
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0 , len);
}
in.close();
out.close();

}

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

9.3 验证码

  • 前端实现,js实现
  • 后端实现,需要用到java图片类,生产一个图片
  • 数字验证码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package cn.xxy.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.util.Random;

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 g = (Graphics2D) image.getGraphics();
//设置图片背景
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/jpeg");
//网站存在缓存,不让浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
//把图片写给浏览器
ImageIO.write(image, "jpg", resp.getOutputStream());

}
//生成随机数
private String makeNum() {
Random random = new Random();
String num = random.nextInt(9999999) + "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 7-num.length(); i++) {
sb.append("0");
}
num = sb.toString() + num;
return num;
}

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

  • 成语验证码
  • cyyzm.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<script type="text/javascript">
function change(obj) {
/* 给服务器传递一个时间戳(参数),每一个时刻点击的时候都会发送不同的参数,这样就会骗过服务器一直重新做加载,而不会加载缓存。 做到每点击一次就刷新一次显示的图片*/
obj.src = "/CheckCodeServlet?time=" + new Date().getTime();
}
</script>

</head>
<body>

<form action="/RegistServlet">
<!--在图片标签中的src图片地址直接填上绘制图片的后台Servlet即可-->
<input type="text" placeholder="请输入验证码..." name = "code"> <img src="/CheckCodeServlet" onclick="change(this)"> <br />
<input type="submit" value="注册">
</form>


</body>
</html>
  • CheckCodeServlet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
RegistServletpackage cn.xxy.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


//@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

// 集合中保存所有成语
private List<String> words = new ArrayList<String>();

@Override
public void init() throws ServletException {
// 初始化阶段,读取new_words.txt
// web工程中读取 文件,必须使用绝对磁盘路径
String path = getServletContext().getRealPath("/WEB-INF/word.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(path));
String line;
//把读的成语全部添加到一个集合当中
while ((line = reader.readLine()) != null) {
words.add(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//每5秒刷新一次
response.setHeader("Refresh","60");
// 禁止缓存
response.setHeader("Cache-Control", "no-cache");
//设置过期时间为立即过期
response.setDateHeader("Expires", 0);
response.setHeader("Pragma","no-cache");
response.setHeader("Content-Encoding","utf-8");
int width = 420;
int height = 30;
// 步骤一 绘制一张内存中图片
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 步骤二 图片绘制背景颜色 ---通过绘图对象
Graphics graphics = (Graphics2D) bufferedImage.getGraphics();// 得到画图对象 --- 画笔
// 绘制任何图形之前 都必须指定一个颜色
graphics.setColor(getRandColor(200, 250));
graphics.fillRect(0, 0, width, height);
// 步骤三 绘制边框
graphics.setColor(Color.WHITE);
graphics.drawRect(0, 0, width - 1, height - 1);
// 步骤四 四个随机数字
Graphics2D graphics2d = (Graphics2D) graphics;
// 设置输出字体
graphics2d.setFont(new Font("宋体", Font.BOLD, 18));
Random random = new Random();// 生成随机数
int index = random.nextInt(words.size());
String word = words.get(index);// 获得成语
System.out.println(word);
// 定义x坐标
int x = 10;
for (int i = 0; i < word.length(); i++) {
// 随机颜色
graphics2d.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
// 旋转 -30 --- 30度
int jiaodu = random.nextInt(60) - 30;
// 换算弧度
double theta = jiaodu * Math.PI / 180;

// 获得字母数字
char c = word.charAt(i);

// 将c 输出到图片
graphics2d.rotate(theta, x, 20);
graphics2d.drawString(String.valueOf(c), x, 20);
graphics2d.rotate(-theta, x, 20);
x += 30;
}

// 将验证码内容保存session
//request.getSession().setAttribute("checkcode_session", word);
//把生成的验证码存放到全局域对象当中
this.getServletContext().setAttribute("checkCode", word);
// 步骤五 绘制干扰线
graphics.setColor(getRandColor(160, 200));
int x1;
int x2;
int y1;
int y2;
for (int i = 0; i < 30; i++) {
x1 = random.nextInt(width);
x2 = random.nextInt(12);
y1 = random.nextInt(height);
y2 = random.nextInt(12);
graphics.drawLine(x1, y1, x1 + x2, x2 + y2);
}
// 将上面图片输出到浏览器 ImageIO
graphics.dispose();// 释放资源
//将图片写到response.getOutputStream()中
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

/**
* 取其某一范围的color
*
* @param fc
* int 范围参数1
* @param bc
* int 范围参数2
* @return Color
*/
private Color getRandColor(int fc, int bc) {
// 取其随机颜色
Random random = new Random();
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}

}
  • RegistServlet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package cn.xxy.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.jsp.PageContext;


//@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收请求参数
String code = request.getParameter("code");
System.out.println(code);

//将输入的文字转换为utf-8编码形式
//byte[] bytes = code.getBytes("ISO8859-1");
//byte[] bytes = code.getBytes("ISO8859-1");
// code = new String(bytes,"UTF-8");
System.out.println(code);

//取出一开始存放 的word 成语绘图处理界面在绘制图片的时候已经将所绘制的文字存放到了ServerletContext域当中了
String word = (String)this.getServletContext().getAttribute("checkCode");


//设置字符集
response.setContentType("text/html;charset=UTF-8");

//两个做对比
if (!code.equals(word)) {
response.getWriter().write("验证码错误 ");
response.setHeader("refresh","3;url= ../target/MavenTest04/cyyzm.html");
} else {
response.getWriter().write("注册 成功 ");
}

}

}
  • web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
<servlet-mapping>
<servlet-name>CheckCodeServlet</servlet-name>
<url-pattern>/CheckCodeServlet</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>RegistServlet</servlet-name>
<servlet-class>cn.xxy.servlet.RegistServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegistServlet</servlet-name>
<url-pattern>/RegistServlet</url-pattern>
</servlet-mapping>
  • word.txt
1
2
3
4
5
6
擎天柱
空城计
救世主
丑八怪
美人计
里程碑

9.4 实现重定向

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

类别 代码 发送请求 地址改变 共享参数 跨域 访问WEB-INF目录(不能被外部通过地址直接访问) 数字
请求转发 req.getRequestDispatcher(“/WEB-INF/views/student.jsp”).forward(req,resp); 一次 不会改变 可以共享 不能 307
重定向 resp.sendRedirect(“/day02_01/WEB-INF/views/student.jsp”) 两次 会改变 不可以 可以 不能 302
1
public void sendRedirect(String location) throws IOException;
  • Redirect.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package cn.xxy.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 Redirect extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/**
* 原理: resp.setHeader("Location","/imageServlet");
* resp.setStatus(302);
*/

resp.sendRedirect("/imageServlet");
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
  • web.xml
1
2
3
4
5
6
7
8
<servlet>
<servlet-name>Redirect</servlet-name>
<servlet-class>cn.xxy.servlet.Redirect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Redirect</servlet-name>
<url-pattern>/Redirect</url-pattern>
</servlet-mapping>

9.5 登录

  • index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>cyyzm</title>

<script type="text/javascript">
function change(obj) {
/* 给服务器传递一个时间戳(参数),每一个时刻点击的时候都会发送不同的参数,这样就会骗过服务器一直重新做加载,而不会加载缓存。 做到每点击一次就刷新一次显示的图片*/
obj.src = "/CheckCodeServlet?time=" + new Date().getTime();
}
</script>

</head>
<body>
<h2>Hello World!</h2>
<form action="/RegistServlet" method="post">
用户名 : <input name="username" type="text" > </br>
密码 : <input name="password" type="password"> </br>
<input type="text" placeholder="请输入验证码..." name = "code"> <img src="/CheckCodeServlet" onclick="change(this)"> <br /><br />
<input type="submit" value="注册">
</form>
</body>

</html>

  • RegistServlet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package cn.xxy.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.jsp.PageContext;


//@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收请求参数
String code = request.getParameter("code");
String userName = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(code);

//将输入的文字转换为utf-8编码形式
//byte[] bytes = code.getBytes("ISO8859-1");
//byte[] bytes = code.getBytes("ISO8859-1");
// code = new String(bytes,"UTF-8");
System.out.println(code);
System.out.println(userName + " " + password);

//取出一开始存放 的word 成语绘图处理界面在绘制图片的时候已经将所绘制的文字存放到了ServerletContext域当中了
String word = (String)this.getServletContext().getAttribute("checkCode");


//设置字符集
response.setContentType("text/html;charset=UTF-8");

//两个做对比
if (!code.equals(word)) {
response.getWriter().write("验证码错误 ");
response.setHeader("refresh","3;url= ../target/MavenTest04/cyyzm.html");
} else {
response.getWriter().write("注册 成功 ");
}

}

}

9.5 上传

  • 上传注意

    • 上传文件要放在外界访问不到的目录下,比如WEB-INF下
    • 为防止文件覆盖,需要重命名唯一的名字

    时间戳、UUID、md5、位运算算法

    • 限制文件上传的最大值
    • 限制上传文件的类型

10. Cookie、Session

10.1 不同点

名称 存储位置 存储容量 存储方式 隐私策略 有效期 服务器压力 浏览器支持 跨域支持
Cookie 客户端浏览器 <=4KB,最多保存20个Cookie,300个cookie浏览器上限 只能保管ASCII字符串 客户端可见,不安全 设置cookie的属性长期有效 不占用服务器资源,并发 禁用或不支持cookie,则会话跟踪会失效,能够设置子窗口 cookie支持跨域名访问
Session 服务器 设置session删除机制,没有上限 任何 透明对 只需关闭窗口该session就会失效 耗费大量的内存 需要使用URL地址重写的方式,本窗口以及子窗口 session不支持跨域名访问

10.2 会话

  • 会话

用户打开浏览器,点开很多超链接,关闭浏览器,过程叫会话

  • 有状态会话

服务器保存用户信息,下次登录或者来时,知道曾经登录或者来过

  • 服务器给客户端一个信件,客户端下次访问服务端带上信件就可以了 -Cookie
  • 服务器登记过你了,下次来的时候我来匹配你 -Session
  • 从请求中拿到cookie信息
  • 服务器响应给客户端cookie
1
2
3
4
5
6
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

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

  • CookieDemo01.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package cn.xxy.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 CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
Cookie[] cookies = req.getCookies();
if (cookies != null) {
out.write("你上一次访问的时间是:");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
//获取cookie的名字
// if (cookie.getName().equals("lastLoginTime")) {
// Long lastLoginTime = Long.valueOf(cookie.getValue());
// Date date = new Date(lastLoginTime);
// out.write(date.toLocaleString());
// }
if (cookie.getName().equals("name")) {
out.write(URLDecoder.decode(cookie.getValue(),"utf-8"));
}

}
} else {
out.write("这是您第一次访问");
}
//服务给客户端响应一个
// Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
Cookie cookie = new Cookie("name", URLEncoder.encode("这里","utf-8"));
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);

}

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

  • web.xml
1
2
3
4
5
6
7
8
<servlet>
<servlet-name>CookieDemo01</servlet-name>
<servlet-class>cn.xxy.servlet.CookieDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieDemo01</servlet-name>
<url-pattern>/CookieDemo01</url-pattern>
</servlet-mapping>

10.4 Session

10.4.1 使用场景

  • 保存登录用户的信息
  • 购物车信息
  • 在整个网站中经常会使用的数据

10.4.2 使用Session

  • 新建session
  • SessionDemo01.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package cn.xxy.servlet;

import cn.xxy.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
resp.setContentType("text/html");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//获取session
HttpSession session = req.getSession();
//得到session存储信息
session.setAttribute("person",new Person("he",22));
//获取session的id
String id = session.getId();
//判断session是不是新创建的
if (session.isNew()) {
resp.getWriter().write("Seesion创建成功,ID:" + id);
} else {
resp.getWriter().write("ID为:" + id + "的seesion在服务器中已经存在了");
}
//session在创建的时候做了什么
Cookie jsessionid = new Cookie("JSESSIONID", id);
resp.addCookie(jsessionid);

}

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

  • 共享数据
  • SessionDemo02.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package cn.xxy.servlet;

import cn.xxy.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class SessionDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
resp.setContentType("text/html");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//获取session
HttpSession session = req.getSession();
//得到session存储信息
Person person = (Person) session.getAttribute("person");
System.out.println(person.toString());


}

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

  • 销毁session
  • SessionDemo03.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package cn.xxy.servlet;

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 {
HttpSession session = req.getSession();
session.removeAttribute("person");
//手动注销
session.invalidate();

}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
  • Session自动过期和配置文件

  • web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>CookieDemo01</servlet-name>
<servlet-class>cn.xxy.servlet.CookieDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieDemo01</servlet-name>
<url-pattern>/CookieDemo01</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>SessionDemo01</servlet-name>
<servlet-class>cn.xxy.servlet.SessionDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionDemo01</servlet-name>
<url-pattern>/SessionDemo01</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>SessionDemo02</servlet-name>
<servlet-class>cn.xxy.servlet.SessionDemo02</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionDemo02</servlet-name>
<url-pattern>/SessionDemo02</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>SessionDemo03</servlet-name>
<servlet-class>cn.xxy.servlet.SessionDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionDemo03</servlet-name>
<url-pattern>/SessionDemo03</url-pattern>
</servlet-mapping>

<!-- 设置session自动失效时间-->
<session-config>
<!-- 15分钟session自动失效,单位为分钟-->
<session-timeout>15</session-timeout>
</session-config>
</web-app>
  • 共享还可以是用ApplicationContext,全局上下文

11. Jsp

此技术比较老旧,重点了解思路和方式

11.1 Jsp怎么运行的

  • 代码
  • 服务器内部工作

Tomcat有一个work工作夹,IDEA中使用Tomcat会在IDEA的Tomcat中生产一个work目录

1
C:\Users\.IntelliJIdea2019.3\system\tomcat\Unnamed_Demo01\work\Catalina\localhost\_\org\apache\jsp

发现页面变为了.java程序

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

Jsp本质上就是一个Servlet

Jsp最终会被转换成为一个Java类,编译为.class文件供用户访问,也就是Servlet

  • index_jsp.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {

private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();

private static java.util.List _jspx_dependants;

private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.AnnotationProcessor _jsp_annotationprocessor;

public Object getDependants() {
return _jspx_dependants;
}
//初始化
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
}
//销毁
public void _jspDestroy() {
}
//JspService
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
//1.判断请求,我这里没有
//2.内置一些对象,可以直接在页面使用 <% %>
PageContext pageContext = null;//页面上下文
HttpSession session = null;//session
ServletContext application = null;//aplicationContext
ServletConfig config = null;//config
JspWriter out = null;//out
Object page = this;//page:当前页
//HttpServletRequest request 请求
//HttpServletResponse response 响应
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;

//输出页面前 可以在页面使用${}
try {
response.setContentType("text/html");//设置响应的页面类型
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;
//输出的页面
out.write("<html>\n");
out.write("<body>\n");
out.write("<h2>Hello World!</h2>\n");
out.write("</body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}

  • 每次点击重启,删除work,然后重新生成

在Jsp中只要是java代码原本不动输出,如果是HTML代码就会转换为:

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

11.2 基本语法

  • JSP声明:会被编译到JSP生成的Java类中,其他的则是会被生成到_jspService方法中
1
2
3
<% %>
<!--JSP注释不会在前端显示-->
<!--组件化-->

11.3 九大内置对象

  • pageContext 保存的数据只在一个页面中有效
  • request 保存的数据只在一次请求或者请求转发中有效,产生的数据,用户看完就没用了,新闻
  • response
  • application[ServletContext] 保存的数据只在服务器中有效,一个用完其他可能接着用,聊天数
  • session 保存的数据只在一次会话中有效,产生的数据,用户用完一会还有用,购物车
  • config[ServletConfig]
  • out
  • page
  • exception

查找保存的从底层到高层 page-request-session-application,类似于JVM双亲委派机制

11.4 Jsp标签、JSTL标签、EL表达式

11.4.1 EL表达式

${}

  • 获取数据
  • 执行运算
  • 获取Web开发的常用对象
  • 调用Java方法

11.4.2 加入的依赖

  • pom.xml
1
2
3
4
5
6
7
8
9
10
11
12
<!--    JSTL表达式的依赖-->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!-- standard标签库-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>

11.4.3 JSP标签

  • index.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%-- 内置对象--%>
<%--<jsp:include page="/index.jsp"></jsp:include>--%>
<jsp:forward page="index.jsp">
<jsp:param name="name" value="xx"/>
<jsp:param name="age" value="12"/>
</jsp:forward>
</body>
</html>

11.4.4 JSTL表达式

JSTL标签为了弥补HTML语言的不足,封装了JSP应用的通用核心功能

  • 核心标签

  • SQL标签

  • XML标签

  • JSTL函数

  • index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--引入JSTL核心标签库,我们才能使用JSTL标签,Tomcat也要引入JSTL的包,否则会报错:JSTL解析错误--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
ArrayList<String> pepole = new ArrayList<>();
pepole.add("在");
pepole.add("jdh");
pepole.add("jfid");
pepole.add("好几顿饭");
pepole.add("djhf");
pepole.add("djhf")
request.setAttribute("list",pepole);
%>
<%--
var 每一次遍历的对象
items 受遍历的对象
begin 开始遍历的下标
end 结束遍历的下标
step 步长
--%>
<c:forEach var="pepole" items="${list}" begin="1" end="3" step="2" >
<c:out value="${pepole}" />
</c:forEach>

</body>
</html>

12. JavaBean、MVC、过滤器、监听器

对象关系映射 ORM

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

12.1 MVC(model-view-controller)

现在MVVM

  • Controller(Servlet)

接收客户的请求(req,session),响应给客户端内容,重定向或转发

  • view

展示数据,提供可以供我们操作的请求

  • 数据库(JDBC)
  • Model(JavaBen、Service、Dao)

控制业务操作,crud,导入导出,批量操作

  • JavaBen(pojo、entity【vo、dto】)

  • Service

  • Dao

  • 登录

登录-接收用户的登录请求,处理用户的请求,获取用户登录的参数-交给业务层处理(判断用户名密码是否正确:事务)-Dao查询用户名密码是否正确-数据库

12.2 Filter过滤器

处理乱码,登录验证

  • 导包
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!--    JSTL表达式的依赖-->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!-- standard标签库-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
  • 编写过滤器

  • CharacterEncodingFilter.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package cn.xxy.servlet;

import javax.servlet.*;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter {
//初始化,服务器启动的时候就初始化了
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter初始化");
}
//FilterChain 链

/**
* 1.过滤中的所有代码,在过滤特定的请求的时候都会执行
* 2. 必须注意让过滤器继续同行 filterChain.doFilter(request,response);
* @param request
* @param response
* @param filterChain
* @throws IOException
* @throws ServletException
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
System.out.println("CharacterEncodingFilter执行前");
//让我们的请求继续走,如果不写,程序到这里就被拦截停止
filterChain.doFilter(request,response);
System.out.println("CharacterEncodingFilter执行后");

}

//销毁
@Override
public void destroy() {
System.out.println("CharacterEncodingFilter销毁");
}
}

  • ShowServlet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package cn.xxy.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 ShowServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setContentType("text/html");
// resp.setCharacterEncoding("utf-8");
resp.getWriter().write("你好,世界");
}

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

  • web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<servlet>
<servlet-name>ShowServlet</servlet-name>
<servlet-class>cn.xxy.servlet.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/ShowServlet</url-pattern>
</servlet-mapping>


<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>cn.xxy.servlet.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

12.3 监听器

  • 编写监听器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package cn.xxy.lister;


import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//统计网站在线人数 :统计session
public class OnlineCountListener implements HttpSessionListener {
//创建session监听:看你的一举一动
//一旦创建Session就会触发一次这个事件
@Override
public void sessionCreated(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");

if (onlineCount == null) {
onlineCount = Integer.valueOf("1");
} else {
int count = onlineCount.intValue();
count += 1;
onlineCount = Integer.valueOf(count+"");
}
ctx.setAttribute("OnlineCount",onlineCount);
}
//销毁Session监听
//一旦销毁Session就会触发一次这个事件
@Override
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");

if (onlineCount == null) {
onlineCount = Integer.valueOf("0");
} else {
int count = onlineCount.intValue();
count -= 1;
onlineCount = Integer.valueOf(count+"");
}
ctx.setAttribute("OnlineCount",onlineCount);
}
}

  • web.xml
1
2
3
<listener>
<listener-class>cn.xxy.lister.OnlineCountListener</listener-class>
</listener>

13. JDBC

  • 导入数据库依赖
1
2
3
4
5
6
7
8
<dependencies>
<!-- mysql的驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
  • JDBC通用步骤

  • TestJdbc.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.sql.*;

public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=GMT&useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=GMT";
String name = "root";
String password = "root";
//1. 加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库
Connection connection = DriverManager.getConnection(url,name,password);
//3.向数据库发送SQL的对象CRUD
Statement statement = connection.createStatement();
//4.编写SQL
String sql = "select * from t_dept";
//5.执行查询,返回结果集
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
System.out.println("id=" + rs.getObject("dept_id"));
}
//6.关闭连接,释放资源,一定是先开后关
rs.close();
statement.close();
connection.close();

}
}

  • 事务ACID

@Test注解只能作用于方法上

14. SMBMS【超市订单管理系统】

14.1. 配置

  • SQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
CREATE DATABASE `smbms`;

USE `smbms`;


CREATE TABLE if not exists `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);

select `id`,`contact`,`addressDesc`,`postCode`,`tel`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`,`userId` from `smbms_address`;


CREATE TABLE if not exists `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);

select `id`,`billCode`,`productName`,`productDesc`,`productUnit`,`productCount`,`totalPrice`,`isPayment`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`,`providerId` from `smbms_bill`;


CREATE TABLE if not exists `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);

select `id`,`proCode`,`proName`,`proDesc`,`proContact`,`proPhone`,`proAddress`,`proFax`,`createdBy`,`creationDate`,`modifyDate`,`modifyBy` from `smbms_provider`


CREATE TABLE if not exists `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);

select `id`,`roleCode`,`roleName`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate` from `smbms_role`



CREATE TABLE if not exists `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);

select `id`,`userCode`,`userName`,`userPassword`,`gender`,`birthday`,`phone`,`address`,`userRole`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate` from `smbms_user`

  • 搭建一个Maven Web项目

  • web.xml

1
2
3
4
5
6
7
8
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">

</web-app>

  • 配置Tomcat
  • 测试项目跑起来
  • 导入项目中会遇到的jar包
  • pom.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?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>cn.xxy</groupId>
<artifactId>smbms</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<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.3</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>

<!-- JSTL表达式的依赖,记得Tomcat需要导包-->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!-- standard标签库-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>

</project>
  • 创建项目包结构

  • 编写实体类

  • User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package cn.xxy.pojo;
import java.util.Date;

/**
* @author xxy
* @date 2021/11/9
* 用户类
*/
public class User {
/**
* id id
*/
private Integer id;
/**
* userCode 用户编码
*/
private String userCode;
/**
* userName 用户名称
*/
private String userName;
/**
* userPassword 用户密码
*/
private String userPassword;
/**
* gender 性别
*/
private Integer gender;
/**
* birthday 出生日期
*/
private Date birthday;
/**
* phone 电话
*/
private String phone;
/**
* address 地址
*/
private String address;
/**
* userRole 用户角色
*/
private Integer userRole;
/**
* createdBy 创建者
*/
private Integer createdBy;
/**
* creationDate 创建时间
*/
private Date creationDate;
/**
* modifyBy 更新者
*/
private Integer modifyBy;
/**
* modifyDate 更新时间
*/
private Date modifyDate;
/**
* age 年龄
*/
private Integer age;
/**
* userRoleName 用户角色名称
*/
private String userRoleName;


public String getUserRoleName() {
return userRoleName;
}
public void setUserRoleName(String userRoleName) {
this.userRoleName = userRoleName;
}
public Integer getAge() {
Date date = new Date();
Integer age = date.getYear()-birthday.getYear();
return age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getUserRole() {
return userRole;
}
public void setUserRole(Integer userRole) {
this.userRole = userRole;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}

}
  • Bill.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package cn.xxy.pojo;

import java.math.BigDecimal;
import java.util.Date;

/**
* @author xxy
* @date 2021-11-09
* Bill 订单类
*/
public class Bill {
/**
*id id
*/
private Integer id;
/**
*billCode 账单编码
*/
private String billCode;
/**
*productName 商品名称
*/
private String productName;
/**
*productDesc 商品描述
*/
private String productDesc;
/**
*productUnit商品单位
*/
private String productUnit;
/**
*productCount 商品数量
*/
private BigDecimal productCount;
/**
*totalPrice 总金额
*/
private BigDecimal totalPrice;
/**
*isPayment 是否支付
*/
private Integer isPayment;
/**
*providerId 供应商ID
*/
private Integer providerId;
/**
*createdBy 创建者
*/
private Integer createdBy;
/**
*creationDate 创建时间
*/
private Date creationDate;
/**
*modifyBy 更新者
*/
private Integer modifyBy;
/**
*modifyDate 更新时间
*/
private Date modifyDate;
/**
*providerName 供应商名称
*/
private String providerName;


public String getProviderName() {
return providerName;
}
public void setProviderName(String providerName) {
this.providerName = providerName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBillCode() {
return billCode;
}
public void setBillCode(String billCode) {
this.billCode = billCode;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductDesc() {
return productDesc;
}
public void setProductDesc(String productDesc) {
this.productDesc = productDesc;
}
public String getProductUnit() {
return productUnit;
}
public void setProductUnit(String productUnit) {
this.productUnit = productUnit;
}
public BigDecimal getProductCount() {
return productCount;
}
public void setProductCount(BigDecimal productCount) {
this.productCount = productCount;
}
public BigDecimal getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(BigDecimal totalPrice) {
this.totalPrice = totalPrice;
}
public Integer getIsPayment() {
return isPayment;
}
public void setIsPayment(Integer isPayment) {
this.isPayment = isPayment;
}

public Integer getProviderId() {
return providerId;
}
public void setProviderId(Integer providerId) {
this.providerId = providerId;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}

  • Role.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package cn.xxy.pojo;

import java.util.Date;

/**
* @author xxy
* @date 2021-11-09
* Role 角色类
*/
public class Role {
/**
*id id
*/
private Integer id;
/**
*roleCode 角色编码
*/
private String roleCode;
/**
*roleName角色名称
*/
private String roleName;
/**
*createdBy 创建者
*/
private Integer createdBy;
/**
*creationDate 创建时间
*/
private Date creationDate;
/**
*modifyBy 更新者
*/
private Integer modifyBy;
/**
*modifyDate 更新时间
*/
private Date modifyDate;

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
  • Provider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package cn.xxy.pojo;

import java.util.Date;

/**
* @author xxy
* @date 2021-11-09
* Provider 供应商类
*/
public class Provider {
/**
*id id
*/
private Integer id;
/**
*proCode 供应商编码
*/
private String proCode;
/**
*proName 供应商名称
*/
private String proName;
/**
*proDesc 供应商描述
*/
private String proDesc;
/**
*proContact 供应商联系人
*/
private String proContact;
/**
*proPhone 供应商电话
*/
private String proPhone;
/**
*proAddress 供应商地址
*/
private String proAddress;
/**
*proFax 供应商传真
*/
private String proFax;
/**
*createdBy 创建者
*/
private Integer createdBy;
/**
*creationDate 创建时间
*/
private Date creationDate;
/**
*modifyBy 更新者
*/
private Integer modifyBy;
/**
* modifyDate 更新时间
*/
private Date modifyDate;

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProCode() {
return proCode;
}
public void setProCode(String proCode) {
this.proCode = proCode;
}
public String getProName() {
return proName;
}
public void setProName(String proName) {
this.proName = proName;
}
public String getProDesc() {
return proDesc;
}
public void setProDesc(String proDesc) {
this.proDesc = proDesc;
}
public String getProContact() {
return proContact;
}
public void setProContact(String proContact) {
this.proContact = proContact;
}
public String getProPhone() {
return proPhone;
}
public void setProPhone(String proPhone) {
this.proPhone = proPhone;
}
public String getProAddress() {
return proAddress;
}
public void setProAddress(String proAddress) {
this.proAddress = proAddress;
}
public String getProFax() {
return proFax;
}
public void setProFax(String proFax) {
this.proFax = proFax;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
  • 编写基础公共类

  • BaseDaoUtil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package cn.xxy.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//操作数据库的公共类
public class BaseDaoUtil {
private static String driver;
private static String url;
private static String username;
private static String password;

//静态代码块,类加载的时候就初始化了
static {
Properties properties = new Properties();
//通过类加载器读取对应的资源
InputStream is = BaseDaoUtil.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]);
}

int updateRows = preparedStatement.executeUpdate();
return updateRows;
}


//释放资源
public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
boolean flag = true;

if (resultSet!=null){
try {
resultSet.close();
//GC回收
resultSet = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}

if (preparedStatement!=null){
try {
preparedStatement.close();
//GC回收
preparedStatement = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}

if (connection!=null){
try {
connection.close();
//GC回收
connection = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
return flag;
}
}

  • 编写字符编码过滤器

  • CharacterEncodingFilter.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package cn.xxy.filter;


import javax.servlet.*;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter {

public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
chain.doFilter(request,response);
}
public void destroy() {

}
}


  • 导入静态资源

14.2 编码

  • 一般数据访问层Dao
  • IUserDao
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package cn.xxy.dao.user;

import cn.xxy.pojo.User;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
* 用户接口 smbms_user、smbms_role
*
* @author xxy
* @version XXX.XXX.XX
* @date 2021-12-29
*/
public interface IUserDao {

/**
* 得到要登陆的用户getLoginUser
*
* @param connection 数据库连接
* @param userCode 用户名
* @param userPassword 用户密码
* @return User 该用户
* @throws SQLException
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
User getLoginUser(Connection connection, String userCode, String userPassword) throws SQLException;

/**
* 得到要登陆的用户getLoginUser
*
* @param connection 数据库连接
* @param userCode 用户名
* @return User 该用户
* @throws SQLException
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
User getUserCode(Connection connection, String userCode) throws SQLException;

/**
* 根据条件查询用户数量
*
* @param connection 数据库连接
* @param queryUserName 查询的用户名
* @param queryUserRole 查询的角色
* @return int
* @throws Exception
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
int getUserCount(Connection connection, String queryUserName, int queryUserRole) throws Exception;

/**
* 根据用户Id修改当前密码
*
* @param connection 数据库连接
* @param id Id
* @param userPassword 新密码
* @return int
* @throws SQLException
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
int updatePwd(Connection connection, int id, String userPassword) throws SQLException;

/**
* 通过条件查询列表并分页
*
* @param connection 数据库连接
* @param userName 用户名
* @param userRole 用户角色
* @param currentPageNo 当前页
* @param pageSize 一页的数目
* @return List<User>
* @throws Exception
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception;

/**
* 增加用户信息
*
* @param connection 数据库连接
* @param user 用户信息
* @return int
* @throws Exception
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
int addUser(Connection connection, User user) throws Exception;

/**
* 根据id删除用户
*
* @param connection 数据库连接
* @param id id
* @return int
* @throws Exception
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX *
*/
int deleteUserById(Connection connection, Integer id) throws Exception;

/**
* 修改用户信息
*
* @param connection 数据库连接
* @param user 用户信息
* @return int
* @throws Exception
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX *
*/
int updateUserById(Connection connection, User user) throws Exception;

/**
* 根据id查询当前用户信息
*
* @param connection 数据库连接
* @param id id
* @return User
* @throws Exception
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
User getUserById(Connection connection, String id) throws Exception;

}

  • UserDaoImpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package cn.xxy.dao.user;

import cn.xxy.pojo.User;
import cn.xxy.util.BaseDaoUtil;
import com.mysql.jdbc.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
* 用户接口实现类 smbms_user、smbms_role
*
* @author xxy
* @version XXX.XXX.XX
* @date 2021-12-29
*/
public class UserDaoImpl implements IUserDao {

public User getLoginUser(Connection connection, String userCode, String userPassword) throws SQLException{
PreparedStatement pstm = null;
ResultSet rs = null;
User user = null;
String sql = "select `id`,`userCode`,`userName`,`userPassword`,`gender`,`birthday`,`phone`,`address`,`userRole`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate` from `smbms_user` su where su.userCode = ? and su.userPassword = ? ";
Object[] params = {userCode,userPassword};
try {
if(null != connection) {
rs = BaseDaoUtil.execute(connection, sql, params, rs, pstm);
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"));
}
}

} catch (SQLException e) {
e.printStackTrace();
} finally {
BaseDaoUtil.closeResource(connection,pstm,rs);
}
return user;
}

public User getUserCode(Connection connection, String userCode) throws SQLException {
PreparedStatement pstm = null;
ResultSet rs = null;
User user = null;
String sql = "select `id`,`userCode`,`userName`,`userPassword`,`gender`,`birthday`,`phone`,`address`,`userRole`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate` from `smbms_user` su where su.userCode = ? ";
Object[] params = {userCode};
try {
if(null != connection) {
rs = BaseDaoUtil.execute(connection, sql, params, rs, pstm);
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"));
}
}

} catch (SQLException e) {
e.printStackTrace();
} finally {
BaseDaoUtil.closeResource(connection,pstm,rs);
}
return user;
}

public int getUserCount(Connection connection, String queryUserName, int queryUserRole) throws Exception {
PreparedStatement pstm = null;
ResultSet rs = null;
int count = 0;
if (connection != null) {
StringBuffer sql = new StringBuffer();
sql.append(" select count(*) as count from smbms_user su inner join smbms_role sr on su.userRole = sr.id ");
List<Object> list = new ArrayList<Object>();
if (!StringUtils.isNullOrEmpty(queryUserName)) {
sql.append(" where su.userName like ? ");
list.add("%" + queryUserName + "%");
}
if (queryUserRole > 0) {
sql.append(" and su.userRole = ? ");
list.add(queryUserRole);
}
Object[] params = list.toArray();
System.out.println("sql--->" + sql.toString());
rs = BaseDaoUtil.execute(connection,sql.toString(),params,rs,pstm);
if (rs.next()) {
count = rs.getInt("count");
}
BaseDaoUtil.closeResource(connection,pstm,rs);

}
return count;
}

public int updatePwd(Connection connection, int id, String userPassword) throws SQLException {
System.out.println("UserDaoImpl" + userPassword);
PreparedStatement pstm = null;

int execute = 0;
if (null != connection) {
String sql = " update smbms_user su set su.userPassword = ? where su.id = ? ";
Object params[] = {userPassword,id};
execute = BaseDaoUtil.execute(connection, sql, params, pstm);
BaseDaoUtil.closeResource(null,pstm,null);
}
return execute;
}

public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception {
PreparedStatement pstm = null;
ResultSet rs = null;
List<User> userList = new ArrayList<User>();
if (null != connection) {
StringBuffer sql = new StringBuffer();
sql.append(" select su.*,sr.roleName as userRoleName from smbms_user su inner join smbms_role sr on su.userRole = sr.id ");
List<Object> list = new ArrayList<Object>();
if (!StringUtils.isNullOrEmpty(userName)) {
sql.append(" where su.userName like ? ");
list.add("%" + userName + "%");
}
if (userRole > 0) {
sql.append(" and su.userRole = ? ");
list.add(userRole);
}
//在数据库中分页使用limit
sql.append(" order by su.creationDate desc limit ?,? ");
currentPageNo = (currentPageNo - 1) * pageSize;
list.add(currentPageNo);
list.add(pageSize);
Object[] params = list.toArray();
System.out.println("sql -->" + sql.toString());
rs = BaseDaoUtil.execute(connection,sql.toString(),params,rs,pstm);
while (rs.next()) {
User user1 = new User();
user1.setId(rs.getInt("id"));
user1.setUserCode(rs.getString("userCode"));
user1.setUserName(rs.getString("userName"));
user1.setGender(rs.getInt("gender"));
user1.setBirthday(rs.getDate("birthday"));
user1.setPhone(rs.getString("phone"));
user1.setUserRole(rs.getInt("userRole"));
user1.setUserRoleName(rs.getString("userRoleName"));
userList.add(user1);
}
BaseDaoUtil.closeResource(connection,pstm,rs);
}
return userList;
}

public int addUser(Connection connection, User user) throws Exception {
PreparedStatement pstm = null;
int execute = 0;
if (null != connection) {
String sql = " INSERT INTO `smbms_user`(`userCode`,`userName`,`userPassword`,`gender`,`birthday`,`phone`,`address`,`userRole`,`creationDate`,`createdBy`) VALUES (?,?,?,?,?,?,?,?,?,?) ";
Object[] params = {user.getUserCode(),user.getUserName(),user.getUserPassword(), user.getGender(),user.getBirthday(), user.getPhone(),user.getAddress(),user.getUserRole(),user.getCreationDate(),user.getCreatedBy()};
execute = BaseDaoUtil.execute(connection,sql,params,pstm);
BaseDaoUtil.closeResource(null,pstm,null);
}
return execute;
}

public int deleteUserById(Connection connection, Integer id) throws Exception {
PreparedStatement pstm = null;
int execute = 0;
if (connection != null) {
String sql = " delete su.* from smbms_user su where su.id = ? ";
System.out.println();
Object[] params = {id};
execute = BaseDaoUtil.execute(connection, sql, params, pstm);
BaseDaoUtil.closeResource(null,pstm,null);
}
return execute;
}

public int updateUserById(Connection connection, User user) throws Exception {
PreparedStatement pstm = null;
int execute = 0;
if (null != connection) {
String sql = "update smbms_user set userName=?,"+
"gender=?,birthday=?,phone=?,address=?,userRole=?,modifyBy=?,modifyDate=? where id = ? ";
Object[] params = {user.getUserName(),user.getGender(),user.getBirthday(),
user.getPhone(),user.getAddress(),user.getUserRole(),user.getModifyBy(),
user.getModifyDate(),user.getId()};
execute = BaseDaoUtil.execute(connection, sql, params, pstm);
BaseDaoUtil.closeResource(null,pstm,null);
}
return execute;
}

public User getUserById(Connection connection, String id) throws Exception {
PreparedStatement pstm = null;
ResultSet rs = null;
User user = null;
if (connection != null) {
String sql = "select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.id=? and u.userRole = r.id";
Object[] params = {id};
rs = BaseDaoUtil.execute(connection,sql,params,rs,pstm);
while (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"));
user.setUserRoleName(rs.getString("userRoleName"));
}
BaseDaoUtil.closeResource(connection,pstm,rs);
}
return user;
}
}

  • Service层【业务逻辑层】
  • IUserService
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package cn.xxy.service.user;

import cn.xxy.pojo.User;

import java.sql.SQLException;
import java.util.List;

/**
* 用户业务逻辑层 smbms_user、smbms_role
*
* @author xxy
* @version XXX.XXX.XX
* @date 2021-12-29
*/
public interface IUserService {


/**
* 用户登录
*
* @param userCode 用户名
* @param userPassword 用户密码
* @return User
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
User login(String userCode, String userPassword);

/**
* 根据条件查询用户表记录数
*
* @param queryUserName 查询名字
* @param queryUserRole 查询用户角色
* @return int
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
int getUserCount(String queryUserName, int queryUserRole);

/**
* 根据条件查询用户列表
*
* @param queryUserName 查询名字
* @param queryUserRole 查询用户角色
* @return List<User>
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize);

/**
* 根据id修改密码
*
* @param id id
* @param password 新密码
* @return boolean
* @throws SQLException
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
boolean updatePwd(int id, String password) throws SQLException;

/**
* 增加用户信息
*
* @param user 用户
* @return boolean
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
boolean addUser(User user);

/**
* 根据id删除用户信息
*
* @param id id
* @return boolean
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
boolean deleteUserById(Integer id);

/**
* 修改用户信息
*
* @param user 用户
* @return boolean
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
boolean updateUserById(User user);

/**
* 根据id查找用户信息
*
* @param id id
* @return User
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
User getUserById(String id);

/**
* 根据userCode查询出User
*
* @param userCode 用户code
* @return User
* @author xxy
* @date 2021-12-29
* @version XXX.XXX.XX
*/
User selectUserCodeExist(String userCode);

}

  • UserServiceImpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package cn.xxy.service.user;

import cn.xxy.dao.user.IUserDao;
import cn.xxy.dao.user.UserDaoImpl;
import cn.xxy.pojo.User;
import cn.xxy.util.BaseDaoUtil;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
* 用户业务逻辑实现层 smbms_user、smbms_role
*
* @author xxy
* @version XXX.XXX.XX
* @date 2021-12-29
*/
public class UserServiceImpl implements IUserService {
private IUserDao userDao;

public UserServiceImpl() {
userDao = new UserDaoImpl();
}

public User login(String userCode, String password) {
Connection connection = null;
User user = null;
try {
connection = BaseDaoUtil.getConnection();
user = userDao.getLoginUser(connection,userCode,password);
} catch (SQLException e) {
e.printStackTrace();
} finally {
BaseDaoUtil.closeResource(connection,null,null);
}
return user;
}

public int getUserCount(String queryUserName, int queryUserRole) {
Connection connection = null;
int count = 0;
System.out.println("queryUserName --->" + queryUserName);
System.out.println("queryUserRole---->" + queryUserRole);
try {
connection = BaseDaoUtil.getConnection();
count = userDao.getUserCount(connection, queryUserName, queryUserRole);
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDaoUtil.closeResource(connection,null,null);
}
return count;
}

public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) {
Connection connection = null;
List<User> userList = null;
System.out.println("queryUserName ---- > " + queryUserName);
System.out.println("queryUserRole ---- > " + queryUserRole);
System.out.println("currentPageNo ---- > " + currentPageNo);
System.out.println("pageSize ---- > " + pageSize);
try {
connection = BaseDaoUtil.getConnection();
userList = userDao.getUserList(connection,queryUserName,queryUserRole,currentPageNo,pageSize);
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDaoUtil.closeResource(connection,null,null);
}
return userList;
}

public boolean updatePwd(int id, String password) {
System.out.println("UserDaoImpl" + password);
Connection connection = null;
boolean flag = false;
//修改密码
try {
connection = BaseDaoUtil.getConnection();
if (userDao.updatePwd(connection,id,password) > 0) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
BaseDaoUtil.closeResource(connection,null,null);
}
return flag;
}

public boolean addUser(User user) {
boolean flag = false;
Connection connection = null;
int updateRows = 0;
try {
connection = BaseDaoUtil.getConnection();
connection.setAutoCommit(false);
updateRows = userDao.addUser(connection, user);
connection.commit();
if (updateRows > 0) {
flag = true;
System.out.println("add success");
} else {
System.out.println("add failed");
}
} catch (Exception e) {
e.printStackTrace();
try {
System.out.println("rollback======");
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
} finally {
BaseDaoUtil.closeResource(connection,null,null);
}
return flag;
}

public boolean deleteUserById(Integer id) {
boolean flag = false;
Connection connection = null;
int delRows = 0;
try {
connection = BaseDaoUtil.getConnection();
connection.setAutoCommit(false);
delRows = userDao.deleteUserById(connection,id);
connection.commit();
if (delRows > 0) {
flag = true;
System.out.println("delete success");
} else {
System.out.println("delete failed");
}
} catch (Exception e) {
e.printStackTrace();
try {
System.out.println("rollback==================");
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
} finally {
BaseDaoUtil.closeResource(connection,null,null);
}
return flag;
}

public boolean updateUserById(User user) {
boolean flag = false;
Connection connection = null;
int updateRows = 0;
try {
connection = BaseDaoUtil.getConnection();
connection.setAutoCommit(false);
updateRows = userDao.updateUserById(connection,user);
connection.commit();
if (updateRows > 0) {
flag = true;
System.out.println("update success");
} else {
System.out.println("update failed");
}

} catch (Exception e) {
e.printStackTrace();
try {
System.out.println("rollback=======");
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
} finally {
BaseDaoUtil.closeResource(connection,null,null);
}
return flag;
}

public User getUserById(String id) {
Connection connection = null;
User user = null;
try {
connection = BaseDaoUtil.getConnection();
user = userDao.getUserById(connection,id);
} catch (Exception e) {
e.printStackTrace();
user = null;
} finally {
BaseDaoUtil.closeResource(connection,null,null);
}
return user;
}

public User selectUserCodeExist(String userCode) {
Connection connection = null;
User user = null;
try {
connection = BaseDaoUtil.getConnection();
user = userDao.getUserCode(connection,userCode);
} catch (SQLException e) {
e.printStackTrace();
} finally {
BaseDaoUtil.closeResource(connection,null,null);
}
return user;
}
//
// @Test
// public void test() {
// IUserService userService = new UserServiceImpl();
// User admin = userService.login("admin", "12");
// System.out.println(admin.getUserPassword());
// }
// @Test
// public void testGetUserCount() {
// IUserService userService = new UserServiceImpl();
// int userCount = userService.getUserCount(null, 1);
// System.out.println(userCount);
//
// }
}

  • Servlet层
  • LoginServlet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package cn.xxy.servlet.user;

import cn.xxy.pojo.User;
import cn.xxy.service.user.IUserService;
import cn.xxy.service.user.UserServiceImpl;
import cn.xxy.util.Constants;

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 {
this.doPost(req,resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("login----------------");
String userCode = req.getParameter("userCode");
String userPassword = req.getParameter("userPassword");
IUserService userService = new UserServiceImpl();
User user = userService.login(userCode,userPassword);
if (null != user) {
req.getSession().setAttribute(Constants.USER_SESSION, user);
resp.sendRedirect("/jsp/frame.jsp");
} else {
req.setAttribute("error","用户名和密码不正确,请重新输入");
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
}
}

  • LogoutServlet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package cn.xxy.servlet.user;

import cn.xxy.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* 退出登录,移除session中的用户对象Constants.USER_SESSION,重定向页面
* */
public class LogoutServlet extends HttpServlet {
public LogoutServlet() {
super();
}

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

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().removeAttribute(Constants.USER_SESSION);
resp.sendRedirect(req.getContextPath() + "/login.jsp");
}

@Override
public void destroy() {
super.destroy();
}

@Override
public void init() throws ServletException {

}
}

  • UserServlet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
package cn.xxy.servlet.user;

import cn.xxy.pojo.Role;
import cn.xxy.pojo.User;
import cn.xxy.service.role.IRoleService;
import cn.xxy.service.role.RoleServiceImpl;
import cn.xxy.service.user.IUserService;
import cn.xxy.service.user.UserServiceImpl;
import cn.xxy.util.BaseDaoUtil;
import cn.xxy.util.Constants;
import cn.xxy.util.PageSupport;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

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;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class UserServlet extends HttpServlet {
public UserServlet() {
super();
}

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

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
System.out.println("method--->" + method);
if (null != method && Constants.ADD.equals(method)) {
//增加操作
this.add(req,resp);
} else if (null != method && Constants.DELUSER.equals(method)) {
//删除操作
this.delUser(req,resp);
} else if (null != method && Constants.MODIFY.equals(method)) {
//修改查看操作,查询出信息
this.getUserById(req, resp,"usermodify.jsp");
} else if (null != method && Constants.MODIFYEXE.equals(method)) {
//修改保存操作
this.modifyexe(req,resp);
} else if (null != method && Constants.GETROLELIST.equals(method)) {
//获取用户角色操作
this.getrolelist(req,resp);
} else if (null != method && Constants.QUERY.equals(method)) {
//查询所有列表操作
this.query(req,resp);
} else if (null != method && Constants.VIEW.equals(method)) {
//根据id查询当前用户
this.getUserById(req, resp,"userview.jsp");
} else if (null != method && Constants.SAVEPWD.equals(method)) {
//进行保存密码
try {
this.pwdModify(req, resp);
} catch (SQLException e) {
e.printStackTrace();
}
} else if (null != method && Constants.PWDMODIFY.equals(method)) {
//修改密码异步操作判断旧密码是否相同
this.oldPwdModify(req,resp);
} else if (null != method && Constants.UCEXIST.equals(method)) {
//新增异步操作检查是否存在
this.ucexist(req,resp);
}

}

private void modifyexe(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
System.out.println("modfiyexe----------");
String id = req.getParameter("uid");
String userName = req.getParameter("userName");
String gender = req.getParameter("gender");
String birthday = req.getParameter("birthday");
String phone = req.getParameter("phone");
String address = req.getParameter("address");
String userRole = req.getParameter("userRole");

User user = new User();
user.setId(Integer.valueOf(id));
user.setUserName(userName);
user.setGender(Integer.valueOf(gender));
try {
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
} catch (ParseException e) {
e.printStackTrace();
}
user.setPhone(phone);
user.setAddress(address);
user.setUserRole(Integer.valueOf(userRole));
user.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
user.setModifyDate(new Date());
IUserService userService = new UserServiceImpl();
if (userService.updateUserById(user)) {
resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
} else {
req.getRequestDispatcher("usermodify.jsp").forward(req,resp);
}
}

private void getUserById(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException {
System.out.println("view-------");
String id = req.getParameter("uid");
if (!StringUtils.isNullOrEmpty(id)) {
IUserService userService = new UserServiceImpl();
User user = userService.getUserById(id);
req.setAttribute("user",user);
req.getRequestDispatcher(url).forward(req,resp);
}

}

private void getrolelist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
System.out.println("getrolelist---------------");
List<Role> roleList = null;
IRoleService roleService = new RoleServiceImpl();
roleList = roleService.getRoleList();
if (roleList != null) {
resp.setContentType("application/json");
PrintWriter outPrintWriter = resp.getWriter();
outPrintWriter.write(JSONArray.toJSONString(roleList));
outPrintWriter.flush();
outPrintWriter.close();
}
}

private void delUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
System.out.println("del---------");
String id = req.getParameter("uid");
Integer delId = 0;
try {
delId = Integer.parseInt(id);
} catch (Exception e) {
delId = 0;
}
HashMap<String,String> resultMap = new HashMap<String, String>();
if (delId <= 0) {
resultMap.put("delResult","notexist");
} else {
IUserService userService = new UserServiceImpl();
if (userService.deleteUserById(delId)) {
resultMap.put("delResult", "true");
} else {
resultMap.put("delResult", "false");
}
}
resp.setContentType("pplication/json");
PrintWriter outPrintWriter = resp.getWriter();
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();
outPrintWriter.close();

}

private void ucexist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
System.out.println("ucexist======");
//判断用户账号是否可用
String userCode = req.getParameter("userCode");
HashMap<String, String> resultMap = new HashMap<String, String>();
if (StringUtils.isNullOrEmpty(userCode)) {
resultMap.put("userCode","exist");
} else {
IUserService userService = new UserServiceImpl();
User user = userService.selectUserCodeExist(userCode);
if (null != user) {
resultMap.put("userCode","exist");
} else {
resultMap.put("userCode", "notexist");
}
}
resp.setContentType("application/json");
//从response对象中获取往外输出的writer对象
PrintWriter outPrintWriter = resp.getWriter();
//把resultMap转为json字符串 输出
outPrintWriter.write(JSONArray.toJSONString(resultMap));
outPrintWriter.flush();//刷新
outPrintWriter.close();//关闭流
}

//验证旧密码
private void oldPwdModify(HttpServletRequest req, HttpServletResponse resp) {
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String oldPassword = req.getParameter("oldpassword");
//万能的Map
HashMap<String, String> resultMap = new HashMap<String, String>();
//session失效了
if (o == null) {
resultMap.put("result","sessionerror");
} else if (StringUtils.isNullOrEmpty(oldPassword)) {
resultMap.put("result","error");
} else {
String userPassword = ((User)o).getUserPassword();
if (oldPassword.equals(userPassword)) {
resultMap.put("result","true");
} else {
resultMap.put("result","false");
}

try {
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
/**
* resultMap = {"result","sessionerror"}
* JSON格式 = {key : value}
*/
//阿里巴巴的JSON工具类,转换格式
writer.write(JSONArray.toJSONString(resultMap));
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

private void pwdModify(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException {
boolean falg = false;
//从Session拿ID
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String newPassword = req.getParameter("newpassword");
System.out.println("UserServlet" + newPassword);
if (null != o && !StringUtils.isNullOrEmpty(newPassword)) {
IUserService userService = new UserServiceImpl();
falg = userService.updatePwd(((User) o).getId(), newPassword);
if (falg) {
req.setAttribute(Constants.SYS_MESSAGE,"用户修改成功,请退出,使用新密码登录");
//密码修改成功,移除当前session
req.getSession().removeAttribute(Constants.USER_SESSION);
} else {
req.setAttribute(Constants.SYS_MESSAGE,"密码修改失败");
}
} else {
req.setAttribute(Constants.SYS_MESSAGE,"新密码不合格式,请重新输入");
}
req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
}
private void query(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
//查询用户列表
//从前端获取数据
String queryUserName = req.getParameter("queryname");
String temp = req.getParameter("queryUserRole");
String pageIndex = req.getParameter("pageIndex");
int queryUserRole = 0;
//获取用户列表
IUserService userService = new UserServiceImpl();
//第一次走页面一定是第一页,页面大小是固定的
List<User> userList = null;
//设置页面容量
int pageSize = Constants.pageSize;
//设置当前页码
int currentPageNo = 1;
/**
* http://localhost:8090/SMBMS/userlist.do
* ----queryUserName --NULL
* http://localhost:8090/SMBMS/userlist.do?queryname=
* --queryUserName ---""
*/
System.out.println("queryUserName servlet--------"+queryUserName);
System.out.println("queryUserRole servlet--------"+queryUserRole);
System.out.println("query pageIndex--------- > " + pageIndex);
if (queryUserName == null) {
queryUserName = "";
}
if (temp != null && !"".equals(temp)) {
queryUserRole = Integer.parseInt(temp);
}
if (pageIndex != null) {
try {
currentPageNo = Integer.valueOf(pageIndex);
} catch (NumberFormatException e) {
resp.sendRedirect("error.jsp");
}
}
//总数量(表)
int totalCount = userService.getUserCount(queryUserName,queryUserRole);
//总页数
PageSupport pages = new PageSupport();
pages.setCurrentPageNo(currentPageNo);
pages.setPageSize(pageSize);
pages.setTotalCount(totalCount);
int totalPageCount = pages.getTotalPageCount();
//控制首页和尾页,如果页面小于1了,显示第一页
if (currentPageNo < 1) {
currentPageNo = 1;
} else if (currentPageNo > totalPageCount) { //如果页面大于最后一页,显示最后一页的数据
currentPageNo = totalPageCount;
}

userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo,pageSize);
req.setAttribute("userList",userList);
List<Role> roleList = null;
IRoleService roleService = new RoleServiceImpl();
roleList = roleService.getRoleList();
req.setAttribute("roleList",roleList);
req.setAttribute("queryUserName",queryUserName);
req.setAttribute("queryUserRole",queryUserRole);
req.setAttribute("totalPageCount",totalPageCount);
req.setAttribute("totalCount",totalCount);
req.setAttribute("currentPageNo",currentPageNo);
req.getRequestDispatcher("userlist.jsp").forward(req,resp);



}

private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("add()-------");
boolean flag = false;
User user1 = new User();
String userCode = req.getParameter("userCode");
String userName = req.getParameter("userName");
String userPassword = req.getParameter("userPassword");
String ruserPassword = req.getParameter("ruserPassword");
String gender = req.getParameter("gender");
String birthday = req.getParameter("birthday");
String phone = req.getParameter("phone");
String address = req.getParameter("address");
String userRole = req.getParameter("userRole");
user1.setUserCode(userCode);
user1.setUserName(userName);
user1.setUserPassword(userPassword);
user1.setGender(Integer.valueOf(gender));
try {
user1.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
} catch (ParseException e) {
e.printStackTrace();
}
user1.setPhone(phone);
user1.setAddress(address);
user1.setUserRole(Integer.valueOf(userRole));
user1.setCreationDate(new Date());
user1.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
IUserService userService = new UserServiceImpl();
flag = userService.addUser(user1);
if (flag) {
resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
} else {
req.getRequestDispatcher("useradd.jsp").forward(req,resp);
}

}

@Override
public void destroy() {
super.destroy();
}
}

15. 总结

对于计算机网络和JSP的原理进行了了解