JavaWeb

Tomcat

*web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
          http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
</web-app>

下载Tomcat

http://tomcat.apache.org/

tomcat启动和配置

  • 启动 关闭 tomcat:bin目录下的start up和shut down
  • 访问测试:http://localhost:8080/

配置

在这里插入图片描述
可以配置启动的端口
在这里插入图片描述
可以配置主机域名
在这里插入图片描述

我们是如何访问一个网站的

在这里插入图片描述

配置环境变量(可选)

发布一个web网站

在这里插入图片描述

HTTP

什么是HTTP

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

HTTPS (全称:Hyper Text Transfer Protocol over SecureSocket Layer),是以安全为目标的 HTTP 通道,在HTTP的基础上通过传输加密和身份认证保证了传输过程的安全性。443

两个时代

  • http1.0:客户端可以与web服务器连接后,只能获得一个web资源,断开连接
  • http1.1:客户端可以与web服务器连接后,可以获得多个web资源。

Http请求

  • 客户端向服务器发起请求
  • 百度:
Request URL: https://www.baidu.com/  //请求地址
Request Method: GET   //get方法
Status Code: 200 OK   //状态码200
Remote Address: 39.156.66.14:443
Referrer Policy: unsafe-url
Accept:  text/html,application/xhtml+xml,application/xml;q=0.9,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
  • 请求行
    • 请求方式:Get,Post
      • get:请求能够携带的参数比较小,大小有限制,会在浏览器的url中显示,不安全但高效
      • post:请求能够携带的参数没有限制,大小没有限制,不会在浏览器的url中显示,安全但不高效
  • 消息头
Accept: 告诉浏览器它支持的数据类型
Accept-Encoding: gzip, deflate, br  支持哪种格式编码 GBK UTF-8 ...
Accept-Language: zh-CN,zh;q=0.9     告诉浏览器它的语言环境
Cache-Control: max-age=0            缓存控制
Connection: keep-alive				告诉浏览器请求完成是断开还是连接

Http响应

  • 服务器向客户端回复响应
  • 百度:
Cache-Control: private			//缓存控制
Connection: keep-alive			//连接 保持 http1.1
Content-Encoding: gzip			//编码
Set-Cookie: H_PS_PSSID=30969_1455_31118_21078_30826_30904_30823_31086_22157; path=/; domain=.baidu.com
  • 响应体
Accept: 							告诉浏览器它支持的数据类型
Accept-Encoding: gzip, deflate, br  支持哪种格式编码 GBK UTF-8 ...
Accept-Language: zh-CN,zh;q=0.9     告诉浏览器它的语言环境
Cache-Control: max-age=0            缓存控制
Connection: keep-alive				告诉浏览器请求完成是断开还是连接
refresh:     				    	 告诉客户端多久刷新一次
location:							让网页重新定位
  • 响应状态码
    200:请求响应成功
    3xx:请求重定向(重新到我给你的新位置去)
    4xx:找不到资源
    5xx:服务器代码错误 :502网关错误

Maven

https://editor.csdn.net/md/?articleId=104970644

创建一个Maven项目

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

解决资源导出问题
 <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>

Servlet

什么是Servlet

  • Servlet就是sun公司开发动态web的一门技术
  • sun在这些api中提供一个接口叫做:Servlet
  • 如果你想开发一个Servlet程序只需要两个步骤(把实现了Servlet接口的Java程序叫做Servlet)
    • 编写一个类,实现Servlet接口
    • 把开发好的java类部署到web服务器中

HelloServlet

  • 构建一个普通Maven项目,删掉src目录,以后就可以直接建立子项目
  • 关于Maven父子工程的理解:
  • 父项目中会有:
<modules>
    <module>sevlet-01</module>
</modules>
  • 子项目中会有
<parent>
        <artifactId>JavaWeb-01-maven02</artifactId>
        <groupId>com.lhy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
  • 父项目中的jar包子项目可以直接使用
  • Maven环境优化
    • 修改web.xml为最新的
    • 将maven结构搭建完整
  • 编写一个Servlet
    • 编写一个普通类
    • 实现Servlet接口,这里直接继承HttpServlet
public class HelloServlet extends HttpServlet {
    //由于get和post只是请求实现的不同方式 可以相互调用,业务逻辑都一样
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter writer = resp.getWriter();//响应流
        writer.print("HelloServlet");
    }

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

  • 编写Servlet的映射
    • 为什么需要映射:我们写的是java程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务中注册我们写的servlet,还需要给他一个浏览器访问的路径
<servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.lhy.servlet.HelloServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
  • 配置tomcat
    • 注意配置项目发布的路径就可以了
      *启动测试

Servlet原理

Mapping

一对一

  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

一对多

  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello/*</url-pattern>
  </servlet-mapping>

自定义后缀

  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>*.lhy</url-pattern>
  </servlet-mapping>

优先级问题

指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求

<servlet>
    <servlet-name>error</servlet-name>
    <servlet-class>com.lhy.servlet.ErrorServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>error</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

  

ServletContext

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

共享数据:我在这个Servlet中保存的数据可以在另一个Servlet中使用

设置共享数据变量

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("hello");
        ServletContext context = this.getServletContext();
        String username = "lhy";//数据
        context.setAttribute("username",username); //将一个数据保存到ServletContext中

    }

读取并输出共享数据变量

 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String username =(String) context.getAttribute("username");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("名字"+username);
    }
获取初始化参数

在这里插入图片描述

请求转发
		ServletContext context = this.getServletContext();
        RequestDispatcher requestDispatcher = context.getRequestDispatcher("/hello");//转发到请求路径
        requestDispatcher.forward(req,resp);//调用forward实现请求转发

ps:访问这个页面时会跳转到/hello但是url不会改变(重定向会改变)

获取资源(通过ServletContext获取配置文件)

在这里插入图片描述

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream resourceAsStream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties prop = new Properties();
        prop.load(resourceAsStream);
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        resp.getWriter().print(username+password);
    }

HttpServletResponse

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

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

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

    ServletOutputStream getOutputStream() throws IOException;

    PrintWriter getWriter() throws IOException;

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

    void setCharacterEncoding(String var1);

    void setContentLength(int var1);

    void setContentLengthLong(long var1);

    void setContentType(String var1);
    
    void setDateHeader(String var1, long var2);

    void addDateHeader(String var1, long var2);

    void setHeader(String var1, String var2);

    void addHeader(String var1, String var2);

    void setIntHeader(String var1, int var2);

    void addIntHeader(String var1, int var2);

常见应用

  • 向浏览器输出消息(getWrite。。)
  • 下载文件
    • 要获取下载文件的路径
    • 下载的文件名是什么?
    • 设置想办法让浏览器 能够支持下载我们需要的东西
    • 获取下载文件的输入流
    • 创建缓冲区
    • 获取OutPutStream对象
    • 将FileOutPutStream流写入到buffer缓冲区
    • 使用OutPutStream将缓冲区中的数据输出到客户端
//               * 要获取下载文件的路径
        //String realPath = this.getServletContext().getRealPath("/icon.png");
        String realPath ="E:\\java\\JavaWeb-01-maven02\\response\\target\\classes\\icon.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();


  • 验证码功能
    • 前端实现
    • 后端实现:java图片类,生成一个图片
  //如何让浏览器五秒自动刷新一次;
        resp.setHeader("refresh","3");
        //在内存中创建一个图片
        BufferedImage bufferedImage = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
        //得到图片
        Graphics2D graphics = (Graphics2D)bufferedImage.getGraphics();//笔
        //设置图片背景颜色
        graphics.setColor(Color.white);
        graphics.fillRect(0,0,80,20);
        //给图片写数据
        graphics.setColor(Color.BLUE);
        graphics.setFont(new Font(null,Font.BOLD,20));
        graphics.drawString(makeNum(),0,20);
        //告诉浏览器这个请求用图片的方式打开
        resp.setContentType("image/png");
        //网站存在缓存:不让浏览器缓存
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");

        //把图片写给浏览器
        ImageIO.write(bufferedImage,"png",resp.getOutputStream());

生成7位随机数

  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");
        }
        return sb.toString()+num;
    }
  • 实现重定向
    一个Web资源收到客户端请求后,他会停止客户端去访问另一个web资源,这个过程叫重定向
    常见场景:用户登录
    使用该函数
void sendRedirect(String var1) throws IOException;

案例

/*
resp.setHeader("Location","/s3/image");
resp.setStatus(302);
*/
 resp.sendRedirect("/s3/image");

面试题:说一说重定向和转发的区别
相同点:页面都会转跳
不同点:

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

HttpServletRequest

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

  • 获取前端传递的参数
    • String getParameter(String s)
    • String[] getParameterValues(String s)
  • 请求转发
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        String[] hobbies = req.getParameterValues("hobbies");
            //Dispatcher不需要写/s4 这里的/代表当前的web应用
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }

Cookie和Session

  • 会话
    用户打开一个浏览器,点击了很多超链接,访问了多个web资源,关闭浏览器。这就是一次会话

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

保存会话的两种技术

cookie

  • 客户端技术,(响应,请求)
  • 从请求中拿到cookie信息
  • 服务器响应给客户端
Cookie[] cookies = req.getCookies(); //获得cookie
cookie.getName()  //获得cookie的key
cookie.getValue() //获得cookie的value
Cookie cookie = new Cookie("name","lhy"); //new 一个cookie
cookie.setMaxAge(24*60*60);  //设置cookie有效期 单位秒
 resp.addCookie(cookie);   //相应给客户端一个cookie

cookie一般保存在本地的用户目录下appdata

  • 一个网站cookie是否存在上限?
    一个Cookie只能保存一个信息
    一个web站点可以给浏览器发送多个cookie,上限约为300个
    cookie大小有限制 4kb
  • 删除cookie
    不设置有效期,关闭浏览器自动失效
    设置有效期时间为0
编码与解码

这是最快的解决中文乱码的方法

//编码
URLEncoder.encode("林青霞","utf-8");
//解码
URLEncoder.decode(cookie.getValue(),"utf-8"));

session(重点)

  • 服务器技术,利用这个技术可以保存用户的会话信息,我们可以把信息或者数据放在Session中
  • 服务器会给每一个用户(浏览器)创建一个Seesion对象
  • 一个Session独占一个浏览器,只要浏览器没关,这个Session就存在
  • 用户登陆之后,整个网站都可以访问

Session和Cookie的区别

  • Cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个)
  • Session是把用户的数据写道独占Session中,服务器端保存(保存重要的信息,减少服务器资源浪费)
  • Session对象由服务器端创建;
    使用场景:
  • 保存一个登录用户的信息
  • 购物车信息
  • 经常在整个网站中使用的数据,我们将它保存在session中
  • 使用Session:
//得到Session
HttpSession session = req.getSession();
//手动注销session
session.invalidate();
//向session存东西
session.setAttribute("name","林青霞");
//从seession中取东西
session.getAttribute("name");
//获取SessioonId
String sessionId = session.getId();
//判断session是不是新建
session.isNew();

会话自动关闭

<!--Session配置-->
    <session-config>
        <session-timeout>1</session-timeout><!--//1分钟后失效-->
    </session-config>

JSP

什么是JSP

Java Server Pages : java服务器端页面,也和servlet一样,用来开发动态页面
最大的特点:

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

JSP原理

思路:jsp是怎么执行的

  • 代码层面没有任何问题
  • 服务器内部工作
    tomcat中有一个work目录:
    IDEA中使用tomcat会在IDEA的tomcat中产生一个work目录
    在这里插入图片描述
    浏览器向服务器发送请求,不管访问什么资源,都是在访问servlet
    JSP最终也会被转化为一个JAVA类
    JSP本质上就是一个servlet
//初始化
public void _jspInit(){

}
//销毁
public void _jspDestroy(){}
//JSPService
public void _jspService(HttpServletRequest request.HttpServletResponse response)

1.判断请求
2.内置对象
在这里插入图片描述
在这里插入图片描述

JSP基础语法

任何语言都有自己的语法,java有,jsp作为java技术的一种应用,它拥有一些自己扩充的语法(了解即可)Java所有语法都支持

JSP表达式:

<%--  JSP表达式
      作用:用来将程序输出到客户端
      <%= 变量或表达式 %>
--%>

JSP脚本片段:

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

脚本片段的再实现

<%--在java代码中嵌入HTML元素--%>
<%
  for (int i = 0; i <5 ; i++) {


%>
<h1>helloWorld  <%=i%></h1>
<%
  }
%>

JSP声明:会被编译到JSP生成的java类中! 其他的会被生成到_jspService方法中!

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

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

JSP指令

可以定制错误页面

<%--定制错误页面--%>
<%@page errorPage="error/500.jsp" %>

web.xml中也可以配置错误页面

 <error-page>
        <error-code>404</error-code>
        <location>/error/404.jsp</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/error/500.jsp</location>
    </error-page>

引用公共页面(将两个页面合而为一 变为一个)

<%@ include file="common/header.jsp"%>
<h1>我是网页主体</h1>
<%@ include file="common/footer.jsp"%>

JSP标签(调用函数拼接页面 本质还是三个)

<jsp:include page="/common/header.jsp"/>
<h1>我是网页主体</h1>
<jsp:include page="/common/footer.jsp"/>

九大内置对象

  • PageContext //存东西 几乎不用
  • Request //存东西 客户端向服务器发送请求,产生的数据,用户看完就没用了 比如:新闻
  • Response
  • Session //存东西 客户端向服务器发送请求,产生的数据,用户用完一会儿还有用 比如:购物车
  • Application [ServletContext] //存东西 客户端向服务器发送请求,产生的数据,一个用户用完了其他用户还有用 比如:统计用户人数
  • config [ServletConfig]
  • out
  • page
  • exception
 	pageContext.setAttribute("name1","001");//保存的数据在一个页面中有效
    request.setAttribute("name2","002");//在一次请求中有效,请求转发会携带这个数据
    session.setAttribute("name3","003");//在一个会话中有效,从打开浏览器到关闭浏览器
    application.setAttribute("name4","004");//在服务器中有效,从打开服务器到关闭服务器

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

el表达式:${}

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

JSP标签

<%--<jsp:include page=""></jsp:include>--%>
<jsp:forward page="/jspTag02.jsp">
    <jsp:param name="name1" value="001"/>
    <jsp:param name="age" value="2"/>
</jsp:forward>

JSTL表达式

  • JSTL标签库的使用就是为了弥补HTML标签的不足:它自定义许多标签可以供我们使用,标签的功能和java代码一样!
  • 格式化标签
  • sql标签
  • xml标签
  • 核心标签(掌握部分)<%@ taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>
    在这里插入图片描述
    JSTL标签库使用步骤
  • 引入对应的taglib
  • 使用其中的方法
  • 在Tomcat中也需要引入jstl和standar的包否则会报错
    JSTL的一些实用
    c:if
<%--引入jstl核心标签库--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
 <h1>if测试</h1>
<form action="coreif.jsp" method="get">
<%--    EL表达式获取表单中的数据${param.参数名}--%>
    <input type="text" name="username" value="${param.username}">
    <input type="submit" value="登录">
</form>

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

c:choose c:when

<%--定义一个变量score 值为85--%>
<c:set var="score" value="85"/>

<c:choose>
    <c:when test="${score>=90}">
        <c:out value="你的成绩为优"></c:out>
    </c:when>
    <c:when test="${score>=80}">
        <c:out value="你的成绩为良"></c:out>
    </c:when>
    <c:when test="${score>=70}">
        <c:out value="你的成绩为一般"></c:out>
    </c:when>
    <c:when test="${score<=60}">
        <c:out value="你的成绩为不及格"></c:out>
    </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:每一次遍历出来的变量
 itmes,要遍历的对象
--%>
<c:forEach var="people" items="${list}">
    <c:out value="${people}"/><br>
</c:forEach>
<%--类似于JAVA的fori 后三个参数默认0,last,1--%>
<c:forEach var="people" items="${list}" begin="1" end="3" step="2">
    <c:out value="${people}"/><br>
</c:forEach>

JAVABean

实体类
JAVABean有特定的写法:

  • 必须有无参构造
  • 属性必须私有化
  • 必须有对应的get/set方法
    一般用来和数据库字段做映射
    ORM:对象关系映射
  • 表--------->类
  • 字段--------->属性
  • 行记录--------->对象
    在这里插入图片描述
    应用
<%
//    People people = new People();
    people.setAddress("东北");
    people.setAge(22);
    people.setId(1);
    people.setName("lhy");
//    people.getAddress();
//    people.getAge();
//    people.getId();
//    people.getName();
%>
这两段代码作用相同 一个用jsp标签一个用java代码
<jsp:useBean id="people" class="com.lhy.pojo.People"/>

<jsp:setProperty name="people" property="address" value="东北"/>
<jsp:setProperty name="people" property="id" value="1"/>
<jsp:setProperty name="people" property="name" value="lhy"/>
<jsp:setProperty name="people" property="age" value="22"/>

姓名:<jsp:getProperty name="people" property="name"/>
id:<jsp:getProperty name="people" property="id"/>
年龄:<jsp:getProperty name="people" property="age"/>
地址:<jsp:getProperty name="people" property="address"/>

MVC三层架构

什么是MVC

Model View Controller 模型视图控制器

早期架构

在这里插入图片描述
用户直接访问控制层,控制层可以直接操作数据库;
servlet—》CRUD—》数据库
弊端:程序十分臃肿,不利于维护 servlet代码:处理请求,响应,视图转跳,处理JDBC,处理业务代码,处理逻辑代码
架构:没有什么是加一层解决不了的!!!

三层架构MVC

在这里插入图片描述

Model

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

View

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

Controller(Servlet)

  • 接收用户的请求:(req:请求参数,session信息)
  • 交给业务层处理相应的代码
  • 控制视图的跳转

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

过滤器Filter(重点)

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

  • 处理中文乱码
  • 登陆验证…
    在这里插入图片描述

Filter开发步骤

1.导包
2.编写过滤器

  • 导javax.servlet的包 不要搞错
  • 在这里插入图片描述
  • 实现Filter接口实现方法
public class CharacterEncodingFilter implements Filter {
    //web服务器启动就已经初始化了,随时等待过滤请求
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");
    }
//filterChain链
    /*
    * 过滤器中的所有代码,在过滤特定请求的时候都会执行
    * 必须要让过滤器继续执行
    * */

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=UTF-8");
        System.out.println("过滤器执行前");
        filterChain.doFilter(servletRequest,servletResponse);//让请求继续走,如果不写程序到这里就被拦截停止
        System.out.println("过滤器执行后");
    }
   //web服务器关闭的时候过滤器销毁
    public void destroy() {
        System.out.println("销毁");
    }
}
  • 配置web.xml
   <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>com.lhy.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
<!--        只要是/servlet下的任何请求都会经过这个过滤器-->
        <url-pattern>/servlet/*</url-pattern>
    </filter-mapping>

监听器

实现监听器接口(有很多种)
编写一个监听器:
1.实现一个监听器的接口
2.重写方法

//统计网站在线人数:统计session
public class OnlineCountListener implements HttpSessionListener {
    //session创建监听
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        Integer onlineCount =(Integer) ctx.getAttribute("OnlineCount");
        if(onlineCount==null){
            onlineCount = 1;
        }else{
            ;
            onlineCount +=1;
        }
        ctx.setAttribute("OnlineCount",onlineCount);
    }
    //session销毁监听
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        Integer onlineCount =(Integer) ctx.getAttribute("OnlineCount");
        if(onlineCount==null){
            onlineCount = 0;
        }else{

            onlineCount-=1;
        }
        ctx.setAttribute("OnlineCount",onlineCount);
    }
}
/*
* session销毁:
* 1手动销毁 se.getSession().invalidate();
* 2在web.xml中配置过期时间
* */

3.到web.xml中配置监听器

<!--    注册监听器-->
    <listener>
        <listener-class>com.lhy.listener.OnlineCountListener</listener-class>
    </listener>

4.看情况是否使用

JDBC

什么是JDBC

java database connect
JAVA连接数据库
需要jar包支持:

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

实验环境搭建

public class testjdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //解决中文乱码useUnicode=true&characterEncoding=gbk
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username="root";
        String password= "289989142";
        //1.加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.连接数据  connection代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        //3.向数据库发送sql的对象statement crud
        Statement statement = connection.createStatement();
        //4.编写sql
        String sql = "select * from users";
        //5.执行查询sql,返回一个结果集
        ResultSet resultSet = statement.executeQuery(sql);

        while(resultSet.next()){
            System.out.println("id="+resultSet.getObject("id"));
            System.out.println("name="+resultSet.getObject("name"));
            System.out.println("password="+resultSet.getObject("password"));
            System.out.println("email="+resultSet.getObject("email"));
            System.out.println("birthday="+resultSet.getObject("birthday"));
        }
        //6.关闭连接释放资源 (先开得后关)
        resultSet.close();
        statement.close();
        connection.close();
    }
}

导入数据库依赖

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

JDBC固定步骤

  • 加载驱动
  • 连接数据 connection代表数据库
  • 向数据库发送sql的对象statement crud
  • 编写sql
  • 执行sql,返回一个结果集
  • 关闭连接释放资源 (先开得后关)
    预编译sql
public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //解决中文乱码useUnicode=true&characterEncoding=gbk
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username="root";
        String password= "289989142";
        //1.加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.连接数据  connection代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        //3.编写sql
        String sql = "insert into users(name,password) values (?,?);";
        //4.预编译
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setString(1,"lhy");//给第一个问号的地方赋值为1
        preparedStatement.setString(2,"123456");//给第一个问号的地方赋值为1


        //5.执行查询sql,返回一个结果集
        int i = preparedStatement.executeUpdate(sql);

        if(i>0){
            System.out.println("success");
        }
        //6.关闭连接释放资源 (先开得后关)
        preparedStatement.close();
        connection.close();
    }

事务

要么都成功,要么都失败!
acid原则:保证数据的安全

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

单元测试JUNIT

依赖

<dependency>
 <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

简单实用 @Test注解只有在方法上有效 只要加了这个注解就可以运行

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值