既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新
FileInputStream in = new FileInputStream(realPath);
// 5. 创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
// 6. 获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
// 7. 将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端!
while ((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
##### 6.6.3、验证码功能
验证怎么来的?
* 前端实现
* 后端实现,需要用到Java的图片类,生产一个图片
package com.kuang.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.setColor(Color.white);
g.fillRect(0,0,80,20);
//给图片写数据
g.setColor(Color.BLUE);
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);
}
}
ImageServlet com.kuang.servlet.ImageServlet Imageservlet /img
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200505163538698.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
常见场景:
* 用户登录
void sendRedirect(String var1) throws IOException;
测试:
@override
protected void doGet(HttpservletRequest req, HttpservletResponse resp) throws ServletException, IOException {
resp. sendRedirect("/r/img");//重定向
/\*
resp. setHeader(“Location”,“/r/img”);
resp. setstatus (302);
*
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200505163946136.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200505163953854.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
**index.jsp**
Hel1o World!
<%--这里超交的路径,需要寻找到项目的路径--%>
<%--${pageContext. request, contextPath}代表当前的项目--%>
<form action="${pageContext. request.contextPath}/login" method="get">
用户名: <input type="text" name="username"> <br>
密码: <input type="password" name="password"> <br>
<input type="submit">
</form>
</body>
**RequestTest.java**
public class RequestTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理方求
String username = req.getParameter( s: “username”);
String password rea.getParameter( s: “password”);
System.out.println(username+":"+password);
resp.sendRedirect(s: "/r/success.jsp");
}
**重定向页面success.jsp**
<%@ page contentType=“text/html; charset=UTF-8” language=“java” %>
success
**web.xml配置**
<servlet>
<servlet-name>requset</servlet-name>
<servlet-class>com. kuang. servlet. RequestTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>requset</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
**导入依赖的jar包**
<dependencies>
<!-- https://mvnrepository. com/artifact/javax. servLet/javax. servlet-opi -->
<dependency>
<groupld>javax.servlet</grouptd>
<artifactId>javax. servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax. servLet.jsp/javax. servLet.jsp-opi -->
<dependency>
<groupId>javax.servlet.jsp</groupld>
<artifactId>javax. servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
</dependencies>
</project>
#### 6.7、HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息;
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200505165609562.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200505165618601.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
##### 6.7.1、获取参数,请求转发
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200505165652729.png)
**自己创建类,且需要继承HttpServlet类**
@Override
protected void doGet(HttpservletRequest req. HttpservletResponse resp) throws ServletException, IOException {
req. setcharacterEncoding("utf-8");
resp.setcharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbys = req.getParameterValues("hobbys");
System.out.println("==========");
//后台接收中文乱码问题
System. out.println(username);
System. out.println(password);
System. out.println(Arrays.tostring(hobbys));
System. out.println("============");
system. out.println(req.getContextPath());
//通过请求转发
//这里的/代表当前的web应用
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200505170535748.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
### 7、Cookie、Session
#### 7.1、会话
**会话**:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话;
**有状态会话**:一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过,称之为有状态会话;
**你能怎么证明你是西开的学生?**
你,西开
1. 发票, 西开给你发票
2. 学校登记, 西开标记你来过了
**一个网站,怎么证明你来过?**
客户端, 服务端
1. 服务端给客户端一个 信件,客户端下次访问服务端带上信件就可以了; cookie
2. 服务器登记你来过了,下次你来的时候我来匹配你; seesion
#### 7.2、保存会话的两种技术
**cookie**
* 客户端技术 (响应,请求)
**session**
* 服务器技术,利用这个技术,可以保存用户的会话信息? 我们可以把信息或者数据放在Session中!
常见:网站登录之后,你下次不用再登录了,第二次访问直接就上去了!
#### 7.3、Cookie
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200506182559338.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
1. 从请求中拿到cookie信息
2. 服务器响应给客户端cookie
Cookie[] cookies = req.getCookies(); //获得Cookie
cookie.getName(); //获得cookie中的key
cookie.getValue(); //获得cookie中的vlaue
new Cookie(“lastLoginTime”, System.currentTimeMillis()+“”); //新建一个cookie
cookie.setMaxAge(24*60*60); //设置cookie的有效期
resp.addCookie(cookie); //响应给客户端一个cookie
**cookie:一般会保存在本地的 用户目录下 appdata;**
一个网站cookie是否存在上限!**聊聊细节问题**
* 一个Cookie只能保存一个信息;
* 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie;
* Cookie大小有限制4kb;
* 300个cookie浏览器上限
**删除Cookie;**
* 不设置有效期,关闭浏览器,自动失效;
* 设置有效期时间为 0 ;
**编码解码:**
URLEncoder.encode(“秦疆”,“utf-8”)
URLDecoder.decode(cookie.getValue(),“UTF-8”)
#### 7.4、Session(重点)
![在这里插入图片描述](https://img-blog.csdnimg.cn/2020050618262991.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
什么是Session:
* 服务器会给每一个用户(浏览器)创建一个Seesion对象;
* 一个Seesion独占一个浏览器,只要浏览器没有关闭,这个Session就存在;
* 用户登录之后,整个网站它都可以访问!–> 保存用户的信息;保存购物车的信息……
…
…
…
Session和cookie的区别:
* Cookie是把用户的数据写给用户的浏览器,浏览器保存 (可以保存多个)
* Session把用户的数据写到用户独占Session中,服务器端保存 (保存重要的信息,减少服务器资源的浪费)
* Session对象由服务创建;
使用场景:
* 保存一个登录用户的信息;
* 购物车信息;
* 在整个网站中经常会使用的数据,我们将它保存在Session中;
使用Session:
package com.kuang.servlet;
import com.kuang.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 {
//解决乱码问题
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
//得到Session
HttpSession session = req.getSession();
//给Session中存东西
session.setAttribute("name",new Person("秦疆",1));
//获取Session的ID
String sessionId = session.getId();
//判断Session是不是新创建
if (session.isNew()){
resp.getWriter().write("session创建成功,ID:"+sessionId);
}else {
resp.getWriter().write("session以及在服务器中存在了,ID:"+sessionId);
}
//Session创建的时候做了什么事情;
// Cookie cookie = new Cookie(“JSESSIONID”,sessionId);
// resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
//得到Session
HttpSession session = req.getSession();
Person person = (Person) session.getAttribute(“name”);
System.out.println(person.toString());
HttpSession session = req.getSession();
session.removeAttribute(“name”);
//手动注销Session
session.invalidate();
**会话自动过期:web.xml配置**
15
![在这里插入图片描述](https://img-blog.csdnimg.cn/2020050618301064.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
### 8、JSP
#### 8.1、什么是JSP
Java Server Pages : Java服务器端页面,也和Servlet一样,用于动态Web技术!
最大的特点:
* 写JSP就像在写HTML
* 区别:
+ HTML只给用户提供静态的数据
+ JSP页面中可以嵌入JAVA代码,为用户提供动态数据;
#### 8.2、JSP原理
思路:JSP到底怎么执行的!
* 代码层面没有任何问题
* 服务器内部工作
Tomcat中有一个work目录;
IDEA中使用Tomcat的会在IDEA的Tomcat中生产一个work目录
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200506184154282.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
我电脑的地址:
**C:\Users\Administrator.IntelliJIdea2018.1\system\tomcat\Unnamed\_javaweb-session-cookie\work\Catalina\localhost\ROOT\org\apache\jsp**
发现页面转变成了Java程序!
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200506184204931.png)
**浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet!**
JSP最终也会被转换成为一个Java类!
**JSP 本质上就是一个Servlet**
//初始化
public void _jspInit() {
}
//销毁
public void _jspDestroy() {
}
//JSPService
public void _jspService(.HttpServletRequest request,HttpServletResponse response)
1. 判断请求
2. 内置一些对象
final javax.servlet.jsp.PageContext pageContext; //页面上下文
javax.servlet.http.HttpSession session = null; //session
final javax.servlet.ServletContext application; //applicationContext
final javax.servlet.ServletConfig config; //config
javax.servlet.jsp.JspWriter out = null; //out
final java.lang.Object page = this; //page:当前
HttpServletRequest request //请求
HttpServletResponse response //响应
3. 输出页面前增加的代码
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;
4. 以上的这些个对象我们可以在JSP页面中直接使用!
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200506183804973.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
在JSP页面中;
只要是 JAVA代码就会原封不动的输出;
如果是HTML代码,就会被转换为:
out.write(“\r\n”);
这样的格式,输出到前端!
#### 8.3、JSP基础语法
任何语言都有自己的语法,JAVA中有。 JSP 作为java技术的一种应用,它拥有一些自己扩充的语法(了解,知道即可!),Java所有语法都支持!
##### 8.3.1、JSP表达式
<%–JSP表达式
作用:用来将程序的输出,输出到客户端
<%= 变量或者表达式%>
–%>
<%= new java.util.Date()%>
##### 8.3.2、jsp脚本片段
<%–jsp脚本片段–%>
<%
int sum = 0;
for (int i = 1; i <=100 ; i++) {
sum+=i;
}
out.println(“
Sum=”+sum+“
”);%>
**脚本片段的再实现**
<%
int x = 10;
out.println(x);
%>
这是一个JSP文档
<% int y = 2; out.println(y); %><%–在代码嵌入HTML元素–%>
<%
for (int i = 0; i < 5; i++) {
%>
Hello,World <%=i%>
<%
}
%>
##### 8.3.3、JSP声明
<%!
static {
System.out.println(“Loading Servlet!”);
}
private int globalVar = 0;
public void kuang(){
System.out.println("进入了方法Kuang!");
}
%>
JSP声明:会被编译到JSP生成Java的类中!其他的,就会被生成到\_jspService方法中!
在JSP,嵌入Java代码即可!
<%%>
<%=%>
<%!%>
<%–注释–%>
JSP的注释,不会在客户端显示,HTML就会!
#### 8.4、JSP指令
<%@page args… %>
<%@include file=“”%>
<%–@include会将两个页面合二为一–%>
<%@include file=“common/header.jsp”%>
网页主体
<%@include file=“common/footer.jsp”%>
<%–jSP标签
jsp:include:拼接页面,本质还是三个
–%>
<jsp:include page=“/common/header.jsp”/>
网页主体
#### 8.5、9大内置对象
* PageContext 存东西
* Request 存东西
* Response
* Session 存东西
* Application 【SerlvetContext】 存东西
* config 【SerlvetConfig】
* out
* page ,不用了解
* exception
pageContext.setAttribute(“name1”,“秦疆1号”); //保存的数据只在一个页面中有效
request.setAttribute(“name2”,“秦疆2号”); //保存的数据只在一次请求中有效,请求转发会携带这个数据
session.setAttribute(“name3”,“秦疆3号”); //保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
application.setAttribute(“name4”,“秦疆4号”); //保存的数据只在服务器中有效,从打开服务器到关闭服务器
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200507213158259.png)
request:客户端向服务器发送请求,产生的数据,用户看完就没用了,比如:新闻,用户看完没用的!
session:客户端向服务器发送请求,产生的数据,用户用完一会还有用,比如:购物车;
application:客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可能使用,比如:聊天数据;
#### 8.6、JSP标签、JSTL标签、EL表达式
javax.servlet.jsp.jstl jstl-api 1.2
taglibs standard 1.1.2
EL表达式: ${ }
* **获取数据**
* **执行运算**
* **获取web开发的常用对象**
**JSP标签**
<%–jsp:include–%>
<%–
http://localhost:8080/jsptag.jsp?name=kuangshen&age=12
–%>
<jsp:forward page=“/jsptag2.jsp”>
<jsp:param name=“name” value=“kuangshen”></jsp:param>
<jsp:param name=“age” value=“12”></jsp:param>
</jsp:forward>
**JSTL表达式**
JSTL标签库的使用就是为了弥补HTML标签的不足;它自定义许多标签,可以供我们使用,标签的功能和Java代码一样!
**格式化标签**
**SQL标签**
**XML 标签**
**核心标签** (掌握部分)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200508152235704.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
**JSTL标签库使用步骤**
* 引入对应的 taglib
* 使用其中的方法
* **在Tomcat 也需要引入 jstl 的包,否则会报错:JSTL解析错误**
**c:if**
if测试
<%-- EL表达式获取表单中的数据 ${param.参数名} --%>
<%–判断如果提交的用户名是管理员,则登录成功–%>
<c:if test=“${param.username==‘admin’}” var=“isAdmin”>
<c:out value=“管理员欢迎您!”/>
</c:if>
<%–自闭合标签–%>
<c:out value=“${isAdmin}”/>
**c:choose、c:when**
<%–定义一个变量score,值为85–%>
<c:set var=“score” value=“55”/>
<c:choose>
<c:when test=“
s
c
o
r
e
>
=
90
"
>
你的成绩为优秀
<
/
c
:
w
h
e
n
>
<
c
:
w
h
e
n
t
e
s
t
=
"
{score>=90}"> 你的成绩为优秀 </c:when> <c:when test="
score>=90">你的成绩为优秀</c:when><c:whentest="{score>=80}”>
你的成绩为一般
</c:when>
<c:when test=“
s
c
o
r
e
>
=
70
"
>
你的成绩为良好
<
/
c
:
w
h
e
n
>
<
c
:
w
h
e
n
t
e
s
t
=
"
{score>=70}"> 你的成绩为良好 </c:when> <c:when test="
score>=70">你的成绩为良好</c:when><c:whentest="{score<=60}”>
你的成绩为不及格
</c:when>
</c:choose>
**c:forEach**
<%
ArrayList<String> people = new ArrayList<>();
people.add(0,"张三");
people.add(1,"李四");
people.add(2,"王五");
people.add(3,"赵六");
people.add(4,"田六");
request.setAttribute("list",people);
%>
<%–
var , 每一次遍历出来的变量
items, 要遍历的对象
begin, 哪里开始
end, 到哪里
step, 步长
–%>
<c:forEach var=“people” items=“
l
i
s
t
"
>
<
c
:
o
u
t
v
a
l
u
e
=
"
{list}"> <c:out value="
list"><c:outvalue="{people}”/>
</c:forEach>
<c:forEach var=“people” items=“
l
i
s
t
"
b
e
g
i
n
=
"
1
"
e
n
d
=
"
3
"
s
t
e
p
=
"
1
"
>
<
c
:
o
u
t
v
a
l
u
e
=
"
{list}" begin="1" end="3" step="1" > <c:out value="
list"begin="1"end="3"step="1"><c:outvalue="{people}”/>
</c:forEach>
### 9、JavaBean
实体类
JavaBean有特定的写法:
* 必须要有一个无参构造
* 属性必须私有化
* 必须有对应的Get/Set方法;
一般用来和数据库的字段做映射 ORM;
ORM :对象关系映射
* 表---->类
* 字段---->属性
* 行记录---->对象
**people表**
| id | name | age | address |
| --- | --- | --- | --- |
| 1 | 秦疆1号 | 3 | 西安 |
| 2 | 秦疆2号 | 18 | 西安 |
| 3 | 秦疆3号 | 100 | 西安 |
class People{
private int id;
private String name;
private int id;
private String address;
}
class A{
new People(1,“秦疆1号”,3,“西安”);
new People(2,“秦疆2号”,3,“西安”);
new People(3,“秦疆3号”,3,“西安”);
}
* 过滤器
* 文件上传
* 邮件发送
* JDBC 复习 : 如何使用JDBC , JDBC crud, jdbc 事务
### 10、MVC三层架构
* 什么是MVC: Model、view、Controller(模型、视图、控制器)
#### 10.1、以前的架构
![(img-NGdCSHqw-1588757845418)(JavaWeb.assets/1568423664332.png)](https://img-blog.csdnimg.cn/20200508154442187.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
用户直接访问控制层,控制层就可以直接操作数据库;
servlet–CRUD–>数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求、响应、视图跳转、处理JDBC、处理业务代码、处理逻辑代码
架构:没有什么是加一层解决不了的!
程序员调用
↑
JDBC (实现该接口)
↑
Mysql Oracle SqlServer …(不同厂商)
#### 10.2、MVC三层架构
![[(img-BWDJGUCN-1588757845419)(JavaWeb.assets/1568424227281.png)]](https://img-blog.csdnimg.cn/20200508154512751.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
Model
* 业务处理 :业务逻辑(Service)
* 数据持久层:CRUD (Dao - 数据持久化对象)
View
* 展示数据
* 提供链接发起Servlet请求 (a,form,img…)
Controller (Servlet)
* 接收用户的请求 :(req:请求参数、Session信息….)
* 交给业务层处理对应的代码
* 控制视图的跳转
登录—>接收用户的登录请求—>处理用户的请求(获取用户登录的参数,username,password)---->交给业务层处理登录业务(判断用户名密码是否正确:事务)—>Dao层查询用户名和密码是否正确–>数据库
### 11、Filter (重点)
比如 Shiro安全框架技术就是用Filter来实现的
Filter:过滤器,用来过滤网站的数据;
* 处理中文乱码
* 登录验证….
(比如用来过滤网上骂人的话,我\*\*\*我自己 0-0)
![(img-QEq74VyV-1588757845420)(JavaWeb.assets/1568424858708.png)](https://img-blog.csdnimg.cn/20200508154536177.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
Filter开发步骤:
1. 导包
2. 编写过滤器
1. 导包不要错 **(注意)**
![[(img-HHsC3JBD-1588757845420)(JavaWeb.assets/1568425162525.png)]](https://img-blog.csdnimg.cn/20200508154555952.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
实现Filter接口,重写对应的方法即可
public class CharacterEncodingFilter implements Filter {
//初始化:web服务器启动,就以及初始化了,随时等待过滤对象出现!
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter初始化");
}
//Chain : 链
/\*
-
过滤中的所有代码,在过滤特定请求的时候都会执行
-
必须要让过滤器继续同行
chain.doFilter(request,response);
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(“utf-8”);
response.setCharacterEncoding(“utf-8”);
response.setContentType(“text/html;charset=UTF-8”);System.out.println("CharacterEncodingFilter执行前...."); chain.doFilter(request,response); //让我们的请求继续走,如果不写,程序到这里就被拦截停止! System.out.println("CharacterEncodingFilter执行后...."); } //销毁:web服务器关闭的时候,过滤器会销毁 public void destroy() { System.out.println("CharacterEncodingFilter销毁"); }
}
3. 在web.xml中配置 Filter
CharacterEncodingFilter com.kuang.filter.CharacterEncodingFilter CharacterEncodingFilter
/servlet/*
### 12、监听器
实现一个监听器的接口;(有n种监听器)
1. 编写一个监听器
实现监听器的接口…
依赖的jar包![在这里插入图片描述](https://img-blog.csdnimg.cn/2020050820562995.png)
//统计网站在线人数 : 统计session
public class OnlineCountListener implements HttpSessionListener {
//创建session监听: 看你的一举一动
//一旦创建Session就会触发一次这个事件!
public void sessionCreated(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
System.out.println(se.getSession().getId());
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count+1);
}
ctx.setAttribute("OnlineCount",onlineCount);
}
//销毁session监听
//一旦销毁Session就会触发一次这个事件!
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(0);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count-1);
}
ctx.setAttribute("OnlineCount",onlineCount);
}
/\*
Session销毁:
- 手动销毁 getSession().invalidate();
- 自动销毁
*/
}
2. web.xml中注册监听器
com.kuang.listener.OnlineCountListener
3. 看情况是否使用!
### 13、过滤器、监听器常见应用
**监听器:GUI编程中经常使用;**
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame(“中秋节快乐”); //新建一个窗体
Panel panel = new Panel(null); //面板
frame.setLayout(null); //设置窗体的布局
frame.setBounds(300,300,500,500);
frame.setBackground(new Color(0,0,255)); //设置背景颜色
panel.setBounds(50,50,300,300);
panel.setBackground(new Color(0,255,0)); //设置背景颜色
frame.add(panel);
frame.setVisible(true);
//监听事件,监听关闭事件
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
}
});
}
}
用户登录之后才能进入主页!用户注销后就不能进入主页了!
1. 用户登录之后,向Session中放入用户的数据
2. 进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现!
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
if (request.getSession().getAttribute(Constant.USER_SESSION)==null){
response.sendRedirect(“/error.jsp”);
}
chain.doFilter(request,response);
### 14、JDBC
什么是JDBC : Java连接数据库!
![[(img-rZzTXmtn-1588757845422)(JavaWeb.assets/1568439601825.png)]](https://img-blog.csdnimg.cn/20200508154620734.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
需要jar包的支持:
* java.sql
* javax.sql
* mysql-connector-java… 连接驱动(必须要导入)
**实验环境搭建**
CREATE TABLE users(
id INT PRIMARY KEY,
name
VARCHAR(40),
password
VARCHAR(40),
email VARCHAR(60),
birthday DATE
);
INSERT INTO users(id,name
,password
,email,birthday)
VALUES(1,‘张三’,‘123456’,‘zs@qq.com’,‘2000-01-01’);
INSERT INTO users(id,name
,password
,email,birthday)
VALUES(2,‘李四’,‘123456’,‘ls@qq.com’,‘2000-01-01’);
INSERT INTO users(id,name
,password
,email,birthday)
VALUES(3,‘王五’,‘123456’,‘ww@qq.com’,‘2000-01-01’);
SELECT * FROM users;
导入数据库依赖
mysql mysql-connector-java 5.1.47
IDEA中连接数据库:
![[(img-XErw4ElS-1588757845423)(JavaWeb.assets/1568440926845.png)]](https://img-blog.csdnimg.cn/20200508154638633.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
**JDBC 固定步骤:**
1. 加载驱动
2. 连接数据库,代表数据库
3. 向数据库发送SQL的对象Statement : CRUD
4. 编写SQL (根据业务,不同的SQL)
5. 执行SQL
6. 关闭连接(先开的后关)
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url=“jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8”;
String username = “root”;
String password = “123456”;
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.向数据库发送SQL的对象Statement,PreparedStatement : CRUD
Statement statement = connection.createStatement();
//4.编写SQL
String sql = "select \* from users";
//5.执行查询SQL,返回一个 ResultSet : 结果集
ResultSet rs = statement.executeQuery(sql);
while (rs.next()){
System.out.println("id="+rs.getObject("id"));
System.out.println("name="+rs.getObject("name"));
System.out.println("password="+rs.getObject("password"));
System.out.println("email="+rs.getObject("email"));
System.out.println("birthday="+rs.getObject("birthday"));
}
//6.关闭连接,释放资源(一定要做) 先开后关
rs.close();
statement.close();
connection.close();
}
}
**预编译SQL**
public class TestJDBC2 {
public static void main(String[] args) throws Exception {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url=“jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8”;
String username = “root”;
String password = “123456”;
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.编写SQL
String sql = "insert into users(id, name, password, email, birthday) values (?,?,?,?,?);";
//4.预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,2);//给第一个占位符? 的值赋值为1;
preparedStatement.setString(2,"狂神说Java");//给第二个占位符? 的值赋值为狂神说Java;
preparedStatement.setString(3,"123456");//给第三个占位符? 的值赋值为123456;
preparedStatement.setString(4,"24736743@qq.com");//给第四个占位符? 的值赋值为1;
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));//给第五个占位符? 的值赋值为new Date(new java.util.Date().getTime());
//5.执行SQL
int i = preparedStatement.executeUpdate();
if (i>0){
System.out.println("插入成功@");
}
//6.关闭连接,释放资源(一定要做) 先开后关
preparedStatement.close();
connection.close();
}
}
**事务**
要么都成功,要么都失败!
ACID原则:保证数据的安全。
开启事务
事务提交 commit()
事务回滚 rollback()
关闭事务
转账:
A:1000
B:1000
A(900) --100–> B(1100)
**Junit单元测试**
依赖
junit junit 4.12
简单使用
@Test注解只有在方法上有效,只要加了这个注解的方法,就可以直接运行!
@Test
public void test(){
System.out.println(“Hello”);
}
![[(img-OsUubVNQ-1588757845424)(JavaWeb.assets/1568442261610.png)]](https://img-blog.csdnimg.cn/20200508154657792.png)
失败的时候是红色:
![[(img-qv2oTEGI-1588757845425)(JavaWeb.assets/1568442289597.png)]](https://img-blog.csdnimg.cn/20200508154708211.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JlbGxfbG92ZQ==,size_16,color_FFFFFF,t_70)
**搭建一个环境**
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT,
name
VARCHAR(40),
money FLOAT
);
INSERT INTO account(name
,money) VALUES(‘A’,1000);
INSERT INTO account(name
,money) VALUES(‘B’,1000);
INSERT INTO account(name
,money) VALUES(‘C’,1000);
@Test
public void test() {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
Connection connection = null;
//1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
connection = DriverManager.getConnection(url, username, password);
//3.通知数据库开启事务,false 开启
connection.setAutoCommit(false);
String sql = "update account set money = money-100 where name = 'A'";
connection.prepareStatement(sql).executeUpdate();
//制造错误
//int i = 1/0;
String sql2 = "update account set money = money+100 where name = 'B'";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();//以上两条SQL都执行成功了,就提交事务!
System.out.println("success");
} catch (Exception e) {
try {
//如果出现异常,就通知数据库回滚事务
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
### 15、SMBMS(超市管理项目)
30~37集的SMBMS项目实验
[B站狂神说 - Eclipse - SMBMS项目实验
https://blog.csdn.net/bell\_love/article/details/106157413](https://bbs.csdn.net/topics/618545628)
。。。
![img](https://img-blog.csdnimg.cn/img_convert/3f8a3d07fc7a329458097f8691cad6ae.png)
![img](https://img-blog.csdnimg.cn/img_convert/be9ed656711c96b895fa2b29443b86b1.png)
**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**
**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**
**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
c.Driver");
//2.连接数据库,代表数据库
connection = DriverManager.getConnection(url, username, password);
//3.通知数据库开启事务,false 开启
connection.setAutoCommit(false);
String sql = "update account set money = money-100 where name = 'A'";
connection.prepareStatement(sql).executeUpdate();
//制造错误
//int i = 1/0;
String sql2 = "update account set money = money+100 where name = 'B'";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();//以上两条SQL都执行成功了,就提交事务!
System.out.println("success");
} catch (Exception e) {
try {
//如果出现异常,就通知数据库回滚事务
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
15、SMBMS(超市管理项目)
30~37集的SMBMS项目实验
B站狂神说 - Eclipse - SMBMS项目实验
https://blog.csdn.net/bell_love/article/details/106157413
。。。
[外链图片转存中…(img-ilbUecTV-1715764094690)]
[外链图片转存中…(img-bc936qJG-1715764094690)]
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!