栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

javaWeb

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

javaWeb

javaWeb
  • 一级目录
    • 二级目录
      • 三级目录
  • 1 基本概念
    • 1.1 web开发:
    • 1.2web应用程序
    • 1.3 静态web
    • 1.4 动态web
  • 2web服务器
    • 2.1技术讲解
    • 2.2 web服务器
  • 3 Tomcat
    • 3.4 发布一个web网站
  • 4 https
    • 4.1 什么是http
    • 4.2 两个时代
    • 4.3 http请求
    • 4.4 http响应
  • 5 Maven
    • 5.1 Maven项目架构管理工具
    • 5.2 下载安装Maven
    • 5.3 配置环境变量
    • 5.4 阿里云镜像
    • 5.5 本地仓库
    • 5.6 在IDEA中使用maven
    • 5.7创建一个普通的maven项目
    • 5.8 标记文件夹功能(新版不需要)
    • 5.9 在idea中配置tomcat
    • 5.10 pom.xml文件
    • 5.12 idea中的一些操作
    • 5.13 遇到的一些问题(后续遇到问题可以开始查询)
  • 6 Servlet
    • 6.1 Servlet简介
    • 6.2 HelloServlet
    • 6.3 Servlet 原理
    • 6.4 mapping问题
    • 6.5 ServletContext
    • 6.6 HttpServletResponse
      • 6.6.1 简单分类
      • 6.6.2 常见应用
      • 6.6.3 验证码功能
      • 6.6.4 实现重定向
    • 6.7 HttpServletRequest
      • 6.7.1获取前端传递的参数
  • 7 cookies、Session
    • 7.1 会话
    • 7.2 保存会话的两种技术
    • 7.3 cookie
    • 7.3.1
      • 7.3.2 编码与解码
    • 7.4 Session(重点)
  • 8 JSP
    • 8.1 什么是JSP
    • 8.2 jsp原理
    • 8.3 jsp语法
    • 8.4 jsp指令(这部分有点混乱,有需要再回来补充)
    • 8.5 9大内置对象
    • 8.6 jsp标签、jstl标签、EL表达式
  • 9 javaBean
  • 10 MVC 三层架构
    • 10.1 以前
  • 11 过滤器(Filter)(重点!!!)
  • 12 监听器
  • 13 监听器 过滤器常见功能
  • 14 JDBC

一级目录 二级目录 三级目录 1 基本概念 1.1 web开发:

1.web,网页的意思
2.静态web:html css 提供给所有人看的数据始终不会发生变化
3.动态web,提供给所有人看的数据始终发生变化,每个人在不同的时间,不同的地点看到的信息各不相同
技术栈:servlet/jsp、asp、php
在java中,动态web资源开发的技术被统称为javaWeb:

1.2web应用程序

什么是程序
web应用程序:可以提供浏览器访问的程序;
a.html、b.html…多个web资源,这些web资源可以被外界访问,对外界提供服务;
你们能访问到的任何一个页面或者资源,都存在于这个世界的某一个角落的计算机上
url
这个统一的web资源会被放在同一个文件夹上,web应用程序–>tomcat:服务器
一个web应用由多部分组成(静态web,动态web)
html,css,js
jsp,servlet
java程序
jar包
配置文件
web应用程序编写完毕后,若想提供给外界访问:需要一个服务器来统一管理;

1.3 静态web

*.html这些都是网页后缀,如果服务器上一直存在这些东西,我们就可以直接进行读取

静态web存在的缺点:
1.web页面无法动态更新,所有用户看到都是同一个页面
(1)轮播图,点击特效:伪动态(js,VBscript)
(2)它无法和数据库交互(数据无法持久化,用户无法交互)

1.4 动态web

页面会动态展示:“web的页面展示的效果因人而异”

缺点:
(1)加入服务器的动态web资源出现了错误,我们需要重新编写我们的后台程序,重新发布(停机维护)
有点:
(1)web页面可以动态更新
(2)可以与数据库交互(数据持久化:注册,商品信息,用户)

2web服务器 2.1技术讲解

ASP:微软:国内最早流行的;在HTML中嵌入了VB的脚本,ASP+COM;在ASP开发中,基本一个页面都是嵌套,几千行的业务代码 ,页面极其混乱,维护成本高;C#;IIS
PHP:PHP开发速度很快,功能强大,跨平台,代码很简单,但是无法承载大访问量的情况(局限性)
JSP/Servlet:
1.sun公司主推的B/S架构,B/S浏览和服务器,C/S客户端和服务器
2.基于java语音的
3.可以承载三高问题带来的影响
4.语法像ASP,ASP–>JSP,加强市场强度;

2.2 web服务器

服务器是一种被动的操作,用来处理用户的一些请求和给用户一些相应信息;

IIS
微软的;ASP…windows中自带的
Tomcat
面向百度编程
工作3-5年之后,可以尝试手写tomcat服务器;

下载tomcat:
1.安装或者解压
2.了解配置文件以及目录结构
3.这个东西的作用

3 Tomcat

文件夹作用:

启动,关闭tomcat

访问测试 localhost:8080
可能遇到的问题:
1.java变量没有配置好
2.
3.

可以配置启动的的uankouhao
1.tomcat:8080
2.mysql:3306
3.http:80
4.https:443


高难度面试题
请你谈谈网站是如何进行访问的
1.输入一个域名,回车;
2.检查本机的C:WINDOWSSystem32driversetchosts配置文件下有没有这个域名映射;
1.有:直接返回ip对应的地址,这个地址中,有我们需要访问的web程序,可以直接访问
2.没有:去DNS服务器搜索,找到就返回,找不到就返回找不到;

4.可以配置一下环境变量(可选性)

3.4 发布一个web网站

不会就先模仿

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

--webapps:tomcat服务器的web目录
	-ROOT:
	-kuangstudy:网站的目录名
		-WEB-INF
			-classes:java程序
			-lib:web应用所依赖的jar包
			-web.xml
		-index.html 默认的首页
		-static
			-css
				-style.css
			-js
			-img
		-...
4 https 4.1 什么是http

超文本传输协议(Hyper Text Transfer Protocol,HTTP)是一个简单的请求-响应协议,它通常运行在TCP之上。它指定了客户端可能发送给服务器什么样的消息以及得到什么样的响应。请求和响应消息的头以ASCII形式给出;而消息内容则具有一个类似MIME的格式。这个简单模型是早期Web成功的有功之臣,因为它使开发和部署非常地直截了当。
1.文本:html,字符串,~…
2.超文本:图片,音乐,视频,定位,地图…
3.80
https:安全的
1.443(默认端口)

4.2 两个时代

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

4.3 http请求

客户端—发请求(Request)—服务器
百度:

Request URL: https://sp1.baidu.com/  请求地址
Request Method: GET 				get方法/post方法
Status Code: 200 OK					状态码:200
Remote Address: 183.232.231.172:443	远程地址
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,**.properties
                    ***.properties
                    **/*.xml
                
                false
            
        
    

5.12 idea中的一些操作 5.13 遇到的一些问题(后续遇到问题可以开始查询)

2.tomcat闪退
3.idea每次都要重复配置maven
4.maven项目中tomcat无法配置

6 Servlet 6.1 Servlet简介

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

Servlet中一些乱码的解决方式以及解释.
Servlet中文乱码原因

6.2 HelloServlet

两个默认的实现类:HttpServlet

1.构建一个(普通的)Maven项目,删掉里面的src目录,以后我们的学习就在这个项目里面建立Model;这个空的工程就是Maven的主工程
2.关于maven父子工程的理解:
父项目中会有

  
        servelet-01
    

子项目中会有

我的没有找到(暂且不管)

父项目中的java子项目可以直接使用
3.Maven环境优化
 1.修改web.xml为最新的
 2.将maven的结构搭建完整
4.编写一个servlet程序
 1.编写一个普通类
 2.实现servlet接口

Servlet接口

public interface Servlet {
    void init(ServletConfig var1) throws ServletException;
    ServletConfig getServletConfig();
    void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
    String getServletInfo();
    void destroy();
}
public class HelloServlet extends HttpServlet {
//    由于get或者post只是请求实现的不同的方式,可以相互调用,业务逻辑也一样

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

        PrintWriter writer = resp.getWriter();//相应流
        writer.print("Hello Servlet");
    }

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

5.编写Servlet的映射
为什么需要映射:我们写的是java程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务中注册我们写的Servlet,还需要给他 一个浏览器能够访问的路径;

 
    hello
    com.lin.servlet.HelloServlet
  
  
    hello
    /hello
  

配置tomcat
注意:配置项目发布的路径就可以了
7.启动测试

6.3 Servlet 原理

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

请求和响应.

6.4 mapping问题

1.一个Servlet可以指定一个映射路径
2.一个Servlet可以指定多个映射路径
3.一个Servlet可以指定通用映射路径


                hello
                /hello/*
        

4.默认请求路径(尽量不要用,会覆盖首页)


                hello
                /*
        

5.指定前缀和后缀等问题


                hello
                .lll
        

6.优先级问题
指定了固有的映射路径优先级最高,如果找不到就会找默认的请求;


    
        error
        com.lzf.myServlet.ErrorServlet
    
    
        error
        /*
    

public class ErrorServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf8");
        PrintWriter writer = resp.getWriter();
        writer.print("404");
    }

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


这里的配置只有一个,免得运行太慢

6.5 ServletContext

web容器在启动的时候,它会为每个web程序都创建一个对应的servletContext对象,它代表了当前的web应用;
1.共享数据(我在这个servlet保存的数据,可以在另外的一个servlet中使用)
(1)设置类

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        this.getInitParameter() 初始化参数
//        this.getServletConfig() servlet配置
//        this.getServletContext() servlet上下文
        ServletContext context = this.getServletContext();
        String username = "小林";//数据
        // 将一个数据保存在了servletcontext中,名字为username,值username
        context.setAttribute("username",username);

        System.out.println("Hello Test");
    }


}

(2)获取类

public class GetServlet extends HttpServlet {
    @Override
    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("utf8");

        PrintWriter writer = resp.getWriter();
        writer.print("名字"+username);
    }

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

(3)更新类

    
        getc
        com.lzf.servlet.GetServlet
    
    
        getc
        /getc
    

(4)测试访问结果;名字null

2.获取初始化参数

    
        url
        jdbc:mysql://localhost:3306/mabatis
    
        
        gp
        com.lzf.servlet.ServletDemo03
    
    
        gp
        /gp
    
public class ServletDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String url = context.getInitParameter("url");
        resp.getWriter().print(url);
    }

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

3.请求转发(注意和重定向的区别)

//注意web.xml要添加新的映射
public class ServletDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String url = context.getInitParameter("url");
        resp.getWriter().print(url);
    }

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


4.读取资源文件
Properties
1.在java目录下新建properties
2.在resources目录下新建properties
发现:都被打包到了同一路径下:classes,我们俗称这个路径为classpath
思路:需要一个文件流;

username = root
password = root
public class ServletDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");//这里要注意路径
        Properties prop = new Properties()
        prop.load(is);
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");

        resp.getWriter().print(username+":"+password);
    }

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

访问测试即可ok;

6.6 HttpServletResponse

web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;
1.如果要获取客户端请求过来的参数:找HttpServletRequest
2.如果要给客户端响应一些消息:找HttpServletResponse

6.6.1 简单分类

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

    ServletOutputStream getOutputStream() throws IOException;
    PrintWriter getWriter() throws IOException;

2.负责向浏览器发送响应的方法

6.6.2 常见应用

1.向浏览器输出消息(一直在讲,就不说了)

2.下载文件(建立新的环境,tomcat务必更换驱动)

(1)要获取下载文件的路径
(2)下载的文件名是啥
(3)设置想办法让浏览器能够支持下载我们需要的东西
(4)获取下载文件的输入流
(5)创建缓冲区
(6)获取OutputStream对象
(7)将FileOutputStream流写入到buffer缓冲区
(8)使用OutputStream将缓冲区种的数据输出到客户端

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//(1)要获取下载文件的路径
//        String realPath = this.getServletContext().getRealPath("F:\Program\java-web-servlet02\response\src\main\resources\JAVA后端.jpeg");
        String realPath = "F:\Program\java-web-servlet02\response\src\main\resources\JAVA后端.jpeg";
        System.out.println("下载文件的路径"+ realPath);
//(2)下载的文件名是啥
        String fileName = realPath.substring(realPath.lastIndexOf("\") + 1);
//(3)设置想办法让浏览器能够支持下载我们需要的东西,中文文件名URLEncoder.encode编码,否则有可能乱码(经典解决方法)
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8")); //面向百度查询(web下载文件的头信息)attachment(附件)
//(4)获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);
//(5)创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
//(6)获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
//(7)将FileOutputStream流写入到buffer缓冲区,(8)使用OutputStream将缓冲区种的数据输出到客户端
        while((len = in.read(buffer))>0){
            out.write(buffer,0,len);
        }
//(9) 关闭流
        in.close();
        out.close();
    }

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

路径设置错误的话报的异常

6.6.3 验证码功能

验证怎么来的?
前端实现
后端实现,需要用到java的图片类,生成一个图片

public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        如何让浏览器5s自动刷新一次
        resp.setHeader("refresh", "5");
//        在内存中创建一个图片
        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/jpeg");
        //网站存在缓存,不让浏览器缓存
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");

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

    }

    //生成随机数
    private String makeNum() {
        Random random = new Random();
        String num = random.nextInt(9999999) + "";
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 7 - num.length(); i++) {
            stringBuffer.append(random.nextInt(9)+"");  //这样可以保证验证码长度
        }
        num = stringBuffer.toString() + num;
        return num;
    }

6.6.4 实现重定向

(图片待补充)
一个web资源(B)收到客户端A请求后,他会通知客户端A去访问另外一个web资源(C),这个过程叫做重定向
常见场景:
1.用户登录

public class RedirectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setHeader("Location","/response_war/img");
//        resp.setStatus(HttpServletResponse.SC_FOUND);
        resp.setStatus(302); //和上面注释掉的等价
        resp.sendRedirect("/response_war/img");//重定向
    }

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

面试题:请你聊聊重定向和转发的区别
相同点:
页面都会实现跳转
不同点:
请求转发的时候,url不会产生变化,而重定向的时候url地址栏会发生变化


public class RequestTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        处理请求
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username+":"+password);
        System.out.println("进入这个请求了");
        resp.sendRedirect("/response/success.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
<%--
  Created by IntelliJ IDEA.
  User: lzf
  Date: 2021/9/19
  Time: 18:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


    

Success

6.7 HttpServletRequest

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

6.7.1获取前端传递的参数

自己测试出现的问题

此URL不支持Http方法POST.
请求的资源/$%7BpageContext.request.contextPath%7D/login不可用.

//404 一般是路径错误
//500 一般是页面错误
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(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[] hobbies = req.getParameterValues("hobby");
        System.out.println("=========================");
        System.out.println(username);
        System.out.println(password);
        System.out.println(Arrays.toString(hobbies));
        System.out.println("=========================");
//        通过请求转发
        System.out.println(req.getContextPath()); //获取路径的一个测试方法
//        tip:这里的/代表当前的web应用,因此已经在路径下了,可以直接找到该jsp文件
        req.getRequestDispatcher("/success.jsp").forward(req, resp);
    }

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

  Archetype Created Web Application
  
    loginServlet
    com.lzf.servlet.LoginServlet
  
  
    loginServlet
    /login
  


关于${pageContext.request.contextPath}的理解
"isELignored=false"的作用

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


    登录


登录

<%-- 这里表单表示的意思,以post方式提交表单,提交到我们的login请求--%> <%-- 原因是 ${} 没有解析出来。--%> <%-- <%@ page isELIgnored="true|false"%>如果设定为真,那么JSP中的表达式被当成字符串处理,我们通过字面意思理解一下:是否忽略el表达式,如果为true就是忽略el表达式,就是当做字符串来处理;反之,就是按el表达式来。--%> <%-- 如果通过简单的测试发现你的${pageContext.request.contextPath}为字符串,那么你把 isELIgnore 的 设置为 false 就好了。--%>
用户名:
密码:
爱好: 女孩 代码 唱歌 电影

== 请求转发和重定向的区别==

面试题:请你聊聊重定向和转发的区别
相同点:
页面都会实现跳转
不同点:
请求转发的时候,url不会产生变化 307
而重定向的时候url地址栏会发生变化 302

7 cookies、Session 7.1 会话

会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器这个过程可以称为会话
有状态会话:
怎么证明交了学费 :发票,收费记录
一个网站:怎么证明你来过?

客户端服务端
1.服务端给客户端一个信件,客户端下次访问服务端带上信件就可以了cookies
2.服务器登记你来过了,下次你来的时候我来匹配你;session
7.2 保存会话的两种技术

cookie
1.客户端技术(响应,请求)
session
1.服务器技术,利用这个技术,可以保存用户的会话信息?我们可以把信息或者数据放在session中

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

7.3 cookie 7.3.1

1.从请求中拿到cookie信息
2.服务器响应给客户端cookie

cookie[] cookies = req.getcookie;//获得cookie
cookie.getName()//获得cookie中的key(name)
cookie.getValue()//获得cookie中的value
new cookie("lastLoginTime", System.currentTimeMillis() + ""); 新建一个cookie对象
newcookie.setMaxAge(24 * 60 * 60); //设置cookie有效期
resp.addcookie(newcookie);//设置完cookie添加入响应

//到期时间
 public void setMaxAge(int expiry) {
	maxAge = expiry;
    }

这样设置无效

        resp.addcookie(newcookie);
//        设置cookie有效期
        newcookie.setMaxAge(24 * 60 * 60); //设置有效期为一天

应该这样设置

        cookie newcookie = new cookie("lastLoginTime", System.currentTimeMillis() + "");
//        设置cookie有效期
        newcookie.setMaxAge(24 * 60 * 60); //设置有效期为一天
        resp.addcookie(newcookie);


一个网站cookie是否存在上限!聊聊一些细节
1.一个cookie只能保存一个信息;
2.一个web站点可以给浏览器发送多个cookie,,最多存放20个cookie
3.300个cookie浏览器上限
4.cookie大小有限制,为4kb

删除cookie;
不设置有效期,关闭浏览器,自动生效;
设置有效期为0;

7.3.2 编码与解码
cookie cookie = new cookie("name", URLEncoder.encode("小林","utf-8"));
URLDecoder.decode(cookie.getValue(),"utf-8")
7.4 Session(重点)

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

Session和cookie的区别
1.cookie是吧用户的数据写给用户的浏览器,浏览器保存
2.session是把用户的数据写到用户独占的session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)
3.session对象由服务器创建;

//Session创建的时候做了什么事情
cookie cookie = new cookie("JSESSIONID", id);
resp.addcookie(cookie);

使用场景:
1.保存一个登录用户的信息;
2.购物车信息;
3.在整个网站中经常会使用的数据,我们将它保存在session中;

使用session:
demo1设置session信息

public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      //解决乱码问题
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset = utf-8");
//        得到Session
        HttpSession session = req.getSession();
//        给session存放东西
        session.setAttribute("name",new Person("夏琳",24));
        //获取session的id
        String id = session.getId();
        //判断session是否新创建
        if(session.isNew()){
            resp.getWriter().write("session创建成功,id"+id);
        }else {
            resp.getWriter().write("session已经在服务器中存在了,id"+id);
        }
//        //Session创建的时候做了什么事情
//        cookie cookie = new cookie("JSESSIONID", id);
//        resp.addcookie(cookie);
    }

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

demo2获得session信息

public class SessionDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      //解决乱码问题
        resp.setCharacterEncoding("utf-8");
        req.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());
        resp.getWriter().write(person.toString());
    }

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

demo3清楚session

public class SessionDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("name");
        //手动注销sessionId
        session.invalidate();
    }

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

session自动国企,web.xml配置

    

        20
    

cookie

Session

8 JSP 8.1 什么是JSP

javaServerPages:java服务器端页面,也和Servlet一样,用于动态wei技术!
最大的特点:
1.写jsp就像在写html
2.区别:
(1)html只给用户提供静态的数据
(2)jsp页面中可以嵌入java代码,为用户提供动态数据;

8.2 jsp原理

思路:jsp到底怎么执行的!
1.代码层面没有任何问题
2.服务器内部工作
(1)tomcat中有一个work目录;
(2)idea中使用tomcat的会在idea的tomcat中生产一个work目录
这个log的上级目录就是idea的工作目录

找到idea中的jsp,发现页面转变成了java程序!


浏览器向服务器发送请求,不管访问什么资源,其实都是在访问servlet!
jsp最终也会被转换成java类
jsp本质上是继承了Servlet
maven中的jsp

public interface HttpJspPage extends JspPage {
    void _jspService(HttpServletRequest var1, HttpServletResponse var2) throws ServletException, IOException;
}


public interface JspPage extends Servlet {
    void jspInit();

    void jspDestroy();
}

tomcat中的源码分析
1.判断请求

//初始化
 public void _jspInit() {
  }
//销毁
  public void _jspDestroy() {
  }
//jspService
  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
      throws java.io.IOException, javax.servlet.ServletException {

    if (!javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
      final java.lang.String _jspx_method = request.getMethod();
      if ("OPTIONS".equals(_jspx_method)) {
        response.setHeader("Allow","GET, HEAD, POST, OPTIONS");
        return;
      }
      if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method)) {
        response.setHeader("Allow","GET, HEAD, POST, OPTIONS");
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSP 只允许 GET、POST 或 HEAD。Jasper 还允许 OPTIONS");
        return;
      }
    }

2.内置了一些对象

    final javax.servlet.jsp.PageContext pageContext;//页面上下文
    javax.servlet.http.HttpSession session = null;//session
    final javax.servlet.ServletContext application;//改名为application
    final javax.servlet.ServletConfig config;//config
    javax.servlet.jsp.JspWriter out = null;//out
    final java.lang.Object page = this;//page;当前
    javax.servlet.jsp.JspWriter _jspx_out = null;//请求
    javax.servlet.jsp.PageContext _jspx_page_context = null;//响应

3.输出页面前增加的代码

      response.setContentType("text/html");//设置响应的页面类型
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

4.以上的这些对象可以在jsp页面中直接使用(疯狂封装)

在jsp页面中;
只要是java代码就会原封不动的输出;

    String name = "lzf";

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

      out.write("rn");
      out.write("rn");
      out.write("name : ");
      out.print(name);
      out.write("rn");
      out.write("rn");
      out.write("rn");

这样的格式输出到前端

8.3 jsp语法

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

链接: jsp语法.
jsp表达式

<%=new java.util.Date()%>

jsp脚本片段

<%
    int sum =1;
//    html自动转义
    out.print("sum = "+sum+"");
%>

脚本片段的再实现

花里胡哨的写法,在代码中嵌入html元素

<% for(int i = 0;i<5;i++){ %>

hello,world <%=1%>

<% } %>


JSP声明

<%!
    static {
        System.out.println("loading servlet");

    }
    private int globalVar = 0;
    public void lzf(){
        System.out.println("进入了某方法");
    }
    
%>

jsp声明:会被编译到jsp生成java的类中!其他的,就会被生成到_jspService方法中
在jsp,嵌入java代码即可!

jsp的注释,不会在客户端显示,html就会!

8.4 jsp指令(这部分有点混乱,有需要再回来补充)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--显示的声明表示这是一个错误页面--%>
<%@page isErrorPage="true" %>
<%--定制错误页面--%>
<%@ page errorPage="/error/500.jsp" %>


改成这样可以解决问题



图片必须是png格式才能被识别

8.5 9大内置对象

PageContext 存东西
Request 存东西
Response
Session 存东西
Application【ServletContext】存东西
config【ServletConfig】
out
page
exception

pageContext.setAttribute("name1", "小林1");//保存的数据只在一个页面中存放
request.setAttribute("name2", "小林2");//保存的数据只在一次请求中有效,请求转发会携带这个数据
session.setAttribute("name3", "小林3");//保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
application.setAttribute("name4", "小林4");//保存的数据只在服务器中有效,从打开服务器到关闭服务器

request:客户都向服务器发送请求,产生的数据,用户看完就没用,比如:新闻,用户看完没用的
session:客户端向服务器发送请求,产生的数据,用户用完一会还有用,比如:购物车;
application:客户端向服务器发送请求,产生的数据,一个用户用完了其他用户还可能使用,比如:聊天记录;

8.6 jsp标签、jstl标签、EL表达式
        
        
        
            javax.servlet.jsp.jstl
            jstl-api
            1.2
        
        
        
        
            taglibs
            standard
            1.1.2
        

EL表达式:${}
获取数据
执行运算
获取web开发的常用对象

jsp标签

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


    Title


<%--

1

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


    Title


2

name:<%=request.getParameter("name")%> age:<%=request.getParameter("age")%>

jstl表达式(待补充 )感觉不是特别重要
jstl标签库的使用就是为了弥补html标签的不足;它自定义许多标签类,可以供我们使用

格式化标签
sql标签
xml标签

核心标签(掌握部分)
jstl标签库
1.引入对应的taglib
2.使用其中的方法
3.在tomcat也要引入jstl的包,否则会报错,jstl解析错误

if测试


<%-- el表达式获取表单中的数据${param.参数名}--%> <%-- 判断如果提交的用户名是管理员,则登录成功--%> <%-- <%--%> <%-- if(request.getParameter("username").equals("admin")){--%> <%-- out.print("登陆成功");--%> <%-- }--%> <%-- %>--%>
9 javaBean

实体类
javaBean有特定的写法
1.必须要有一个无参构造
2.属性必须私有化
3.必须有对应的get/set方法
一般用来和数据库的字段做映射 ORM;
ORM:对象关系映射
表–>类
字段–>属性
行记录–>对象
people表

idnameageaddress
11号3西安
22号18西安
33号100西安
class People{
	private int id;
	private String name;
	private int age;
	private String address
	
}

class A{
	new People(1,"1号",3,"西安");
}

实体类

10 MVC 三层架构

什么是MVC:model view controller 模型视图控制器

10.1 以前

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

servlet–>crud–>database
弊端:程序十分臃肿,不利于维护 servlet的代码中:处理请求、响应、视图跳转、处理jdbc、处理业务代码、处理逻辑代码
架构:没有什么是加一层解决不了的,如果有,就再加一层
程序员调用
|
jdbc
|
masql oracle sqlServer


mvc三层架构


model
1.业务处理:业务逻辑(service)
2.数据持久层:crud(dao)
view
1.展示数据
2.提供链接发起servlet请求(a、form、img)
controller
1.接受用户的请求:(req:请求参数、sesion信息)
2.交给业务层处理对应的代码
3.控制视图的跳转

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

11 过滤器(Filter)(重点!!!)

Filter:过滤器,用来过滤网站的数据;
1.处理中文乱码(预先处理)
2.登录验证

filter开发步骤:
1.导包(不要导错)

2.编写过滤器
实现过滤器,重写过滤器的几种方法

package com.lzf.filter;

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

public class CharacterEncodingFilter implements Filter {
    //    初始化 web服务器启动就已经初始化了 随时等待监听对象出现
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");

    }

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

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

    //销毁 关闭的时候销毁
    public void destroy() {
        System.out.println("销毁");

    }
}

3.在web.xml中配置filter映射

    
        CharacterEncodingFilter
        com.lzf.filter.CharacterEncodingFilter
    
    
        CharacterEncodingFilter

        /servlet/*
    
12 监听器

实现一个监听器的接口;(有n种)
有bug待解决,不实时更新(后端里面不是特别重要)
1.编写一个监听器
实现监听器的接口:
2.web.xml中注册监听器


        com.lzf.listener.OnlineCountListener
    

3.看情况是否使用!

13 监听器 过滤器常见功能

监听器:gui编程中经常使用
1.用户登录之后才能进入主页!用户注销后就不能进入主页了!
2.进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现!

public class sysFilter implements Filter {
   @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Object user_session = request.getSession().getAttribute(Constant.USER_SESSION);
        if(user_session == null){
            response.sendRedirect("/error.jsp");
        }else {

        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
14 JDBC

1.什么是jdbc:(Java Database Connectivity )

需要jar包的支持:
1.java.sql
2.javax.sql
3.mysql-connetector-java…连接驱动(必须要导入)

实验环境搭建
1.创建表

CREATE TABLE users(`users``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-02-02'),
(3,'王五','1234567','ww@qq.com','2000-03-03');

SELECt * FROM users;

导入数据库依赖

        

            mysql
            mysql-connector-java
            8.0.25
        

3.idea中连接数据库

jdbc固定步骤

package com.lzf.jdbc;

import java.sql.*;

public class testJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //配置信息
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSI=true";
        String username = "root";
        String password = "root";

//        加载驱动
        Class.forName("com.mysql.jdbc.Driver");
//        2.连接数据库,代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);
//        3.向数据库发送sql的对象statement:crud
        Statement statement = connection.createStatement();
//        4.编写sql
        String sql = "select * from users";
//        5.执行sql,返回一个ResultSet
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()){
            System.out.println("id = "+resultSet.getObject("id"));
            System.out.println("name = "+resultSet.getObject("name"));
            System.out.println("password = "+resultSet.getObject("password"));
            System.out.println("email = "+resultSet.getObject("email"));
            System.out.println("birthday = "+resultSet.getObject("birthday"));
        }
//        6.关闭连接 先开的后关
        resultSet.close();
        statement.close();
        connection.close();

    }
}

事务
要么都成功,要么都失败
ACID原则:保证数据的安全
原子性、一致性、隔离性、持久性

1.开始事务
2.事务提交 commit()
3.事务回滚 rollback()
4.关闭事务

转账:
A:1000
b:1000

A(900) --100 --> B(1100)

junit单元测试
依赖

   
            junit
            junit
            4.0
        

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

搭建一个环境

package com.lzf.jdbc;


import org.junit.Test;

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

public class testJdbc3 {
    @Test
    public void test() throws  SQLException {  //配置信息
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSI=true";
        String username = "root";
        String password = "root";
        Connection connection = null;
        try {

//        加载驱动
        Class.forName("com.mysql.jdbc.Driver");
//        2.连接数据库,代表数据库
         connection = DriverManager.getConnection(url, username, password);
//        3.通知数据库开启事务,false开启
        connection.setAutoCommit(false);
//        4.执行sql语句
        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();
        System.out.println("success");
        }catch (ClassNotFoundException e){
            try {
                connection.rollback();//这里似乎有点问题
            }catch (SQLException e1){
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            connection.close();
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/287736.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号