Loading

javaweb 4、Servlet

Servlet

Servlet简介

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

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

Hello Servlet

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

构建一个普通的Maven项目

  • 删掉里面的src项目
  • 创建servlet子项目

关于Maven父子工程的理解

父项目中会有

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

子项目中会有

<parent>
    <artifactId>javaweb-02-servleb</artifactId>
    <groupId>com.binzaza</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>

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

son extends father

Maven环境优化

  1. 更新web.xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                      https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0"
         metadata-complete="true">

</web-app>
  1. 创建java、resources文件夹(maven的结构搭建完整)

编写一个Serlet程序

  1. 编写一个普通类
    ../servlet-01/src/main/java/com.binzaza.servlet
    HelloServlet.java
public class HelloServlet extends HttpServlet {
}
  1. 实现Servlet接口,这里我们直接继承HttpServlet
public class HelloServlet extends HttpServlet {

    // 重新方法 Ctrl + O
    // 有GET、POST 只是请求实现的不同方式,可以相互调用,因为业务逻辑都一样

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        ServletOutputStream outputStream = resp.getOutputStream();
        PrintWriter writer = resp.getWriter(); // 响应流
        writer.print("hello Servlet");

    }

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

编写Servlet的映射

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

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                      https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0"
         metadata-complete="true">

    <!--注册servlet-->
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.binzaza.servlet.HelloServlet</servlet-class>
    </servlet>

    <!--servlet的请求路径-->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

</web-app>

配置tomcat

启动测试

默认:http://localhost:8080/s1/

访问映射路径:http://localhost:8080/s1/hello

Servlet原理

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

Mapping 问题

web.xml

  1. 一个servlet可以指定一个映射路径
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>
  1. 一个servlet可以指定多个映射路径
    <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>
    <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>
  1. 一个servlet可以指定通用映射路径
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello/*</url-pattern>
</servlet-mapping>
  1. 默认请求路径
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
  1. 指定一些后缀或者前缀等等
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>*.binzaza</url-pattern>
</servlet-mapping>

  1. 优先级问题

定义404

创建ErrorServlet.java

public class ErrorServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");

        PrintWriter writer = resp.getWriter();
        writer.print("<h1>我的404</h1>");
    }

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

配置映射
web.xml

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

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

ServletContext对象

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

  • 共享数据
    我在servlet中保存的数据,可以在另外一个servlet中拿到

在父项目javaweb-02-servlet下

父项目
pom.xml

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

子项目
pom.xml

<parent>
    <artifactId>javaweb-02-servleb</artifactId>
    <groupId>com.binzaza</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>

更新web.xml文件

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                      https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0"
         metadata-complete="true">
</web-app>

优化maven结构

建包,创建类
servlet-02/src/main/java/com.binzaz.servlet
创建HelloServlet.java

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 = "冰渣渣";
        context.setAttribute("username",username); // 将一个数据保存在了ServletContext中,名字为:username,值为username
    }
}

创建GetServlet.java

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

配置映射web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                      https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0"
         metadata-complete="true">
    <!--注册servlet-->
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.binzaza.servlet.HelloServlet</servlet-class>
    </servlet>

    <!--servlet的请求路径-->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>getc</servlet-name>
        <servlet-class>com.binzaza.servlet.GetServlet</servlet-class>
    </servlet>

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

</web-app>

启动tomcat

先访问:http://localhost:8080/s2/hello

再打开:http://localhost:8080/s2/getc

ServletContext应用

获取初始化参数

web.xml配置参数以及路由

<context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>

<servlet>
    <servlet-name>gp</servlet-name>
    <servlet-class>com.binzaza.servlet.ServletDemo03</servlet-class>
</servlet>

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

创建ServletDemo03.java

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 {
        doGet(req, resp);
    }
}

启动tomcat

访问:http://localhost:8080/s2/gp

Ctrl + [ 向前缩进, Ctrl + ] 向后缩进。

请求转发

public class ServletDemo04 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        System.out.println("进入了sd4页面");
//        RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp"); // 转发请求路径
//        requestDispatcher.forward(req,resp); // 调用forward实现请求转发
        context.getRequestDispatcher("/gp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
<servlet>
    <servlet-name>sd4</servlet-name>
    <servlet-class>com.binzaza.servlet.ServletDemo04</servlet-class>
</servlet>

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

读取资源文件

maven配置pom.xml的时候可能会出现的一个问题:资源可能无法导出,这时候需要在pom.xml的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>

Properties

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

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

在resource目录下建db.properties文件

username=root
password=123456

创建文件ServletDemo05.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/db.properties");
//        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/binzaza/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);
    }
}

启动tomcat
访问:http://localhost:8080/s2/sd5

posted @ 2022-11-16 17:20  Binzichen  阅读(16)  评论(0编辑  收藏  举报