狂神说Java Web学习笔记_Servlet

Servlet

简介

Servlet是sun公司开发的动态web的一门技术。提供的其中一个接口叫Servlet。把实现了Servlet接口的Java程序叫Servlet。

HelloServlet

Servlet在Sun公司有两个默认实现类,HttpServlet,GenericServlet。

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HelloServlet extends javax.servlet.http.HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        PrintWriter writer = resp.getWriter();
        writer.print("Hello Servlet");
    }
}
<?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">

  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>helloServlet</servlet-name>
    <servlet-class>com.dawn.HelloServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>helloServlet</servlet-name>
    <url-pattern>/helloServlet</url-pattern>
  </servlet-mapping>
</web-app>

通过http://localhost:8080/s01/helloServlet访问刚刚配置的servlet。

Servlet原理

ServletContext

共享数据

一个servlet可以读取其他Servlet写到Servlet的数据



import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HelloServlet extends javax.servlet.http.HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ServletContext servletContext = this.getServletContext();
        servletContext.setAttribute("name", "闹闹");

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("给ServletContext写入数据");
    }
}
import javax.servlet.ServletContext;
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 GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ServletContext servletContext = this.getServletContext();
        String name = (String) servletContext.getAttribute("name");

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println("名字:" + name);
    }
}
<?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">

    <display-name>Archetype Created Web Application</display-name>

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


    <servlet>
        <servlet-name>getparam</servlet-name>
        <servlet-class>com.dawn.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getparam</servlet-name>
        <url-pattern>/getparam</url-pattern>
    </servlet-mapping>
</web-app>

调用/hello存入值

调用/getparam获取上面存入的值

获取初始化参数

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class GetInitParamServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ServletContext servletContext = this.getServletContext();
        String hobby = servletContext.getInitParameter("hobby");

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("获取到的初始化参数hobby的值为:" + hobby);
    }
}
<servlet>
    <servlet-name>getInitParam</servlet-name>
    <servlet-class>com.dawn.servlet.GetInitParamServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>getInitParam</servlet-name>
    <url-pattern>/getInitParam</url-pattern>
</servlet-mapping>

请求转发

访问的是/dispatch路径,但是转发到了/getInitParam。url上地址不变,但是内容显示改变了,这种叫转发。

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

public class DispatchServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        servletContext.getRequestDispatcher("/getInitParam").forward(req, resp);
    }
}
<servlet>
    <servlet-name>dispatch</servlet-name>
    <servlet-class>com.dawn.servlet.DispatchServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>dispatch</servlet-name>
    <url-pattern>/dispatch</url-pattern>
</servlet-mapping>

读取配置文件

import javax.servlet.ServletContext;
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.io.InputStream;
import java.util.Properties;

public class ReadPropertiesServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        InputStream resourceAsStream = servletContext.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().print("读取配置文件结束,读取到的信息如下。用户名:" + username + ", 密码:" + password);
    }
}

配置文件路径

<servlet>
    <servlet-name>readProperties</servlet-name>
    <servlet-class>com.dawn.servlet.ReadPropertiesServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>readProperties</servlet-name>
    <url-pattern>/readProperties</url-pattern>
</servlet-mapping>

HttpServletResponse

常见应用

下载文件

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.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        URL resource = getClass().getClassLoader().getResource("test.jpg");
        String path = resource.getPath();

        String fileName = path.substring(path.lastIndexOf("/") + 1);
        System.out.println(fileName);

        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        FileInputStream fileInputStream = new FileInputStream(new File(path));
        int bytesRead;
        byte[] buffer = new byte[1024];
        ServletOutputStream outputStream = resp.getOutputStream();
        while ((bytesRead = fileInputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, bytesRead);
        }

        fileInputStream.close();
        outputStream.close();
    }
}

<servlet>
    <servlet-name>downloadfile</servlet-name>
    <servlet-class>com.dawn.response.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>downloadfile</servlet-name>
    <url-pattern>/downloadfile</url-pattern>
</servlet-mapping>

实现重定向功能

刚开始的路径是/redirect

重定向之后的路径变了

HttpServletRequest

功能:获取前台传入的参数,请求转发

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/login" method="post">
    用户名:<input type="text" name="userName"> <br>
    密码:<input type="password" name="password"> <br>

    爱好:
    <input type="checkbox" name="hobby" value="跑步">跑步
    <input type="checkbox" name="hobby" value="阅读">阅读
    <input type="checkbox" name="hobby" value="编程">编程
    <input type="checkbox" name="hobby" value="听音乐">听音乐
    <input type="checkbox" name="hobby" value="爬山">爬山
    <br>

    <input type="submit" value="提交">
</form>
</body>
</html>
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[] hobbies = req.getParameterValues("hobby");

        System.out.println("用户名:" + userName);
        System.out.println("密码:" + password);
        System.out.println("爱好:" + Arrays.toString(hobbies));

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

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
<?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">

    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>com.dawn.request.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
</web-app>

请求转发路径不变

控制台输出刚开始一直乱码,后来是下面这样解决的
-Dfile.encoding=utf-8

posted @ 2024-04-09 08:46  growingbambi  阅读(17)  评论(0编辑  收藏  举报