JavaWeb | Servlet基础

1.Servlet简介

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

按照约定俗成的称呼习惯,把实现了Servlet接口的Java程序叫做Servlet

2 Servlet实现类

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

  • HttpServlet指能够处理HTTP请求的servlet,它在原有Servlet接口上添加了一些与HTTP协议处理方法,它比Servlet接口的功能更为强大,因此开发人员在编写Servlet时,通常应继承这个类,而避免直接去实现Servlet接口

  • HttpServlet在实现Servlet接口时,覆写了service方法,该方法体内的代码会自动判断用户的请求方式,如为GET请求,则调用HttpServlet的doGet方法,如为Post请求,则调用doPost方法,因此,开发人员在编写Servlet时,通常只需要覆写doGet或doPost方法,而不要去覆写service方法

3 Servlet的创建(HelloServlet)

  1. 构建一个普通的Maven项目(不勾选webapp),删掉里面的src目录,以后我们的学习就在这个项目里面建立Moudel;这个空的工程就是Maven主工程;
    在这里插入图片描述
  2. 在主项目的pox文件中,添加所有子项目所需要的依赖,这样所有子项目可以直接使用这些jar包而不必反复导入。
    Servlet需要使用以下两个依赖:
 <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
            <scope>provided</scope>
        </dependency>
  1. 在父项目中,新建一个子模块(new->Moudel),创建Maven的webapp项目,然后对Maven环境进行优化:1.修改web.xml为最新的;2.将maven的结构搭建完整

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>

完整的maven结构:
在这里插入图片描述

  1. 关于Maven父子工程的理解

父项目中会有:

<modules>
        <module>demo1</module>
    </modules>

子项目会有:

<parent>
        <artifactId>javaweb-servlet</artifactId>
        <groupId>com.young</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
  1. 编写一个普通类,实现Servlet接口,这里我们直接继承HttpServlet.

说明:重新方法时,由于get或者post只是请求实现的不同的方式,可以相互调用,因为其业务逻辑都一样;

public class HelloServlet extends HttpServlet {
    @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 {
        doGet(req, resp);
    }
}
  1. HttpServlet接口的分析
    HttpServlet接口的继承关系如下图所示,我们只需要继承HttpServlet,重写需要的方法即可 。在这里插入图片描述

  2. 编写Servlet的映射
    写映射的原因:我们写的是JAVA程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以需要在web服务中注册(在web.xml文件中)我们写的Servlet,还需给他一个浏览器能够访问的路径。

 <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>com.young.HelloServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>//浏览器能够访问的路径
  1. 配置Tomcat

  2. 启动测试

在这里插入图片描述

4 Servlet原理

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

5 Mapping问题

  1. 一个Servlet可以指定一个映射路径
    访问网址:http://localhost:8080/young/hello

        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    
  2. 一个Servlet可以指定多个映射路径
    访问网址:http://localhost:8080/young/hello
    访问网址:http://localhost:8080/young/hello2
    访问网址:http://localhost:8080/young/hello3
    访问网址:http://localhost:8080/young/hello4
    访问网址:http://localhost:8080/young/hello5

        <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可以指定通用映射路径
    访问网址:http://localhost:8080/young/hello/*

        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello/*</url-pattern>
        </servlet-mapping>
    
  4. 默认请求路径
    访问网址:http://localhost:8080/young/*

        <!--默认请求路径-->
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
    
  5. 指定一些后缀或者前缀
    注意:* 前面不能加项目映射的路径,即不能写/.young,要写.young
    访问网址:http://localhost:8080/young/sfkaffsdfdsf.young

    <!--可以自定义后缀实现请求映射
        注意点,*前面不能加项目映射的路径,即不能写/*.young
        -->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>*.young</url-pattern>
    </servlet-mapping>
    
  6. 优先级问题
    指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求;

    <!--404-->
    <servlet>
        <servlet-name>error</servlet-name>
        <servlet-class>com.young.servlet.ErrorServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>error</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    
    

6 ServletContext

web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用。一个Web应用中的所有的Servlet共用一份ServletContext对象。
在这里插入图片描述

6.1 共享数据

在一个Servlet中保存的数据,可以在另外一个servlet中拿到,基于这个原理我们可以共享数据

PutServlet代码:

public class PutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String username="young";
        context.setAttribute("username",username);// //将一个数据保存在了ServletContext中,名字为:username ,值是young。
    }

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

GetServlet代码:

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:"+username);
    }

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

测试:

  1. 访问get页面
    在这里插入图片描述
  2. 访问put页面
    在这里插入图片描述
  3. 访问get页面
    在这里插入图片描述

6.2 获取初始化参数

  1. 在web.xml中设置初始化参数
  <!--配置一些web应用初始化参数-->
  <context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/mydb</param-value>
  </context-param>
  1. 获取初始化参数
public class IniParaServlet 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 {
        doGet(req, resp);
    }
}
  1. 测试

在这里插入图片描述

6.3 请求转发

访问http://localhost:8080/young/Dispatcher,转发到http://localhost:8080/young/hello页面

public class DispatcherServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        context.getRequestDispatcher("/hello").forward(req,resp);
    }

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

测试:
在这里插入图片描述

6.4 转发与重定向的区别:

如下图所示,转发时的访问的页面仍然是页面B;而重定向访问的页面是页面C。
在这里插入图片描述

6.5 读取资源文件

  • 在java目录下新建db2.properties
  • 在resources目录下新建db.properties
    在这里插入图片描述
    如果不做任何处理,可以发现只有resources目录下新建的db.properties在target文件中生成对应的文件,而在java目录下新建db2.properties没有生成对应的文件。

解决办法:在build中配置resources,来防止我们资源导出失败的问题

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

在这里插入图片描述

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

读取资源文件的java代码:

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

测试:
在这里插入图片描述

7 HttpServletResponse

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

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

7.1 HttpServletResponse方法的简单分类

注:下面的这些方法即包括HttpServletResponse中的方法,也包括其父类ServletResponse中的方法。

  1. 负责向浏览器发送数据的方法
ServletOutputStream getOutputStream() throws IOException;   //字节流
PrintWriter getWriter() throws IOException;                 //字符流
  1. 负责向浏览器发送响应头的方法
	void setCharacterEncoding(String var1);
    void setContentLength(int var1);
    void setContentLengthLong(long var1);
    void setContentType(String var1);
    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);
  1. 响应的状态码
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;

7.2 下载文件

下载文件的步骤:

  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="E:\\研究生\\浮生小趣\\JAVE\\6.JavaWeb\\4.mycode\\javaweb-servlet\\response\\src\\main\\resources\\小羊.png";

//2. 下载的文件名
        String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);

//3. 设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名URLEncoder.encode编码,否则有可能乱码
        resp.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename,"utf-8"));
//4. 获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);

//5. 创建缓冲区
        int len = 0;
        byte[] bytes = new byte[1024];

//6. 获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();

//7. 将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端!
        while ((len=in.read(bytes))>0){
            out.write(bytes,0,len);
        }

        in.close();
        out.close();

    }

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

输入测试网址:localhost:8080/down
在这里插入图片描述

7.3 验证码功能

代码:

public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //定时刷新
        resp.setHeader("refresh","2");
        //创建一个图片
        BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
        //得到图片,获得一个画笔
        Graphics2D graphics = (Graphics2D) image.getGraphics();

        //设置背景颜色
        graphics.setColor(Color.green);
        graphics.fillRect(0,0,80,20);

        //给图片写内容
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(null,Font.BOLD,15));
        graphics.drawString(randomNum(),10,15);

        //以图片方式打开
        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 randomNum() {
        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);
    }
}

测试网址:http://localhost:8080/image
在这里插入图片描述

在这里插入图片描述

7.4 重定向

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

代码:

public class RedirectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/image");//重定向
    }

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

测试网址:http://localhost:8080/redirect

在这里插入图片描述

根据上图可知,重定向完成了以下几个功能:

 resp.setHeader("Locaton","/image");
 resp.setStatus(302);

自动跳转至image页面:
在这里插入图片描述

重定向的使用场景:用户登录跳转的页面

登录页面代码:

<html>
<body>
<h2>Hello World!</h2>

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

重定向控制页面:

public class LoginServlet 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("/LoginSuccess.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>
</head>
<body>
登录成功
</body>
</html>

测试:
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

8 HttpServletRequest应用

8.1 简介

HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息。
常用的两个获取参数的方法:

  • getParameter 返回一个String类型
  • getParameterValues 返回String[ ]的数组

8.2 案例

index.jsp

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

<div>
    <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="rap">rap
        <input type="checkbox" name="hobbys" value="篮球">篮球
        <br>
        <input type="submit">
    </form>
</div>

</body>
</html>

LoginServlet类:

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(username);
        System.out.println(password);
        System.out.println(Arrays.toString(hobbys));

        req.getRequestDispatcher("/LoginSuccess.jsp").forward(req,resp);

    }

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

LoginSuccess.jsp

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

测试:
在这里插入图片描述
点击提交,自动转发(还是login的页面,但是现实的loginSuccess的页面)

在这里插入图片描述

后台获得数据:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值