狂神。JavaWeb学习(2)

7、Cookie、Session

7.1、会话

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

**有状态会话:**一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过,称之为有状态会话。

你能怎么证明你是西开的学生?

你——西开

  1. 发票 西开给你发票。
  2. 学校登记 西开标记你来过了。

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

客户端——服务端

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

7.2、保存会话的两种技术

cookie

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

session

  • 服务器技术,利用这个技术,可以保存用户的会话信息? 我们可以把信息或者数据放在Session中!

常见常见:网站登录之后,你下次不用再登录了,第二次访问直接就上去了!

7.3、Cookie

在这里插入图片描述

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

package kuang;

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.util.Date;

//保存用户上一次访问的时间。
public class CookieDemo01 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");

        PrintWriter out = resp.getWriter();

        //Cookie,服务器端从客户端获取。
        Cookie[] cookies = req.getCookies();//这里返回值,说明Cookie可能存在多个。

        //判断Cookie是否存在。
        if (cookies!=null){
            //如果存在怎么办。
            out.write("你上一次访问的时间是:");

            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                //获取Cookie的名字。
                if (cookie.getName().equals("lastLoginTime")){
                    //获取Cookie中的值。
                    long lastLoginTime = Long.parseLong(cookie.getValue());
                    Date date = new Date(lastLoginTime);
                    out.write(date.toLocaleString());
                }
            }

        }else {
            out.write("这是您第一次访问本站!");
        }

        //服务器给客户端响应一个Cookie。
        Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");

        //cookie有效期为1天。
        cookie.setMaxAge(24*60*60);

        resp.addCookie(cookie);
    }

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

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;

public class CookieDemo02 extends HttpServlet {

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

        //创建一个cookie,名字必须要和要删除的名字一致。
        Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");

        //将Cookie有效期设置为0,立马过期。
        cookie.setMaxAge(0);

        resp.addCookie(cookie);
    }

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

package kuang;

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;

//中文数据传递。
public class CookieDemo03 extends HttpServlet {

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

        //解决中文乱码问题。
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        //Cookie,服务器端从客户端获取。
        Cookie[] cookies = req.getCookies();//这里返回值,说明Cookie可能存在多个。
        PrintWriter out = resp.getWriter();

        //判断Cookie是否存在。
        if (cookies!=null){
            //如果存在怎么办。
            out.write("你上一次访问的时间是:");

            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                //获取Cookie的名字。
                if (cookie.getName().equals("name")){
                    //System.out.println(cookie.getValue());
                    //解码
                    out.write(URLDecoder.decode(cookie.getValue(),"UTF-8"));
                }
            }

        }else {
            out.write("这是您第一次访问本站!");
        }

        //编码
        Cookie cookie = new Cookie("name", URLEncoder.encode("德玛西亚","utf-8"));
        resp.addCookie(cookie);
    }

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

}

7.4、Session(重点)

在这里插入图片描述

什么是Session:

  • 服务器会给每一个用户(浏览器)创建一个Seesion对象;
  • 一个Seesion独占一个浏览器,只要浏览器没有关闭,这个Session就存在;
  • 用户登录之后,整个网站它都可以访问!–> 保存用户的信息;保存购物车的信息……

Session和cookie的区别:

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

使用场景:

  • 保存一个登录用户的信息;
  • 购物车信息;
  • 在整个网站中经常会使用的数据,我们将它保存在Session中;

使用Session:

package kuang;

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

package kuang;

import pojo.Person;

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

        Person person = (Person)session.getAttribute("name");
        System.out.println(person.toString());
    }

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

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("name");
        //手动注销。
        session.invalidate();
    }

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

//新建一个person实体类。
public class Person {

    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

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

<!-- 设置Session默认的失效时间. -->
<session-config>
		<!-- xxx分钟够session自动失效,以分钟为单位。-->
    <session-timeout>1440</session-timeout>
</session-config>

在这里插入图片描述

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目录。(mac表示还有没找到!)

在这里插入图片描述

我的电脑地址:

/Users/wangcheng/apachetomcat9.0.60/work/Catalina/localhost/ROOT/org/apache/jsp
/index_jsp.java 

发现页面转变成了java程序!

在这里插入图片描述

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

JSP最终也会被转换成为一个Java类!

JSP 本质上就是一个Servlet.

//初始化
public void _jspInit() {}
//销毁
public void _jspDestroy() {}
//JSPService
public void _jspService(HttpServletRequest request,HttpServletResponse response){}
  1. 判断请求
  2. 内置一些对象
final javax.servlet.jsp.PageContext pageContext;  //页面上下文
javax.servlet.http.HttpSession session = null;    //session
final javax.servlet.ServletContext application;   //applicationContext
final javax.servlet.ServletConfig config;         //config
javax.servlet.jsp.JspWriter out = null;           //out
final java.lang.Object page = this;               //page:当前
HttpServletRequest request                        //请求
HttpServletResponse response                      //响应
  1. 输出页面前增加的代码
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;
  1. 以上的这些个对象我们可以在JSP页面中直接使用!

在这里插入图片描述

在JSP页面中;

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

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

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

这样的格式,输出到前端!

8.3、JSP基础语法

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

  • JSP表达式
<%-- JSP表达式
 作用:用来将程序的输出,输出到客户端。
 <%= 变量或者表达式 %>
--%>
<%= new java.util.Date() %>
  • jsp脚本片段
<%--JSP脚本片段--%>
<%
  int sum = 0;
  for (int i = 0; i < 100; i++) {
    sum += i;
  }
  out.println("<h1>Sum="+sum+"</h1>");
%>
  • 脚本片段的再实现
<%
  int x = 10;
  out.println(x);
%>
<p>这是一个JSP文档</p>
<%
  int y = 10;
  out.println(y);
%>

<hr>

<%--在代码嵌入HTML元素--%>
<%--EL表达式(${i}显示不出来,不知道为啥。)--%>
<% for (int i = 0; i < 5; i++) { %>
<h1>Hello,World! <%=i%> </h1>
<% } %>
  • 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指令

定制错误页面:

  • 404.jsp页面:
<body>
<img src="${pageContext.request.contextPath}/img/404.jpg" alt="404">
</body>
  • 500.jsp页面:
<body>
<%--../img/500.jpg 找不到图片,可能配置tomcat的时候路径加了/javaweb_jsp_war_exploded。--%>
<img src="${pageContext.request.contextPath}/img/500.jpg" alt="500">
<%--<img src="../img/500.jpg" alt="500">--%>
</body>
  • 让他为一个错误页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%--定制错误页面(也可以在xml文件中配置)--%>
<%--<%@ page errorPage="error/500.jsp" %>--%>

<%--显示的声明这是一个错误页面--%>
<%--<%@ page isErrorPage="true" %>
<%@ page pageEncoding="UTF-8" %>--%>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <%
        int x = 1/0;
    %>

</body>
</html>
  • 也可以在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>

将两个页面合二为一。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>Title</title>
</head>
<body>

    <%--@ include会将两个页面合二为一。--%>
    <%@ include file="common/header.jsp"%>
    <h1>网页主体</h1>
    <%@ include file="common/footer.jsp"%>

    <hr>

    <%--jsp标签
    jsp:include:拼接页面,本质还是三个。
    --%>
    <%--jsp标签--%>
    <jsp:include page="common/header.jsp"/>
    <h1>网页主体</h1>
    <jsp:include page="common/footer.jsp"/>

</body>
</html>
  • header.jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<h1>我是头部</h1>
  • footer.jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<h1>我是脚部</h1>

8.5、9大内置对象

  • PageContext 存东西
  • Request 存东西
  • Response
  • Session 存东西
  • Application 【SerlvetContext】 存东西
  • config 【SerlvetConfig】
  • out
  • page ,不用了解
  • exception

request:客户端向服务器发送请求,产生的数据,用户看完就没用了。比如:新闻,用户看完没用的!

session:客户端向服务器发送请求,产生的数据,用户用完一会还有用,比如:购物车;

application:客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可能使用,比如:聊天数据;

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%--内置对象--%>
<%
    pageContext.setAttribute("name1","德玛西亚");//保存的数据只在一个网页中有效。
    request.setAttribute("name2","艾欧尼亚");//保存的数据只在一个请求中有效,请求转发会携带这个数据。
    session.setAttribute("name3","诺克萨斯");//保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器。
    application.setAttribute("name4","班德尔城");//保存的数据只在服务器中有效,从打开服务器到关闭服务器。
%>

<%-- 脚本片段中的代码,会被原封不动生成到.JSP.java中,
要求:这里面的代码,必须保证Java语法的正确性。--%>
<%
    //从pageContext取出,我们通过寻找的方式来。
    //从底层到高层(作用域):page-->request-->session-->application
    //双亲委派机制。
    String name1 = (String) pageContext.findAttribute("name1");
    String name2 = (String) pageContext.findAttribute("name2");
    String name3 = (String) pageContext.findAttribute("name3");
    String name4 = (String) pageContext.findAttribute("name4");
    String name5 = (String) pageContext.findAttribute("name5");//不存在
%>

<%--使用EL表达式输出 ${} --%>
<h1>取出的值为:</h1>
<h3>${name1}</h3>
<h3>${name2}</h3>
<h3>${name3}</h3>
<h3>${name4}</h3>
<%--显示null ,用El表达式写会不显示--%>
<h3><%=name5%></h3>

<%
    //转发到pageDemo02后会显示name2、3、4的值。
    pageContext.forward("/pageDemo02.jsp");
%>

</body>
</html>

这样写只会显示name3、4的值。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%
    //从pageContext取出,我们通过寻找的方式来。
    //从底层到高层(作用域):
    String name1 = (String) pageContext.findAttribute("name1");
    String name2 = (String) pageContext.findAttribute("name2");
    String name3 = (String) pageContext.findAttribute("name3");
    String name4 = (String) pageContext.findAttribute("name4");
    String name5 = (String) pageContext.findAttribute("name5");//不存在
%>

<%--使用EL表达式输出 ${} --%>
<h1>取出的值为:</h1>
<h3>${name1}</h3>
<h3>${name2}</h3>
<h3>${name3}</h3>
<h3>${name4}</h3>
<%--显示null ,用El表达式写会不显示--%>
<h3><%=name5%></h3>

</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  
<%
    pageContext.forward("/index.jsp");
    //相当于 request.getRequestDispatcher("/index.jsp").forward(request,response);
    //这里这样写就行。
%>

<%
  pageContext.setAttribute("hello1","hello",PageContext.SESSION_SCOPE);
  //相当于session.setAttribute("hello1","hello");
%>
  
</body>
</html>

8.6、JSP标签、JSTL标签、EL表达式

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

EL表达式: ${ }

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

JSP标签

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%--jsp:include--%>
<%--
http://localhost:8080/javaweb_jsp_war_exploded/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>

</body>
</html>

取出参数:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%--取出参数--%>
名字:<%= request.getParameter("name") %>
年龄:<%= request.getParameter("age") %>
  
</body>
</html>

JSTL表达式

JSTL标签库的使用就是为了弥补HTML标签的不足;

它自定义许多标签,可以供我们使用,标签的功能和Java代码一样!

格式化标签

SQL标签

XML 标签

核心标签: (掌握部分)

在这里插入图片描述

JSTL标签库使用步骤:

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

c:if

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%--引入JSTL核心标签库,我们才能使用JSTL标签 core(网上搜)(找到包的位置拷贝到tomcat的lib目录下才能用)--%>
<%@ taglib prefix ="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>if测试</title>
</head>
<body>

<form action="coreif.jsp" method="get">
    <%--
    EL表达式获取表单中的数据。
    ${param.参数名}
    --%>
    <input type="text" name="username" value="${param.username}">
    <input type="submit" value="登陆">
</form>

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

<%--自闭和标签,这里返回布尔值。--%>
<c:out value="${isAdmin}"/>

</body>
</html>

c:choose c:when

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

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

<c:choose>
    <c:when test="${score>=90}">
        你的成绩很优秀!
    </c:when>
    <c:when test="${score>=80}">
        你的成绩为一般!
    </c:when>
    <c:when test="${score>=70}">
        你的成绩有点差!
    </c:when>
    <c:when test="${score<=60}">
        你的成绩很不及格!
    </c:when>
</c:choose>

</body>
</html>

c:forEach

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%
    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="${list}">
    <c:out value="${people}"/> <br>
</c:forEach>

<hr>

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

</body>
</html>

9、JavaBean

实体类

JavaBean有特定的写法:

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

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

ORM :对象关系映射.

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

people表:

idnameageaddress
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"西安");
}


  • 一个people实体类:
package kuang.pojo;

//实体类,我们一般都是和数据库中的表结构一一对应!
public class People {

    private int id;
    private String name;
    private int age;
    private String address;

    public People() {
    }

    public People(int id, String name, int age, String address) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

}

  • jsp标签实现:
<%@ page import="kuang.pojo.People" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%
    //相当于
    /*People people = new People();
    people.setAddress();
    people.setAge();
    people.setId();
    people.setName();
    people.getAddress();
    ......*/
%>

<jsp:useBean id="people" class="kuang.pojo.People" scope="page"/>

<jsp:setProperty name="people" property="address" value="西安"/>
<jsp:setProperty name="people" property="id" value="1"/>
<jsp:setProperty name="people" property="age" value="3"/>
<jsp:setProperty name="people" property="name" value="狂神"/>

姓名:<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"/>

</body>
</html>

10、MVC三层架构

  • 什么是MVC: Model view Controller 模型、视图、控制器。

10.1、早些年

在这里插入图片描述

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

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

架构:没有什么是加一层解决不了的!
程序猿调用
|
JDBC (实现该接口)
|
Mysql Oracle SqlServer ....(不同厂商)

10.2、MVC三层架构

在这里插入图片描述

Model:

  • 业务处理 :业务逻辑(Service)
  • 数据持久层:CRUD (Dao - 数据持久化对象)

View:

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

Controller (Servlet):

  • 接收用户的请求 :(req:请求参数、Session信息….)

  • 交给业务层处理对应的代码

  • 控制视图的跳转

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

11、Filter (重点)

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

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

在这里插入图片描述

Filter开发步骤:

  1. 导包
  2. 编写过滤器
    • 导包不要错 (注意是servlet下的包)

在这里插入图片描述

实现Filter接口,重写对应的方法即可。

package kuang.filter;

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

public class CharacterEncodingFilter implements Filter {   //一定到导入javax.servlet.*下的包。

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

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

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

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

12、监听器

实现一个监听器的接口。(有N种监听器)

  1. 编写一个监听器。

    实现监听器的接口。

package kuang.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

//统计网站在线人数:统计session。
public class OnlineCountListener implements HttpSessionListener {

    //创建session监听:看你的一举一动。
    //一旦创建Session就会触发一次这个事件!
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("创建了!");
        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销毁:
    1。手动销毁。se.getSession().invalidate();
    2。自动销毁。xml中配置有效期。
     */
    //销毁session监听。
    //一旦销毁Session就会触发一次这个事件!
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("销毁了!");
        ServletContext ctx = se.getSession().getServletContext();
        //se.getSession().invalidate();//手动销毁
        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);
    }
}

jsp页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>$Title$</title>
</head>
<body>

<h1>当前有<span style="color: blue"><%= this.getServletConfig().getServletContext().getAttribute("OnlineCount") %></span>人在线</h1>

</body>
</html>
  1. web.xml中注册监听器
<!--注册监听器-->
<listener>
    <listener-class>kuang.listener.OnlineCountListener</listener-class>
</listener>
<!--1分钟后销毁-->
<session-config>
    <session-timeout>1</session-timeout>
</session-config>
  1. 看情况是否使用!

13、过滤器、监听器常见应用

  • 监听器:GUI编程中经常使用:
package kuang.listener;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame("节日快乐!");//新建一个窗体。
        Panel panel = new Panel();//面板
        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) {
                System.out.println("关闭!");
                System.exit(0);
            }
        });
    }
}

  • 过滤器:用户登录使用:

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

  1. 用户登录之后,向Sesison中放入用户的数据.
  2. 进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现!
  • 判断用户名是否正确:
package kuang.servlet;

import kuang.utli.Constant;

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 {
        //获取前端请求的参数。
        String username = req.getParameter("username");

        if (username.equals("admin")){//登陆成功。
            req.getSession().setAttribute(Constant.USER_SESSION,req.getSession().getId());
            resp.sendRedirect("/javaweb_filter_war_exploded/sys/success.jsp");
        }else {//登陆失败。
            resp.sendRedirect("/javaweb_filter_war_exploded/error.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  • 注销删除用户的id:
package kuang.servlet;

import kuang.utli.Constant;

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 logoutServlet extends HttpServlet {

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

        Object userSession = req.getSession().getAttribute(Constant.USER_SESSION);
        if (userSession!=null){
            req.getSession().removeAttribute(Constant.USER_SESSION);
            resp.sendRedirect("/javaweb_filter_war_exploded/login.jsp");
        }else {
            resp.sendRedirect("/javaweb_filter_war_exploded/login.jsp");
        }
    }

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

}
  • 拦截器,不让直接访问成功页面:
package kuang.filter;

import kuang.utli.Constant;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SysFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //ServletRequest   HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if (request.getSession().getAttribute(Constant.USER_SESSION) == null) {
            response.sendRedirect("/javaweb_filter_war_exploded/error.jsp");
        }

        filterChain.doFilter(request,response);//这句必须写。
    }

    public void destroy() {

    }
}
  • 设置常量:
package kuang.utli;

//设置一个常用的常量,用到的时候直接调。
public class Constant {
    public final static String USER_SESSION = "USER_SESSION";
}
  • 登陆页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>登陆</h1>

<form action="${pageContext.request.getContextPath()}/servlet/login" method="post">
    <input type="text" name="username">
    <input type="submit">
</form>

</body>
</html>
  • 成功页面:
<%@ page import="kuang.utli.Constant" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>主页</h1>

<p><a href="${pageContext.request.getContextPath()}/servlet/logout">注销</a></p>

</body>
</html>
  • 失败页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>错误</h1>
<h3>没有权限,用户名错误。</h3>

<a href="${pageContext.request.getContextPath()}/login.jsp">返回登陆页面</a>

</body>
</html>
  • xml 配置:
<servlet>
    <servlet-name>loginServlet</servlet-name>
    <servlet-class>kuang.servlet.loginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>loginServlet</servlet-name>
    <url-pattern>/servlet/login</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>logoutServlet</servlet-name>
    <servlet-class>kuang.servlet.logoutServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>logoutServlet</servlet-name>
    <url-pattern>/servlet/logout</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>SysFilter</filter-name>
    <filter-class>kuang.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>SysFilter</filter-name>
    <url-pattern>/sys/*</url-pattern>
</filter-mapping>

14、JDBC

前面MySql学过,这里是复习!

什么是JDBC : Java连接数据库!

在这里插入图片描述

需要jar包的支持:

  • java.sql
  • javax.sql
  • mysql-conneter-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','123456@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,`email`,`birthday`)
VALUES (2,'李四','123456','123456@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,`email`,`birthday`)
VALUES (3,'王二麻子','123456','123456@qq.com','2000-01-01');

SELECT * FROM users;

导入数据库依赖:

<!-- 连接数据库 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>

IDEA中连接数据库:

MySql笔记详细介绍,这里不写了!(偷个懒)

JDBC 固定步骤:

  1. 加载驱动;
  2. 连接数据库,代表数据库;
  3. 向数据库发送SQL的对象Statement : CRUD;
  4. 编写SQL (根据业务,不同的SQL);
  5. 执行SQL;
  6. 关闭连接.(先开的后关)
package kuang.test;

import java.sql.*;

public class TestJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //配置信息
        //useUnicode=true&characterEncoding=utf8   解决中文乱码。
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&useSSL=true";
        String username = "root";
        String password = "newpass";

        //1。加载驱动
        Class.forName("com.mysql.jdbc.Driver");

        //2。连接数据库,代表数据库。
        Connection con = DriverManager.getConnection(url, username, password);

        //3.向数据库发送SQL的对象Statement,PreparedStatement:CURD
        Statement st = con.createStatement();

        //4.编写SQL
        String sql = "SELECT * FROM users";

        /*String sql2 = "delete from users where id = 5";
        //返回受影响的行数。增删改都是executeUpdate。
        int i = st.executeUpdate(sql2);*/

        //5.执行查询SQL,返回一个ResultSet:结果集
        ResultSet rs = st.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();
        st.close();
        con.close();
    }
}

预编译SQL

package kuang.test;

import java.sql.*;

public class TestJdbc2 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //配置信息
        //useUnicode=true&characterEncoding=utf8   解决中文乱码。
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&useSSL=true";
        String username = "root";
        String password = "newpass";

        //1。加载驱动
        Class.forName("com.mysql.jdbc.Driver");

        //2。连接数据库,代表数据库。
        Connection con = DriverManager.getConnection(url, username, password);

        //3.编写SQL
        String sql = "insert into users(id, name, password, email, birthday) VALUES (?,?,?,?,?);";

        //4。预编译
        PreparedStatement pst = con.prepareStatement(sql);

        pst.setInt(1,4);//给第一个占位符的值赋为1。
        pst.setString(2,"狂神");
        pst.setString(3,"123456");
        pst.setString(4,"kuangshen@qq.com");
        pst.setDate(5,new Date(new java.util.Date().getTime()));

        //5。执行SQL
        int i = pst.executeUpdate();
        if (i>0){
            System.out.println("执行成功!");
        }

        //6.关闭连接,释放资源(一定要做),先开后关。
        pst.close();
        con.close();
    }
}

事务

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

ACID原则:保证数据的安全。

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

转账:
A:1000
B:1000
    
A(900)   --100-->   B(1100) 

Junit单元测试

导入依赖:

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

简单使用:

@Test注解只有在方法上有效,只要加了这个注解的方法,就可以直接运行!

@Test
public void test(){
    System.out.println("Hello");
}

在这里插入图片描述

失败的时候是红色:

在这里插入图片描述

搭建一个环境

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);
package kuang.test;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class TestJdbc3 {

    @Test
    public void test(){
        //配置信息
        //useUnicode=true&characterEncoding=utf8   解决中文乱码。
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&useSSL=true";
        String username = "root";
        String password = "newpass";

        Connection connection = null;

        try {
            //1。加载驱动
            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 throwables) {
                throwables.printStackTrace();
            }
        } finally {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

}

15、SMBMS(超市订单管理系统)

链接:https://pan.baidu.com/s/12MmpF9msJVjLT1U77XYfRw
提取码:11fv

SMBMS博客在这里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值