JavaWeb-01

JavaWeb

Java web

1、基本概念

1.1 前言

web开发:

  • web,网页的意思,www.baidu.com

  • 静态web

    • html,css
    • 提供给所有人看的数据始终不会发生变化
  • 动态web

    • 淘宝,几乎所有的网站

    • 提供给所有人看的数据始终会发生变化,每个人在不同时间,不同的地点看到的信息各不相同

    • 技术栈:Servlet/JSP,ASP,PHP

在Java中,动态web资源开发的技术统称为JavaWeb;

1.2 web应用程序

web应用程序:可以提供浏览器访问的程序;

  • a.html、b.html……多个web资源,这些web资源可以被外界访问,对外界提供服务;
  • 能访问到的任何一个页面或者资源,都存在于这个世界的某一个角落的计算机上
  • URL:
  • 这些统一的web资源会被放在同一个文件夹下,web应用程序 --> Tomcat:服务器
  • 一个web应用由多部分组成(静态web,动态web)
    • html,css,js
    • jsp,servlet
    • jar包
    • 配置文件(Properties)

web应用程序编写完毕后,若想提供给外界访问,需要一个服务器来统一管理;

1.3 静态web

  • *.htm, *.html,这些都是网页的后缀,如果服务器上一直存在这些东西,我们就可以直接进行读取。
  • 静态web存在的缺点
    • web页面无法动态更新,所有用户看到的都是同一个页面
      • 轮播图,点击特效:伪动态
      • JavaScript(实际开发中,用的最多)
      • VBScript
    • 它无法和数据库交互(数据无法持久化,用户无法交互)

1.4 动态web

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


缺点

  • 假如服务器的动态web资源出现了错误,我们需要重新弄编写我们的后台程序,重新发布;
    • 停机维护

优点

  • web页面动态更新,所有用户看到的都不是同一个页面
  • 它可以和数据库交互(数据持久化:注册,商品信息,用户信息……)

在这里插入图片描述

2、Web服务器

2.1 技术讲解

ASP

  • 微软:国内最早流行的就是ASP
  • 在HTML中嵌入了VB脚本,ASP+COM
  • 在ASP开发中,基本一个页面都有几千行的业务代码,页面极其混乱
  • 维护成本高
  • C#
  • IIS

PHP

  • PHP开发速度很快,功能很强大,跨平台
  • 无法承载大访问量的情况(局限性)

JSP/Servlet

B/S:浏览器和服务器

C/S:客户端和服务器

  • sun公司主推的B/S架构
  • 基于Java语言的(所有的大公司,或者一些开源的组件,都是用Java写的)
  • 可以承载三高问题带来的影响
  • 语法像ASP,ASP–>JSP,加强市场强度

2.2 web服务器

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

IIS

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

Tomcat

在这里插入图片描述

Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,最新的Servlet 和JSP 规范总是能在Tomcat 中得到体现,因为Tomcat 技术先进、性能稳定,而且免费 ,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为目前比较流行的Web 应用服务器。

Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选。对于一个初学者来说,它是最佳的选择。

Tomcat 实际上运行JSP 页面和Servlet。目前Tomcat最新版本为9.0.31。

工作3-5年之后,可以尝试手写Tomcat服务器

3、Tomcat

可以配置启动的端口号

  • Tomcat的默认端口号:8080
  • mysql:3306
  • http:80
  • https:443
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

可以配置主机的名称

  • 默认的主机名为:localhost -> 127.0.0.1
  • 默认网站应用存放的位置为:webapps
<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

高难度面试题

请你谈谈网站是如何访问的?

  1. 输入一个域名:回车

  2. 检查本机的C:\Windows\System32\drivers\etc\hosts配置文件下有没有这个域名映射;

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

    127.0.0.1       localhost
    

    ​ 2.没有:去DNS服务器找,找到的话就返回,找不到就返回找不到
    在这里插入图片描述

3.1 发布一个web网站

不会就先模仿

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

4、Http

4.1 什么是HTTP

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

  • 文本:html,字符串,……
  • 超文本:图片,音乐,视频,定位,地图,……
  • 80

https:安全的

  • 443

4.2 两个时代

  • HTTP 1.0

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

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

4.3 HTTP请求

  • 客户端—发请求(Request)—服务器

百度:

Request URL: https://www.baidu.com/ 请求地址
Request Method: GET get方法/post方法
Status Code: 200 OK 状态码:200
Remote Address: 180.101.49.12: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

1、请求行

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

2、消息头

Accept: 告诉浏览器,它所支持的数据类型
Accept-Encoding: 支持哪种编码格式 GBK UTF-8 GB2312 ISO8859-1
Accept-Language: 告诉浏览器,它的语言环境
Cache-Control: 缓存控制
Connection: 告诉浏览器,请求是断开还是保持连接

4.4 HTTP响应

  • 服务器—响应—客户端

百度:

Cache-Control: private   缓存控制
Connection: keep-alive   连接
Content-Encoding: gzip   编码 
Content-Type: text/html  类型

1、响应体

Accept: 告诉浏览器,它所支持的数据类型
Accept-Encoding: 支持哪种编码格式 GBK UTF-8 GB2312 ISO8859-1
Accept-Language: 告诉浏览器,它的语言环境
Cache-Control: 缓存控制
Connection: 告诉浏览器,请求是断开还是保持连接
Refresh:告诉客户端,多久刷新一次
Location:让网页重新定位

2、响应状态吗

200:请求响应成功

3XX:请求重定向

  • 重定向:你重新到给你的新位置去

4XX:找不到资源 404

  • 资源不存在

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

常见面试题:

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

5、Servlet

5.1 Servlet简介

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

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

5.2 HelloServlet

Servlet接口Sun公司有两个默认的实现类:HTTPServlet、GenericServlet

1.构建一个普通的Maven项目,删掉里面的src目录,以后我们学习就在这个项目里建立Module;这个空的工程就是Maven的主工程;

2.关于Maven父子工程的理解:

​ 父项目中会有

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

子项目中会有

    <parent>
        <artifactId>javaweb-02-servlet</artifactId>
        <groupId>com.kuang</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

父项目中的jar包,子项目可以直接使用

3.Maven环境优化

  1. 修改web.xml为最新的

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                          http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0"
             metadata-complete="true">
    
    </web-app>
    
  2. 将maven的结构搭建完整

4.编写一个Servlet程序

1. 编写一个普通类

2. 实现Servlet接口,这里直接继承HTTPServlet
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("Hello,Servlet");
    }

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

在这里插入图片描述
5.编写Servlet的映射

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

    <!--注册Servlet-->
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.kuang.servlet.HelloServlet</servlet-class>
    </servlet>
    <!--Servlet的请求路径-->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

6.配置Tomcat

注意:配置项目发布的路径就可以了

7.启动测试

5.3 Servlet原理

Servlet是由web服务器调用,web服务器在收到浏览器的请求之后,会:
在这里插入图片描述

5.4 Mapping

  1. 一个Servlet请求可以指定一个映射路径

        <!--Servlet的请求路径-->
        <!--localhost:8080/s1/hello-->
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    
  2. 一个Servlet请求可以指定多个映射路径

        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello2</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello3</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello4</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello5</url-pattern>
        </servlet-mapping>
    
  3. 一个Servlet请求可以指定通用映射路径

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

    此时,开启Tomcat会首先访问这个路径,而不是index.jsp

  5. 指定一些后缀或者前缀

        <!--Servlet的请求路径-->
        <!--可以自定义后缀实现请求映射
        注意点:*前面不能加项目映射的路径
        /*.jack  /hello/*.jack 将报错
        -->
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>*.jack</url-pattern>
        </servlet-mapping>
    
  6. 优先级问题

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

        <servlet>
            <servlet-name>error</servlet-name>
            <servlet-class>com.kuang.servlet.ErrorServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>error</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
    

5.5 ServletContext

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

  1. 共享数据

我在这个Servlet中保存的数据,可以在另外一个Servlet钟拿到;
在这里插入图片描述

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

        // this.getInitParameter();  初始化参数
        // this.getServletConfig();  Servlet配置
        // this.getServletConfig();  Servlet上下文
        ServletContext context = this.getServletContext();

        String username = "王讷"; // 数据
        context.setAttribute("username",username); // 将一个数据保存在了ServletContext中,名字为username,职位username;

        System.out.println("Heello");
    }
}
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("utf-8");
        resp.getWriter().print("名字:" + username);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.kuang.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>getc</servlet-name>
        <servlet-class>com.kuang.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getc</servlet-name>
        <url-pattern>/getc</url-pattern>
    </servlet-mapping>

测试访问结果

  1. 获取初始化参数
    <!--配置一些web应用初始化参数-->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
    </context-param>
	@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();

        String url = context.getInitParameter("url");
        resp.getWriter().print(url);
    }
  1. 请求转发
    在这里插入图片描述
 @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        System.out.println("进入了ServletDemo04");

//        RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp"); // 转发的请求路径
//        requestDispatcher.forward(req,resp); // 调用forward方法实现请求转发
        context.getRequestDispatcher("/gp").forward(req,resp);
    }
  1. 读取资源文件

Properties

  • 在java目录下新建properties
  • 在resources目录下新建properties

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

思路:需要一个文件流

username=root
password=123456
public class ServletDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/kuang/servlet/aa.properties");
        Properties prop = new Properties();
        prop.load(is);
        String user = prop.getProperty("username");
        String pwd = prop.getProperty("password");

        resp.getWriter().print(user + ":" + pwd);
    }

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

当在java目录下新建properties时,难以导出,maven由于他的约定大于配置,导致写的配置文件无法被导出或者生效,此问题的解决方案如下:

<build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
</build>

访问测试即可!

5.6 HttpServletResponse

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

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

1、简单分类

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

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

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

public void setCharacterEncoding(String charset);
public void setContentLength(int len);
public void setContentLengthLong(long len);
public void setContentType(String type);
public void setDateHeader(String name, long date);
public void setHeader(String name, String value);
public void setIntHeader(String name, int value);
public void setStatus(int sc);

响应的状态码

	public static final int SC_CONTINUE = 100; 
    public static final int SC_SWITCHING_PROTOCOLS = 101;
    public static final int SC_OK = 200;
    public static final int SC_CREATED = 201;
    public static final int SC_ACCEPTED = 202;
    public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;
    public static final int SC_NO_CONTENT = 204;
    public static final int SC_RESET_CONTENT = 205
    public static final int SC_PARTIAL_CONTENT = 206;
    public static final int SC_MULTIPLE_CHOICES = 300;
    public static final int SC_MOVED_PERMANENTLY = 301;
    public static final int SC_MOVED_TEMPORARILY = 302;
    public static final int SC_FOUND = 302;
    public static final int SC_SEE_OTHER = 303;
    public static final int SC_NOT_MODIFIED = 304;
    public static final int SC_USE_PROXY = 305;
    public static final int SC_TEMPORARY_REDIRECT = 307;
    public static final int SC_BAD_REQUEST = 400;
    public static final int SC_UNAUTHORIZED = 401;
    public static final int SC_PAYMENT_REQUIRED = 402;
    public static final int SC_FORBIDDEN = 403;
    public static final int SC_NOT_FOUND = 404;
    public static final int SC_METHOD_NOT_ALLOWED = 405;
    public static final int SC_NOT_ACCEPTABLE = 406;
    public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
    public static final int SC_REQUEST_TIMEOUT = 408;
    public static final int SC_CONFLICT = 409;
    public static final int SC_GONE = 410;
    public static final int SC_LENGTH_REQUIRED = 411;
    public static final int SC_PRECONDITION_FAILED = 412;
    public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413;
    public static final int SC_REQUEST_URI_TOO_LONG = 414;
    public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
    public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    public static final int SC_EXPECTATION_FAILED = 417;
    public static final int SC_INTERNAL_SERVER_ERROR = 500;
    public static final int SC_NOT_IMPLEMENTED = 501;
    public static final int SC_BAD_GATEWAY = 502;
    public static final int SC_SERVICE_UNAVAILABLE = 503;
    public static final int SC_GATEWAY_TIMEOUT = 504;
    public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;

2、下载文件

  1. 向浏览器输出消息
  2. 下载文件
    1. 要获取下载文件的路径
    2. 下载的文件名?
    3. 设置让浏览器能够支持下载需要的东西
    4. 获取下载文件的输入流
    5. 创建缓冲区
    6. 获取OutputStream对象
    7. 将FileOutputStream流写入到buffer缓冲区
    8. 使用OutputStream将缓冲区中的数据输出到客户端
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.  要获取下载文件的路径
//        String realPath = this.getServletContext().getRealPath("/二哈.jpg");
        String realPath = "D:\\IdeaProjects\\javaweb-02-servlet\\response\\target\\response\\WEB-INF\\classes\\二哈.jpg";
        System.out.println("下载文件的路径:" + realPath);
        //2. 下载的文件名是什么?
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        //3. 设置想办法让浏览器能够支持(content-disposition)下载我们需要的东西
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        //4. 获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);
        //5. 创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //6. 获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        //7. 将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端
        while ((len=in.read(buffer)) > 0) {
            out.write(buffer,0,len);
        }
        in.close();
        out.close();
    }

3、验证码功能

验证码怎么来的?

  • 前端实现
  • 后端实现,需要用到java图片类,生成一个图片。
public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 如何让浏览器5秒自动刷新一次?
        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(makeNum(),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 makeNum() {
        Random random = new Random();
        String num = random.nextInt(9999999) + "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 7 - num.length(); i++) {
            sb.append("0");
        }
        num = sb.toString() + num;
        return num;
    }

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

在这里插入图片描述

4、实现重定向

在这里插入图片描述
(B)一个web资源受到客户端(A)请求后,(B)他会通知客户端(A)去访问另一个web资源©,这个过程叫做重定向。

常见场景:

  • 用户登录
public void sendRedirect(String location) throws IOException;
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, 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);
        // 重定向的时候一定要注意路径问题,否则404
        resp.sendRedirect("/r/success.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
    <servlet>
        <servlet-name>request</servlet-name>
        <servlet-class>com.kuang.servlet.RequestTest</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>request</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
<html>
<body>
<h2>Hello World!</h2>

<%--这里提交的路径,需要寻找到项目的路径--%>
<%--${pageContext.request.contextPath} 代表当前项目,推荐写法--%>
<form action="${pageContext.request.contextPath}/login" method="get">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit">
</form>

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

5.7 HttpServletRequest

HttpServletRequest代表客户端的请求,用户通过HTTP协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest中,通过这个HttpServletRequest的方法,获得客户端的所有信息。
在这里插入图片描述

获取参数,请求转发

在这里插入图片描述

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("===============================================");

        // 通过请求转发
        // 这里的 / 代表当前的web应用 req.getContextPath() +
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }

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

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<h1>登录</h1>
<div>
    <%--这里表单的意思是:以post方式提交表单,提交到我们的login请求--%>
    <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>

请你聊聊重定向和转发的区别?

相同点:

  • 页面都会跳转

不同点:

  • 请求转发时,url不会发生变化 307
  • 重定向时,url地址栏会发生变化 302
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值