javaWeb笔记

这篇博客介绍了JavaWeb的基础知识,包括Tomcat服务器的安装与配置、HTTP协议的工作原理、Maven的使用,以及Servlet的实现与原理。此外,还讨论了会话管理中的Cookie和Session,并简单介绍了JSP的概念和执行流程。

####

javaweb

狂神课程记的笔记

1、web服务器

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

IIS

微软的;ASP...Windows中自带的

Tomcat

轻量级应用服务器

运行JSP和Serviet

2、下载Tomcat:

1、安装

2、了解配置文件及目录结构

3、这个东西的作用

3、Tomcat

3.1、安装

3.2、Tomcat启动和配置

文件夹作用

端口配置

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

配置主机名称

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

谈谈网站是如何进行访问的

1、输入一个域名,回车

2、检查本机的 C:windows\System32\drivers\etc \host配置文件下有没有域名映射

1、有:直接返回对应的IP地址,这个地址中,有我们需要访问的web程序,可以直接访问

2、没有:去DNS服务器找,找到就返回,找不到返回找不到

3.3发布网站

  • 将自己写的网站发布到服务器中指定的Web应用文件夹下(webapps),就可以访问

网站要有的结构

--webapps:Tomcat服务器的web目录
    -ROOt
    -wqya : 网站目录名
        -Web-INF
            -classes : java程序
             -lib: web应用所依赖的jar包
             -web.xml:网站的配置文件
         -inde.html   默认首页
         -static
                 -css
                 -js
                 -img

4、http

4.1什么是HTTP

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

  • 文本:html,字符串

  • 超文本:图片、音乐、视频

  • 端口:80

HTTPS:安全的

  • 端口:443

4.2两个时代

  • http1.0

    • HTTP/1.0:客户端可以与web服务器连接后,只能获得一个web资源,断开连接

  • http2.0

    • HTTP/1.1:客户端可以与web服务器连接后,可以获得多个web资源

4.3HTTP请求

  • 客户端 --发请求--服务器

1、请求行

  • 请求行中的请求方式;GET

  • 请求方式:Get,Post,HEAD,DELETE,PUT,TRACT

    • get:请求能够携带的参数比较少,大小有限制,会在URL地址栏显示数据内容,不安全,但高效

    • post:请求能够携带的参数没有限制,大小没有限制,不会在URL地址栏显示数据内容,安全,但不高效

4.4、HTTP响应

  • 服务器--响应--客户端

https:更安全

1、响应体

2、响应状态码

200:请求响应成功

3xx:请求重定向

  • 重定向:你重新给我定位位置

4xx:找不到资源,资源不存在 404

5xx:服务器代码错误

5、Maven

为什么学Maven

1、在JavaWeb中,需要手动导入大量的jar包。

2、Maven能够自动导入和配置jar包

5.1、Maven项目架构管理工具

目前用来方便导入jar包

核心思想:约定大于配置

  • 有约束,不去违反

Maven会规定你改如何去编写java代码,必须按照规定来

5.2、下载Maven

5.3配置环境变量

系统变量

  • M2_HOME maven目录下的bin目录

  • MAVEN_HOME maven的目录

  • path配置 %MAVEN_HOME%\bin

测试,cmd mvn-v

5.4配置阿里云镜像

在setting.xml

       <mirror>
           <id>nexus-aliyun</id>
           <mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf>
           <name>Nexus aliyun</name>
           <url>http://maven.aliyun.com/nexus/content/groups/public</url> 
       </mirror>

5.5配置本地仓库

建立一个本地仓库

  <localRepository>C:\app\apache\apache-maven-3.8.4\maven-repo</localRepository>

5.6在IDEA使用Maven

5.7、pom.xml文件

pom.xml是Maven的核心配置文件

由于maven约定大于配置,我们之后写的配置文件,无法被到处或者生效

解决方案

maven高级之处是会帮你导入jar包所依赖的其他jar包

maven资源导出问题

<!--    在build配置resources,来防止我们资源导出失败问题-->
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <excludes>
          <exclude>**/*.properties</exclude>
          <exclude>**/*.xml</exclude>
        </excludes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
​
  </build>

6、servlet

6.1 servlet简介

  • servlet是sun公司开发的动态web的一门技术

  • sun公司在这些API中提供一个接口叫做:servlet,如果你想开发一个servlet程序,需要两个步骤

    • 编写一个类,实现servlet接口

    • 把开发好的java类部署到web服务器中

把实现Servlet接口的Java程序叫,Servlet

6.2 HelloServlet

Servlet接口Sun公司有两个默认的实现类:HttpServlet,

1、构建一个maven项目

2、编写一个Servlet程序

1、编写一个普通类

2、实现Servlet接口,这里我们继承HttpServlet

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.IOException;
import java.io.PrintWriter;
​
public class HelloServlet extends HttpServlet {
    //由于get post只是实现不同的方式,可以相互调用,业务逻辑都一样
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      
       ServletOutputStream outputStream = resp.getOutputStream ();
        PrintWriter writer = resp.getWriter ();//响应流
       
        
        writer.println ("helloServlet");
    }
​
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet (req, resp);
    }
}

3、编写Servletd的映射

为什么需要映射,我们写的Java程序,需要通过浏览器访问,而浏览器需要连接Web服务器,我们需要在web服务中注册我们写的Servlet,还需要给他一个浏览器访问的路径

  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.aqya.servlet.HelloServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

6.3、servlet原理

Servlet工作原理. 当Web服务器接收到一个HTTP请求时,它会先判断请求内容--如果是静态网页数据,Web服务器将会自行处理,然后产生响应信息;如果牵涉到动态数据,Web服务器会将请求转交给Servlet容器。. 此时Servlet容器会找到对应的处理该请求的Servlet实例来处理,结果会送回Web服务器,再由Web服务器传回用户端。. 针对同一个Servlet,Servlet容器会在第一次收到http请求时建立一个Servlet实例,然后启动一个线程。

6.4 Mapper问题

6.5 Servletcontesxt

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

1、共享数据

我在这个Servlet中保存的数据,可以在另外一个servlet中拿到;

2、获取初始化参数

<!--  配置web初始化参数-->
  <context-param>
  <param-name>url</param-name>
  <param-value>jdbc:mysql://localhost:3306</param-value>
  </context-param>

  <servlet>
    <servlet-name>getu</servlet-name>
    <servlet-class>com.aqya.servlet.ServletDemo03</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>getu</servlet-name>
    <url-pattern>/getu</url-pattern>
  </servlet-mapping>

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 ().println (url);


    }

3、求转发

public class ServletDemo04 extends HttpServlet {
    @Override
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws      ServletException, IOException {
        ServletContext context = this.getServletContext ();


//        RequestDispatcher requestDispatcher = context.getRequestDispatcher ("/getu");  //转发的请求路径
//        requestDispatcher.forward (req,resp);   //调用forWord方法实现请求转发
          context.getRequestDispatcher ("/getu").forward (req,resp);
    }

4、读取资源文件

Properties

  • 在Java目录下新建properties

  • 在resources目录下新建properties

发现:都被打包到同一个路径下:classes,我们俗称这个路径为classpath

   
//出现问题
protected void doGet(HttpServletRequest req, @org.jetbrains.annotations.NotNull HttpServletResponse resp) throws ServletException, IOException {

       InputStream is = this.getServletContext ().getResourceAsStream ("target/Servlet-02/WEB-INF/classes/com/aqya/servlet/aa.properties");
        Properties properties = new Properties ();
        properties.load (is);
        String username = properties.getProperty ("username");
        String pwd = properties.getProperty ("password");

        resp.getWriter ().println (username + ":" + pwd);

    }

6.3 HTTPServletResponse

web接收客户端的http请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResporse;

  • 如果要获取客户端请求响应的参数,找HTTPServletRequest

  • 如果要给客户端响应的一些信息,找HTTPServletReponsed

1、简单分类

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

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


负责向浏览器发送响应头

    void setCharacterEncoding(String var1);

    void setContentLength(int var1);

    void setContentLengthLong(long var1);

    void setContentType(String var1);

    void setBufferSize(int var1);


    void sendError(int var1, String var2) throws IOException;

    void sendError(int var1) throws IOException;

    void sendRedirect(String var1) throws IOException;

    void setDateHeader(String var1, long var2);
    void setHeader(String var1, String var2);
    void setIntHeader(String var1, int var2);

响应状态码

   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;
    int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
    int SC_REQUEST_TIMEOUT = 408;
    int SC_CONFLICT = 409;
    int SC_GONE = 410;
    int SC_LENGTH_REQUIRED = 411;
    int SC_PRECONDITION_FAILED = 412;
    int SC_REQUEST_ENTITY_TOO_LARGE = 413;
    int SC_REQUEST_URI_TOO_LONG = 414;
    int SC_UNSUPPORTED_MEDIA_TYPE = 415;
    int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    int SC_EXPECTATION_FAILED = 417;
    int SC_INTERNAL_SERVER_ERROR = 500;
    int SC_NOT_IMPLEMENTED = 501;
    int SC_BAD_GATEWAY = 502;
    int SC_SERVICE_UNAVAILABLE = 503;
    int SC_GATEWAY_TIMEOUT = 504;
    int SC_HTTP_VERSION_NOT_SUPPORTED = 505;

2、常见应用

1、向浏览器输出消息(getWriter,getOutputStream)

2、下载文件

1、获取下载文件路径

2、下载文件名

3、设置想办法让浏览器支持下载我们需要的东西

4、获取下载文件的输入流

5、创建缓冲区

6、获取OutputStream

7、获取OutputStream流写入到buffer缓冲区

8、使用Outpu的数据输出到缓冲区tStream将缓存区

  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//          1、获取下载文件路径
        String realPath = "E:\\workspaces\\workspace-Javacode\\IDEA\\idea\\javaWeb-02-Servlet\\Servlet-03-Response\\src\\main\\resources\\1.png";
//        String realPath = this.getServletContext ().getRealPath ("/1.png");
        System.out.println ("下载文件的路径"+realPath);
//        2、下载文件名
        String filename = realPath.substring (realPath.lastIndexOf ("\\")+1);
//          3、设置想办法让浏览器支持(Content-disposition)下载我们需要的东西
        resp.setHeader ("Content-disposition","attachment;filename="+filename);
//        ​	4、获取下载文件的输入流
        FileInputStream in = new FileInputStream (realPath);
//        ​	5、创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
//        ​	6、获取OutputStream对象
        ServletOutputStream  out = resp.getOutputStream ();
//        ​	7、获取OutputStream流写入到buffer缓冲区
        while ((len = in.read(buffer))>0){
            out.write (buffer,0,len);
        }
        in.close ();
        out.close ();

//        ​	8、使用Output的数据输出到缓冲区tStream将缓存区
    }

3、验证码功能

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


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

        //设置图片的背景颜色
        g.setColor (Color.white);
        g.fillRect (0,0,80,20);
        //给图片写数据
        g.setColor (Color.blue);
        g.setFont (new Font (null, Font.BOLD,20));
        g.drawString (makeNum (),0,20);

        //告诉浏览器这个请求用图片方式打开
        resp.setContentType ("image/jpg");

        //网站存在缓存  不让浏览器缓存
        resp.setDateHeader ("expires",-1);
        resp.setHeader ("Cache-Control","no-cache");
        resp.setHeader ("Pragma","no-cache");


        //把图片写给浏览器
        boolean write = ImageIO.write (image, "jpg",resp.getOutputStream ());

    }
    //生成随机数
    private  String makeNum(){
        Random random = new Random ();
        String num = random.nextInt (999999) + "";
        StringBuffer sb = new StringBuffer ();
        for(int i=0; i<6-num.length ();i++){
            sb.append ("0");
        }
        String s = sb.toString () + num;
        return  num;
    }


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

4、实现重定向

一个web资源收到客户端A请求后,B它会通知A客户端去访问另外一个web资源C,这个过程叫做重定向

void sendRedirect(String var1) throws IOException;
       /*
       resp.setHeader("location","/r/img");
       resp.setStatus(302);
        
       * */
        resp.sendRedirect ("/r/img");

面试题:重定向和转发的区别

相同点

  • 页面都会实现跳转

不同点

  • 请求转发的时候,是,内部跳转,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);

        resp.sendRedirect ("/r/success.jsp");
    }

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

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

<h1>success</h1>

</body>
</html>

6.4 HTTPServletRequest

1、获取前端传递的参数

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

<div  style="text-align: center">
<%--    以post方式提交表单--%>
    <form action="${pageContext.request.contextPath}/login" method="post">
        用户名: <input type="text" name="username"> <br>
        密码:<input type="password" name="password">  <br>
        爱好:
        <input type="checkbox" name="hobbys" value="女孩"> 女孩
        <input type="checkbox" name="hobbys" value="代码">  代码
        <input type="checkbox" name="hobbys" value="唱歌">  唱歌
        <input type="checkbox" name="hobbys" value="电影"> 电影
        <br>


        <input type="submit">

    </form>



</div>


</body>
</html>

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

<h1>登录成功</h1>

</body>
</html>

package com.aqya.servlet;/*
 @auther  wenqing
 @creat  2022-02-22 19:20
*/

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding ("UTF-8");
        resp.setCharacterEncoding ("UTF-8");
        String username = req.getParameter ("username");
        String password = req.getParameter ("password");
        String[] hobbys = req.getParameterValues ("hobbys");

        System.out.println ("=======================");
        System.out.println (username);
        System.out.println (password);
        System.out.println (Arrays.toString (hobbys));
        System.out.println ("=======================");
        System.out.println (req.getContextPath ());


        //通过请求转发
        req.getRequestDispatcher ("/success.jsp").forward (req,resp);

    }

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

2、请求转发

7、Cookie 、Session

7.1 会话

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

有状态会话:有同学来过教室,我们知道这个同学曾经来过;

怎么证明是学校的学生?

你 学校

1、学生证 学校给你发学生证

2、学校登记 学校给你登记了

一个网站,证明你来过?

客户端 服务端

1、服务端给客户端一个cookie ,客户端下次访问服务端带上信件 cookie;

2、服务器登记客户端来过,下次客户端来的时候匹配;IP

7.2 保存会话的两种技术

cookie

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

session

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

常见网站:网站登录之后,下次不用登录,第二次直接登录

7.3 Cookie

1、从请求中拿到Cookie信息

2、服务器响应给客户端cookie

Cookie[] cookies = req.getCookies ();   //获得cookie
cookie.getName ();  //获得cookie的key
cookie.getValue ();   //获得cookie的值
Cookie cookie = new Cookie ("lastLoginTime", System.currentTimeMillis ()+"");   //新建cookie
  cookie.setMaxAge (24*60*60);   //设置cookie有效期
resp.addCookie (cookie);         //响应给客户端

//保存用户上一次访问时间
public class CookieDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器告诉你来的时间,把这个时间封装成信,你带着来 就知道你来了

        //解决中文乱码
        req.setCharacterEncoding ("GBK");
        resp.setCharacterEncoding ("GBK");


        PrintWriter out = resp.getWriter ();

        //cookie  服务端从客户端获取
        Cookie[] cookies = req.getCookies ();   //返回数组 说明有多个

        //判断cookie是否存在
        if(cookies != null){
            //如果存在  怎么办
            out.write ("你上一次访问时间是:");
            for (int i = 0; i < cookies.length;i++){
                Cookie cookie = cookies[i];
              if(  cookie.getName ().equals ("lastLoginTime")){
                  //获取cookie的值
                  cookie.getValue ();
                 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 ()+"");
        resp.addCookie (cookie);

    }

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

一个网站cookie是否存在上限? 细节问题

  • 一个cookie只能保存一个信息

  • 一个web站点上可以给浏览器发送多个cookie,最多存放20多个cookie

  • Cookie大小限制4kb

  • 300个cookie浏览器上限

删除cookie

  • 不设置有效期,关闭浏览器,自动失效

  • 设置有效期时间为0

7.4 Session

什么是Session

  • 服务器会给每一个用户(浏览器)创建一个Session对象

  • 一个Session独占一个浏览器,只要浏览器没有关,这个Session就一直存在

  • 用户登录后网站就可以使用 ----->保存用户的信息,保存购物车的信息

Session 和 cookie区别

  • cookie是把用户的数据写给浏览器,给浏览器保存

  • session把用户的数据写到独占的session中,服务端保存(保存重要的东西 , 减少服务器资源的浪费)

  • session由服务器创建

使用场景

  • 保存一个登录用户信息

  • 购物车信息

  • 在整个网站中,经常会使用的数据,我们将它保存在session 中

使用session

//得到一个session
public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码问题
        req.setCharacterEncoding ("GBK");
        resp.setCharacterEncoding ("GBK");
        resp.setContentType ("text/html; charset=utf-8");

        //得到getSession
        HttpSession session = req.getSession ();


        //在Session中存东西
        session.setAttribute ("name",new Person ("wenqing",12));

        //获取Session的Id
        String id = session.getId ();

        //判断是否为新创建
        boolean aNew = session.isNew ();
        if(session.isNew ()){
            resp.getWriter ().write ("Session创建成功,ID"+id);

        }else{
            resp.getWriter ().write ("session已经在服务器中存在了"+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);
    }
}

//显示session

public class SessionDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码问题
        req.setCharacterEncoding ("GBK");
        resp.setCharacterEncoding ("GBK");
        resp.setContentType ("text/html; charset=GBK");

        //得到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);
    }
}



//手动注销session

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

    }

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





会话自动过去

<!--    设置Session默认失效时间-->
    <session-config>
        <session-timeout>1</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会生成一个tomcat 的work用户

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

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

JSP本质上就是一个Servlet

 HttpJspBase extends HttpServlet implements HttpJspPage
     
    //初始化 
     public void _jspInit() {
    }
	//销毁
    protected void _jspDestroy() {
    }
	//JSPService
  public abstract void _jspService(HttpServletRequest var1, HttpServletResponse var2) throws ServletException, IOException;

1、判断请求

2、内置对象

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

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

 response.setContentType("text/html; charset=UTF-8");  //设置响应的类型
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, false, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      out = pageContext.getOut();
      _jspx_out = out;

4、以上的这些个对象我们可以在JSP页面中直接使用

在JSP页面中,

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

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

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

这样的格式输出到前端

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值