目录
1. Servlet简介
狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,这里指广义的Servlet。使用者可以通过Servlet实现网址定向,向前端返回数据。创建的类通过继承HttpServlet类,实现其方法来使用。
Httpservlet类又继承自GenericServlet类,GenericServlet类实现了Servlet, ServletConfig, Serializable三个接口。
2. 实现一个简单Servlet的基本步骤
环境 | 版本 |
---|---|
IDEA | 2017.3.1 |
Maven | 3.5.2 |
tomcat | 9.0.56 |
2.1 创建简单Web工程
建议先创建一个空的Web工程,再在其下创建webapp子模块,具体模块如图:
具体pom文档配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.songhc</groupId>
<artifactId>javaweb-02-servlet</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>servlet-01</module>
<module>servlet-02</module>
<module>response</module>
</modules>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
</project>
具体Web工程结构如下,在main下创建java和resources文件夹,并标记:
2.2 创建Servlet类
在java文件夹下新建类,并继承HttpServlet类,主要覆盖doGet()和doPost()两个方法,注意其中一个用另外一个实现,简单代码如下:
package com.songhc.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet{
//由于get和post只是请求的两种不同方式,逻辑都一样,可以相互调用
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入doGet方法。");
//响应的类型
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();//响应流
writer.println("Hello Servlet!\n");
writer.println("我是Servlet!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.3 配置web.xml文件
配置src/webapp/WEB-INF/web.xml文件,需要配置< servlet >和< servlet-mapping >标签,前者定义映射,后者配置访问路径,通常访问路径以.do结尾,具体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_3_1.xsd"
version="3.1"
metadata-complete="true">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.songhc.servlet.HelloServlet</servlet-class>
</servlet>
<!--http://localhost:8080/servlet-02/hello/hello-->
<!-- 默认通配符 * -->
<!-- /* 可以自定义前缀实现请求映射-->
<!-- *.do 可以自定义后缀实现请求映射,注意*前面不能加路径,访问时也不校验前面的路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<!--ErrorServlet-->
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>com.songhc.servlet.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
2.4 配置tomcat服务器
完成以上三步之后,进入左上角Tomcat的Edit Configurations,配置tomcat服务器,具体步骤如下图,6是显示的服务器路径,譬如http://localhost:8080/response/hello,最后点击左上角Tomcat 9右侧的绿色启动键,即可启动Tomcat服务。
2.5 tomcat启动失败(1099 is already in use)
附一个 Address localhost:1099 is already in use报错的解决方案,找到占用该端口号的进程并结束后重启Tomcat
1.打开dos命令行,输入netstat -ano | find “1099”,找到占用当前端口的进程的PID
2.通过PID找到进程,输入:tasklist | find “9280”(双引号里面的是PID)
3.关闭这个进程,taskkill /f /t /im java.exe
3. ServletContext对象应用
ServletContext可以理解为所有继承了HttpServlet的类共用的一个对象,web容器在启动时,会为每个web程序创建ServletContext,它代表了当前的web应用,一般通过this.getServletContext()获取
3.1 数据共享
继承了HttpServlet的类之间可以通过ServletContext对象实现数据共享。
com/songhc/servlet/HelloServlet.java中的doGet方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String str = "<h3>我是从HelloServlet来的!</h3>";
context.setAttribute("str",str);//名字是str,值是str对象
System.out.println("Hello!");
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.print("<h3>我是Servlet!</h3>");
}
com/songhc/servlet/GetServlet.java中的doGet方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
Object o = context.getAttribute("str");
String str = String.valueOf(o);
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.print("文本:" + str);
}
注意必须先访问hello,向ServletContext中放置数据,再访问get,从ServletContext中取出数据,否则会返回null值。访问结果如下图:
3.2 初始化参数
3.2.1 web.xml
通过标签,设置参数的name和value
javaweb-02-servlet\servlet-02\src\main\webapp\WEB-INF\web.xml
<!--配置一些web应用初始化参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
3.2.2 Servlet
在代码中通过context对象的getInitParameter(“name”)方法返回参数的value值。
javaweb-02-servlet\servlet-02\src\main\java\com\songhc\servlet\ServletDemo03.java
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().print(url);
}
实现效果如下:
3.3 请求转发
通过ServletContext对象的RequestDispatcher对象的forward(req,resp)方法实现请求的转发
javaweb-02-servlet\servlet-02\src\main\java\com\songhc\servlet\ServletDemo04.java
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
// RequestDispatcher dispatcher = context.getRequestDispatcher("/gp");//转发的请求路径
// dispatcher.forward(req,resp);//调用forward转发请求
System.out.println("进入了ServletDemo04。");
context.getRequestDispatcher("/gp").forward(req,resp);
resp.setContentType("text/html;charset=utf-8");
}
javaweb-02-servlet\servlet-02\src\main\webapp\WEB-INF\web.xml
<servlet>
<servlet-name>gp</servlet-name>
<servlet-class>com.songhc.servlet.ServletDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gp</servlet-name>
<url-pattern>/gp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>sd4</servlet-name>
<servlet-class>com.songhc.servlet.ServletDemo04</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd4</servlet-name>
<url-pattern>/sd4</url-pattern>
</servlet-mapping>
实现效果:
3.3 读取资源文件
读取资源文件重点在编译后的文件的相对路径
3.3.1 打包过滤设置
在模块的pom.xml设置打包过滤
javaweb-02-servlet\servlet-02\pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>javaweb-02-servlet</artifactId>
<groupId>com.songhc</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>servlet-02</artifactId>
<packaging>war</packaging>
<!--创建设置,都被打包到了classess,俗称classpath-->
<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>
</project>
3.3.2 创建资源文件
一般在resources文件夹下创建,修改pom后在java文件夹下创建也可打包
javaweb-02-servlet\servlet-02\src\main\java\com\songhc\servlet\test.properties
文件目录结构:
3.3.3 读取资源文件
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream inputStream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/songhc/servlet/test.properties");
Properties prop = new Properties();
prop.load(inputStream);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.println(username);
writer.println(password);
}
4. 下篇内容
HttpServletResponse和HttpServletRequest