Servlet

1. Servlet简介

  • Servlet是开发动态web的技术,何为动态?每个人访问可以看到不同的页面。

  • Sun公司提供了接口:Servlet,因此开发Servlet程序,只需要两个步骤:

    • 编写一个类,继承Servlet接口;
    • 把开发好的java程序部署到web服务器中

    实现了Servlet接口的程序,称为Servlet,一般创建名位Servlet的包。

2. HelloServlet

HttpServlet -> GenericServlet -> Servlet

  1. 编写一个类,继承HttpServlet类

    public class servlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            PrintWriter writer = resp.getWriter();
            writer.println("hello servlet");
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  2. 编写Servlet的映射

    为何需要映射?我们写的是java程序,但是需要通过浏览器访问,而浏览器需要连接web服务器,因此需要在web服务器中注册Servlet

    <!--给servlet定义一个名字-->
    <servlet>
      <servlet-name>hello</servlet-name>
      <servlet-class>com.yang.servlet</servlet-class>
    </servlet>
    <!--给servlet映射接口-->
    <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    

3. Tomcat的配置

Idea中tomcat的使用

image-20210125153939752

  • update resources:只更新了html / css / js / jsp后,可以使用这个刷新;
  • update classes and resources:修改java代码后,在调试模式下可以使用该选项刷新,但运行状态不可;
  • redeploy:修改java代码后,使用该选项刷新;
  • restart server:修改了配置文件,比如web.xml,需要重启tomcat服务。

若是不更改为4.0版本,jsp中内置对象无法解析。

<?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">
  1. 第一步

    image-20210113164222449

  2. 第二步

    image-20210113164319067

  3. 第三步

    image-20210113164349321

  4. 第四步

    image-20210113164540978

  5. 第五步

    image-20210113164652488

4. Servlet原理

  • 浏览器向Web服务器发送Http请求;
  • web服务器产生两个对象:Request和Response;
  • 首次访问,将两个对象传给Servlet处理,返回给Web容器;
  • Web容器读取响应的信息;

我们所需要做的就是重写Servlet,接受处理请求,返回相应的信息。

5. Web服务器Mapping

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

    <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>/hello1</url-pattern>
    </servlet-mapping>
    
    <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/hello2</url-pattern>
    </servlet-mapping>
    
  3. 一个Servlet可以指定通用映射路径(使用通配符*)

    <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/*</url-pattern>
    </servlet-mapping>
    
  4. Servlet可以自定义后缀实现请求映射**(前不能加/)*

    <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    
  5. 优先级问题:指定了固有路径的优先级最高,找不到才会走通用页面

6. ServletContext

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

6.1 共享web数据

在一个Servlet中保存的数据,可以在另一个Servlet中拿到

// servlet1:在context设置了一对值
public class Servlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        context.setAttribute("username", "洋洋");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
// servlet2:获取servlet1设置的值
public class Servlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        Object username = context.getAttribute("username");

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println(username);
    }

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

防止返回的数据中文乱码

    resp.setContentType("text/html");
    resp.setCharacterEncoding("utf-8");

6.2 获取初始化参数

可以获取web.xml中配置的初始参数

<context-param>
  <param-name>url</param-name>
  <param-value>jdbc:mysql://localhost:3306/smbms</param-value>
</context-param>
public class ServletGetParams 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);
    }

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

6.3 请求转发

不是重定向,而是将请求转给其他servlet处理,获取到结果显示出来,路径没有变化

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

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

6.4 读取配置文件

注意context.getResourceAsStream("/WEB-INF/classes/db.properties");路径是以生成的target目录下项目为根路径

public class ServletGetResources extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        InputStream resourceAsStream = context.getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties properties = new Properties();
        properties.load(resourceAsStream);
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().println(username);
        resp.getWriter().println(password);
    }

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

7. HttpServletResponse

7.1 简单分类

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

7.2 下载文件

7.3 验证码功能

7.4 实现重定向

重定向的路径需要写完整的路径(包含项目名称)

public class ServletRedirect extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/servlet/s5");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值