javaWeb 之基础理解

javaWeb

基本概念

  • 静态Web

    • Html Css
    • 提供给人看的数据始终不会发生变化

    存在的缺点:

  • WEB页面无法更新,所有用户看到的都是同一个页面

    • 轮播图 点击特效 :伪特效
    • JavaScript
  • 无法和数据库交互数据无法持久化

  • 动态Web

    • 淘宝 几乎是所有的网站
    • 提供给人看的数据始终会发生变化,每个人在不同的时间,不同的时间地点看到的内容各不相同
    • 技术栈 Severlet、JSP、ASP\PHP

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OOKpQu3p-1618562073045)( image-20201208160308960.png)]

    缺点

    • 假如服务器的动态web资源出现了错误,需要重新编写后台程序重新发布

    优点

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

    • 它可以与数据库交互(数据持久化:注册,商品信息…)

WEB服务器

三大技术

  • ASP 微软 国内最早最流行的
  • PHP 开发简单 速度快 跨平台 但不支持高并发
  • JSP sun 主推的B/S架构 支持高并发 高可用 高性能

web 服务器

服务器是一种被动的操作,用来处理用户的请求

  • IIS

    微软的 ASP Windows中自带

  • Tomcat

    Apache

Tomcat

安装tomcat

tomcat安装配置

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tlkJ6Ggz-1618562073048)( image-20201208162430920.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KQqTFdKB-1618562073051)( image-20201208162707404.png)]

配置主机的名称

  <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

配置主机的端口

<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" />

如何访问一个网页?

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UiPf9ULC-1618562073054)( image-20201208163705990.png)]

Http

Http(超文本传输协议)是一个简单的请求响应协议,它通常运行在TCP上 80

Https: 安全的 443

两个时代

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

http请求

客户端 -(Request)–> 服务器

Request URL: https://www.baidu.com/? 请求地址
Request Method: GET //方法
Status Code: 200 OK //状态码
Remote (远程) Address: 163.177.151.110:443
Accept: text/html 
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Cache-Control: max-age=0
Connection: keep-alive

请求行

  • 请求行中的请求方式 GET
  • 请求方式:GET POST HEAD DELETE PUT …
    • get 请求能够携带的参数比较少,大小有限制,会在浏览器的URL地址栏显示数据内容,不安全但是高效
    • post 请求能够携带的参数没有限制,大小也没有限制,不会再浏览器的URL地址栏显示数据内容,安全,但不高效

请求头

Accept 告诉浏览器它所支持的类型
Accept-Encoding 编码格式
Accept-Language 语言环境
Cache-Control 缓存控制
Connection 断开还是连接

http响应

服务器 -(Response)–> 客户端

Cache-Control: private  //缓存控制
Connection: keep-alive  //连接
Content-Type: text/html;charset=utf-8//编码

响应体

Accept 告诉浏览器它所支持的类型
Accept-Encoding 编码格式
Accept-Language 语言环境
Cache-Control 缓存控制
Connection 断开还是连接
Refresh 告诉客户端多久刷新一次
Location 让网页重新定位

2.响应状态码

200: 成功

3xx: 请求重定向

4xx: 找不到资源 404

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

常见的面试题

当你的浏览器中地址栏输入地址并UI车的一瞬间到页面能够展示回来,经历了什么?

maven

<mirror>
    <id>aliyunmaven</id>
    <mirrorOf>*</mirrorOf>
    <name>阿里云公共仓库</name>
  <url>https://maven.aliyun.com/repository/public</url>
</mirror>

然后在IDEA中设置,忽略HTTPS的SSL证书验证就好了,注意是在Maven-Importing-VM options for importer里添加

-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true

Servlet

开发servlet两个步骤

  • 编写一个类实现servlet接口
  • 把开发好的类部署到web服务器中

helloServlet

IDEA中的xml太老了 换新的

<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"
  metadata-complete="true">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tom	cat
  </description>
   
</web-app>

关于父子工程的理解

<modules>
    <module>servlet-01</module>
</modules>

父项目中的jar包可以共享给子项目

编写一个servlet程序

  • 编写一个普通类

  • 实现Setvlet接口,我们这里直接继承HttpServlet类

public class HelloServlet  extends HttpServlet {

   //由于get和post只是请求的方式不一样,业务逻辑是没有什么区别的,只要实现get就好
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter printWriter = resp.getWriter();
        printWriter.println("Hello Servlet");
    }

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

配置Servlet映射

为什么需要映射

因为我们的servlet是一个java程序,我们需要通过浏览器区访问Web服务器来访问它,所以需要在web服务中映射它,并给它一个浏览器可以访问的路径

<!-- 注册一个servlet-->
<servlet>
  <servlet-name>hello</servlet-name>
  <servlet-class>com.xin.servelet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>hello</servlet-name>
  <url-pattern>/hello</url-pattern>
</servlet-mapping>

配置Tomcat

启动OK

Sevlet原理

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xFRt0ven-1618562073055)( image-20201209161010182.png)]

Maping问题

1.映射唯一路径

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

2.映射多个路径

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

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

3.映射通配的任意路径

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

4.映射默认路径

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

5.映射前缀或者后缀路径

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

ServletContext

Web容器在启动的时候会创建一个对应的ServletContext对象,他代表了当前的web应用

1.共享数据

我在这个servlet上传的数据在另一个servlet中会获得

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

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

        ServletContext context = this.getServletContext();
        String username = (String) context.getAttribute("username");
        PrintWriter writer = resp.getWriter();
        writer.print(username);

    }
}
public class Set extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        context.setAttribute("username","name");

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

}
2.获取初始化参数
<context-param>
  <param-name>url</param-name>
  <param-value>mysql:jdbc://localhost:3306/mabatis</param-value>
</context-param>
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ServletContext context = this.getServletContext();
        String url = context.getInitParameter("url");
        resp.getWriter().print(url);

    }
}
3.请求转发

请求转发和重定向是不一样的,都是实现页面跳转,转发地址不会改变,重定向地址会改

相当于这个servlet获得目标页面然后在自己身上运行给请求的对象看

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    context.getRequestDispatcher("/dp").forward(req,resp);//请求转发
}
4.读取资源文件

Properties

被打包到target文件夹下的/WEB-INF/classes

user = root
pass = 773080152
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    ServletContext context = this.getServletContext();
    InputStream inputStream = context.getResourceAsStream("/WEB-INF/classes/db.properties");//获取资源文件为流
    
    Properties properties = new Properties();
    properties.load(inputStream);//properties加载需要将文件转换为流然后加载出来  本来是用File  web就用context上下文来获得

    resp.getWriter().print(properties.get("user"));
5.HttpServletResponse

负责向浏览器发送数据

ServletOutputStream getOutputStream() throws IOException;

PrintWriter getWriter() throws IOException;

负责向浏览器发送响应头信息

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

void setStatus(int var1);

响应状态码

int SC_CONTINUE = 100;
int SC_SWITCHING_PROTOCOLS = 101;
int SC_OK = 200;
int SC_CREATED = 201;
int SC_ACCEPTED = 202;
int SC_NON_AUTHORITATIVE_INFORMATION = 203;
int SC_NO_CONTENT = 204;
int SC_RESET_CONTENT = 205;
int SC_PARTIAL_CONTENT = 206;
int SC_MULTIPLE_CHOICES = 300;
int SC_MOVED_PERMANENTLY = 301;
int SC_MOVED_TEMPORARILY = 302;
int SC_FOUND = 302;
int SC_SEE_OTHER = 303;
int SC_NOT_MODIFIED = 304;
int SC_USE_PROXY = 305;
int SC_TEMPORARY_REDIRECT = 307;
int SC_BAD_REQUEST = 400;
int SC_UNAUTHORIZED = 401;
int SC_PAYMENT_REQUIRED = 402;
int SC_FORBIDDEN = 403;
int SC_NOT_FOUND = 404;
int SC_METHOD_NOT_ALLOWED = 405;
int SC_NOT_ACCEPTABLE = 406;

下载文件

package com.xin.response;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

public class DownDeno extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取文件的下载路径
        String path = "E:\\IDEA_workSpace\\javaweb-02-servlet\\response\\src\\main\\resources\\czx.png";
        //2.文件的名字
        String Filename = path.substring(path.lastIndexOf("\\")+1);

        //设置响应头让浏览器知道我们是要下载,中文文件名
        resp.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(Filename,"utf-8"));
        //获取文件的输入流
        InputStream fileInputStream = new FileInputStream(path);
        //创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];

        //获取Outputstream对象
        ServletOutputStream outputStream = resp.getOutputStream();

        //将输入流写到缓冲区然后写到输出流中
        while((len = fileInputStream.read())!=0){
            outputStream.write(buffer,0,len);
        }
        fileInputStream.close();
        outputStream.close();
    }

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

3、验证码功能

public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //让浏览器3秒刷新一次
        resp.setHeader("refresh","3");

        //在内存中创建一个图片
        BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
        //得到图片
        Graphics2D g = (Graphics2D) image.getGraphics();

        g.setColor(Color.WHITE);
        g.fillRect(0,0,80,20);

        //写数据
        g.setColor(Color.BLUE);
        g.setFont(new Font(null,Font.BOLD,20));
        g.drawString(make(),0,20);

        //告诉浏览器这个请求用图片方式打开
        resp.setContentType("image/jpeg");
        //不让浏览器缓存
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");

        ImageIO.write(image,"jpg",resp.getOutputStream());

    }

    private String make() {
        Random random = new Random();
        String num = random.nextInt(99999999)+"";
        StringBuffer num1 = new StringBuffer();
        for (int i = 0; i < 8-num.length(); i++) {
            num1.append(0);
        }
        num=num1.toString()+num;
        return num;
    }

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

重定向

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/**
 *      resp.setHeader("Location" ,"/s/img");
 *      resp.setStatus(302);
 */

        resp.sendRedirect("/s/img");
    }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String user = req.getParameter("user");
    String passw = req.getParameter("passw");
    System.out.println(user+" "+passw);
    resp.sendRedirect("/s/hello.jsp");
    
}

表单提交然后重定向到servlet

<%--这里的路径需要寻找到项目的路径--%>
<form action="${pageContext.request.contextPath}/req" method="get">
  用户名:<input type="text" name="user">
    密码: <input type="password" name="passw">
<input type="submit">
6.HttpServletRequrst

代表客户端的请求,用户通过Http协议访问服务器,Http请求中的所有信息会被封装到request中,通过HttpServletRequrst方法我们可以获得客户端的所有信息

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9tKnKGu1-1618562073058)( image-20201210204918317.png)]

获得前端的参数请求转发

​ [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-F1rM9V2j-1618562073060)( image-20201210205051647.png)]

getRequestDispatcher分成两种,可以用request调用,也可以用getServletContext()调用 不同的是request.getRequestDispatcher(url)的url可以是相对路径也可以是绝对路径。而this.getServletContext().getRequestDispatcher(url)的url只能是绝对路径。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<div  style="text-align: center">
    <form action="${pageContext.request.contextPath}/login" method="post">
     用户名:<input type="text" name="user">
        密码:<input type="password" name="pass">
        爱好:
        <input type="checkbox" name="hobby" value="女人">女人
        <input type="checkbox" name="hobby" value="代码">代码
        <input type="checkbox" name="hobby" value="尼玛">尼玛
        <input type="checkbox" name="hobby" value="水电">水电
        <br>
        <input type="submit">
    </form>
</div>
</body>
</html>

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   req.setCharacterEncoding("utf-8");
   resp.setCharacterEncoding("utf-8");

    String user = req.getParameter("user");
    String pass = req.getParameter("pass");
    String[] hobbies = req.getParameterValues("hobby");

    System.out.println(user + " " + pass);
    System.out.println(hobbies);

    req.getRequestDispatcher("/sucess.jsp");

}
Cookie Session

会话: 用户打开了浏览器,点击了很多超链接,访问了很多WEB资源,关闭浏览器

有状态会话

无状态会话

保存会话的两种技术

session

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

cookie

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kG32z9Ri-1618562073063)( image-20201211162740618.png)]

    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();
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("lastLoinTime")){
                out.write("你第一次访问的时间为"+new Date(Long.parseLong(cookie.getValue())).toString());
            }
        }
        //服务器响应给客户端一个Cookie
        Cookie cookie = new Cookie ("lastLoinTime",System.currentTimeMillis()+"");
        cookie.setMaxAge(24*24*60);
        resp.addCookie(cookie);//创建一个cookie
    }

Cookie 一般保存在本地

cookie是否存在上限?

  • 一个cookie只能存一个信息
  • 一个web站点可以给浏览器发送多个cookie,最多存放20个
  • cookie有大小限制 4kb
  • 300个cookie 浏览器上限

删除cookie

  • 不设置有效期,关闭浏览器自动失效
  • 设置有效期为0setMaxAge(0)

编码解码

URLEncoder.encode("阿斯蒂芬","utf-8");
URLDecoder.decode("士大夫","UTF-8");
Session(重点)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LP3jX1Xu-1618562073064)( image-20201211163002693.png)]

什么是session?

  • 服务器会给每一个用户创建一个Session对象
  • 一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就会存在
  • 用户登录之后,整个网站他都可以访问

Session 和Cookie的区别

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

Session的使用场景

  • 用户的登录信息
  • 购物车信息
  • 整个网站中经常用到的信息

Session的使用

<session-config>
<!--    //设置什么时间session失效  分钟为单位-->
    <session-timeout>1</session-timeout>
  </session-config>
    @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.setAttribute("name","czx");
        
        //Session的ID
        String sessionId = session.getId();
        PrintWriter writer = resp.getWriter();


        if(session.isNew()){
        writer.write("这个session是新创建的:"+sessionId);
        }
        else{
            writer.write("这个session是旧的:"+sessionId);
        }

        //Session在创建的时候做了什么
//        Cookie cookie = new Cookie("JSESSIONID", "FD34C2D05FDF0B9C92737A7E02401CB1");
//        resp.addCookie(cookie);
    }
//获得session的信息
        HttpSession session = req.getSession();

        String name = (String) session.getAttribute("name");
//注销Session
HttpSession session = req.getSession();
session.removeAttribute("name");
//手动注销
session.invalidate();

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UMfbo6iE-1618562073065)( image-20201211163202296.png)]

JSP

什么是JSP

java server page 也是和servlet一样用来开发动态Web

写jsp就像再写htnl(区别)

  • Html只提供静态的数据
  • JSP页面中可以嵌入java代码为用户提供动态的数据

JSP原理

IDEA中jsp生成java的存放位置

C:\Users\77308\AppData\Local\JetBrains\IntelliJIdea2020.2\tomcat\Unnamed_javaweb-02-servlet_2\work\Catalina\localhost\session_cokkie_war\org\apache\jsp

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6pJ5DhH0-1618562073067)( image-20201211165928959.png)]

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

  public void _jspInit() {//初始化
  }

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

判断请求

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

定义servlet对象

final javax.servlet.jsp.PageContext pageContext;   //页面上下文
javax.servlet.http.HttpSession session = null;	//session	
final javax.servlet.ServletContext application;//applicationcontext
final javax.servlet.ServletConfig config;//配置
javax.servlet.jsp.JspWriter out = null;//输出对象
final java.lang.Object page = this;//当前页
HttpServletRequest request;  //请求
HttpServletResponse response//响应

输出页面前的设置

  response.setContentType("text/html;charset=UTF-8"); 
  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;

以上的对象我们可以在jsp页面中使用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-q9o3HaaO-1618562073071)( image-20201211190753605.png)]

JSP语法

JSP表达式

<%-- JSP表达式--%>
<%--用来将程序的输入输出到客户端--%>
<%= new java.util.Date()%>

jsp脚本片段

<%--jsp脚本片段--%>
<%
    int n = 9;
    int sum = 0;
    for (int i = 0; i < 8; i++) {
        sum+=i;
    }
out.write("<h1>"+sum+"</h1>");
%>

jsp声明 作用域在类下 上面那些在方法中

<%--JSP声明--%>
<%!
    //设置一些全局变量
    //方法()
%>

html的注释会再客户端查看源码的时候显示,JSP就不会 安全

JSP指令

<%@ page .... %> 设置页面的各种属性

<%--将三个页面里的内容取出来放在这个页面中,本质是只有一个页面--%>
<%@include file="common/head.jsp"%>
<h1>主体</h1>
<%@include file="common/foot.jsp"%>

<%--本质上将三个页面拼接在一起  还是三个页面--%>
<jsp:include page="common/foot.jsp"></jsp:include>
<h1>主体</h1>
<jsp:include page="common/foot.jsp"></jsp:include>
    
    引入JSTL标签库
 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

9大内置对象

  • PageContext 存东西 保存的数据只在一个页面中有效

    请求与转发
    pageContext.forward("/index.jsp"); 
    request.getRequestDispatcher("/index.jsp").forward(request,response);
    
  • Request 存东西 保存的数据只在一次请求中有效,请求转发会携带这个数据

  • Response

  • Session 存东西 保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器

  • Application(SevletContext) 存东西 保存的数据只在服务器中有效,从打开放服务器到关闭服务器(牛逼)

  • Config

  • out

  • page 不用了解

  • exeption

4大作用域

public static final int PAGE_SCOPE = 1;// 页面
public static final int REQUEST_SCOPE = 2; //请求
public static final int SESSION_SCOPE = 3;//会话
public static final int APPLICATION_SCOPE = 4;//Session
<% pageContext.setAttribute("name","你爹");%>
<% request.setAttribute("name","你爹");%>
<% session.setAttribute("name","你爹");%>
<% application.setAttribute("name","你爹");%>

<%=application.getAttribute("name")%>
<%=session.getAttribute("name")%>
<%=pageContext.getAttribute("name")%>
<%String name = (String) request.getAttribute("name");%>

<%@ page isELIgnored="false" %>加一个这个指令
EL表达式
${name}
获取数据
执行运算
获取web开发的常见应用

JSTL标签库

为了弥补html标签的不足,功能和java代码是一样的

https://www.runoob.com/jsp/jsp-jstl.html

JavaBean

实体类

JavaBean的特有写法

  • 必须要有一个无参构造器
  • 属性必须私有化
  • 必须有对应的setget

一般和数据库的指端做映射 ORM

ORM 对象光系映射

表–>类

字段->映射

行记录-> 对象

<jsp:useBean id="people" class="com.xin.pojo.People" scope="page" />
<jsp:setProperty name="people" property="id" value="1"/>
<jsp:setProperty name="people" property="address" value="漳州"/>
<jsp:setProperty name="people" property="name" value="张鑫"/>

<jsp:getProperty name="people" property="name" />
<jsp:getProperty name="people" property="id" />
<jsp:getProperty name="people" property="address" />

<%  People people1=new People();
    people1.setId(1);
    people1.setName("s");
    people1.setAddress("zz");
%>

MVC三层架构

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OGhXvTX7-1618562073072)( image-20201211215503764.png)]

MODEL 后端
  • 业务处理(Service)
  • 数据持久层 CRUD (Dao)
VIEW 前端
  • 展示数据
  • 提供链接发起servlet请求
Contrller(Servlet) 相当于一个转换器 来处理前端和后端的交互
  • 接受用户的请求(req : 请求参数 Sesiion信息)
  • 交给业务MODEL层处理
  • 控制视图的跳转

Filter

Filter:用来过滤网站的数据

常见应用: 登录判断 乱码

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KnJsGfo9-1618562073073)( image-20201212142638943.png)]

 <filter>
    <filter-name>FilterEncodeing</filter-name>
    <filter-class>FilterEncodeing</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>FilterEncodeing</filter-name>
<!--    只要经过/servlet这个的就会被过滤-->
    <url-pattern>/servlet/*</url-pattern>
  </filter-mapping>
/**
 * 初始化在web服务器启动的时候
 *销毁在web关闭的时候
 * Chain 链
 *
 *
 */
public class FilterEncodeing implements Filter {
    @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("执行前");
        filterChain.doFilter(servletRequest,servletResponse);//让程序继续走,否则就会停止
        System.out.println("执行后");
    }


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

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");
    }
}

监听器

实现一个监听器的接口.

public class Listener implements HttpSessionListener {
    //一旦销毁一次Session就会触发一次
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext servletContext = se.getSession().getServletContext();
        Integer count = (Integer) servletContext.getAttribute("count");
        if(count == null){
            servletContext.setAttribute("count",0);
        }else{
            count = new Integer(count.intValue()-1);
            servletContext.setAttribute("count",count);
        }
    }
    //一旦创建一次Session就会触发一次
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext servletContext = se.getSession().getServletContext();
        Integer count = (Integer) servletContext.getAttribute("count");
        if(count == null){
            servletContext.setAttribute("count",1);
        }else{
            count = new Integer(count.intValue()+1);
            servletContext.setAttribute("count",count);
        }

    }

在xml中注册

<listener>
  <listener-class>Listener</listener-class>
</listener>
lterConfig) throws ServletException {
        System.out.println("初始化");
    }
}

监听器

实现一个监听器的接口.

public class Listener implements HttpSessionListener {
    //一旦销毁一次Session就会触发一次
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext servletContext = se.getSession().getServletContext();
        Integer count = (Integer) servletContext.getAttribute("count");
        if(count == null){
            servletContext.setAttribute("count",0);
        }else{
            count = new Integer(count.intValue()-1);
            servletContext.setAttribute("count",count);
        }
    }
    //一旦创建一次Session就会触发一次
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext servletContext = se.getSession().getServletContext();
        Integer count = (Integer) servletContext.getAttribute("count");
        if(count == null){
            servletContext.setAttribute("count",1);
        }else{
            count = new Integer(count.intValue()+1);
            servletContext.setAttribute("count",count);
        }

    }

在xml中注册

<listener>
  <listener-class>Listener</listener-class>
</listener>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值