狂神说JavaJavaWeb入门到实战--Servlet详解
Posted 闲言_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了狂神说JavaJavaWeb入门到实战--Servlet详解相关的知识,希望对你有一定的参考价值。
目录
狂神视频地址
1.Servlet 简介
Servlet 就是sun公司开发动态web的一门技术
sun 在这些API 中提供了一个接口:Servlet,如果你想开发一个Servlet 程序,只需要完成两个步骤
- 编写一个类,实现Servlet 接口
- 把开发号好的Java类部署到服务器中
把实现了Servlet接口的Java 程序叫做:Servlet
2.HelloServlet
Servlet 接口有两个默认的实现类:HttpServlet、GenericServlet
关于mavne 父子工程的理解
父项目中会有
<modules>
<module>servlet-01</module>
</modules>
子项目中会有
<parent>
<artifactId>servlet</artifactId>
<groupId>cn.bloghut</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
父项目中的jar包 子项目可以直接使用
子项目中的jar包 父项目不能使用
Zi extends Fu
编写一个普通类,实现Servlet接口,这里我们直接继承httpServlet
public class HelloServlet extends HttpServlet {
}
public class HelloServlet extends HttpServlet {
//由于get或者post只是请求实现的不同的方法,可以相互调用,业务逻辑都一样
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// ServletOutputStream sos = resp.getOutputStream();
PrintWriter writer = resp.getWriter();//响应流
writer.println("hello,Servlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
3.编写Servlet的映射
为什么需要映射:我们写的Java程序,但是要通过浏览访问,而浏览器需要连接web服务器,所以我们需要在web服务中注册我们写的Servlet,还需要给他一个浏览器能够访问的路径。
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>cn.bloghut.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
配置tomcat
测试
4.Servlet 原理
Servlet 是由web服务器调用,web服务器在收到浏览器请求之后,会调用相关API对请求处理。
5.Mapping 问题:
一个请求(Servlet)可以指定一个映射路径
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>cn.bloghut.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
一个请求(Servlet)可以指定多个映射路径
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>cn.bloghut.servlet.HelloServlet</servlet-class>
</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>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello3</url-pattern>
</servlet-mapping>
一个请求(Servlet)可以指定通用映射路径
<!--默认请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
指定一些后缀或者前缀等
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
优先级问题
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求;
6.ServletContext
web容器在启动的时候,它会为每个web程序都创建一个ServletContext对象,它代表了当前的web应用。
6.1.共享数据
我在这个Servlet中保存的数据
放置数据的Servlet
/**
* @author by 闲言
* @classname HelloServlet
* @description 放置数据
* @date 2021/9/11 14:23
*/
public class setData extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("hello");
ServletContext servletContext = this.getServletContext();
String username = "闲言";//数据
servletContext.setAttribute("username",username);//将一个数据保存在ServletContext中 名为:username 值为 闲言
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
读取数据的Servlet
/**
* @author by 闲言
* @classname GetServlet
* @description 获取数据
* @date 2021/9/16 21:32
*/
public class GetData extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = (String) context.getAttribute("username");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.write(username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
6.2获取初始化参数
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/school</param-value>
</context-param>
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");
System.out.println("url: "+url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
6.3 请求转发
路径不会发生变化
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
//请求转发 /get 转发的路径
RequestDispatcher dispatcher = context.getRequestDispatcher("/get");
//调用forward 实现请求转发
dispatcher.forward(req,resp);
}
6.4 读取配置文件
Properties
在resources 目录下新建properties
在java 目录下新建properties
发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath;
思路:需要一个文件流
properties文件
username=xy123
password=123
代码
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream stream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/cn/bloghut/servlet/aa.properties");
// InputStream stream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties pt = new Properties();
pt.load(stream);
String username = pt.getProperty("username");
String password = pt.getProperty("password");
resp.getWriter().println(username+":"+password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
效果
maven资源导出失败问题
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
6.5HttpServletResponse
web服务器接收到客户端的http请求,会针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletRespoonse;
- 如果要获取客户端请求过来的参数:找HttpServletRequest
- 如果要给客户端响应一些信息:找HttpServletResponse
简单分类
负责向浏览器发送数据的方法
public ServletOutputStream getOutputStream() throws IOException;
public PrintWriter getWriter() throws IOException;
负责向浏览器写一些响应头的方法
public void setCharacterEncoding(String charset);
public void setContentLength(int len);
public void setContentLengthLong(long len);
public void setContentType(String type);
public void setDateHeader(String name, long date);
public void addDateHeader(String name, long date);
public void setHeader(String name, String value);
public void addHeader(String name, String value);
public void setIntHeader(String name, int value);
public void addIntHeader(String name, int value);
响应的状态码常量
public static final int SC_CONTINUE = 100;
public static final int SC_SWITCHING_PROTOCOLS = 101;
public static final int SC_OK = 200;
public static final int SC_CREATED = 201;
public static final int SC_ACCEPTED = 202;
public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;
public static final int SC_NO_CONTENT = 204;
public static final int SC_RESET_CONTENT = 205;
public static final int SC_PARTIAL_CONTENT = 206;
public static final int SC_MULTIPLE_CHOICES = 300;
public static final int SC_MOVED_PERMANENTLY = 301;
public static final int SC_MOVED_TEMPORARILY = 302;
public static final int SC_FOUND = 302;
public static final int SC_SEE_OTHER = 303;
public static final int SC_NOT_MODIFIED = 304;
public static final int SC_USE_PROXY = 305;
public static final int SC_TEMPORARY_REDIRECT = 307;
public static final int SC_BAD_REQUEST = 400;
public static final int SC_UNAUTHORIZED = 401;
public static final int SC_PAYMENT_REQUIRED = 402;
public static final int SC_FORBIDDEN = 403;
public static final int SC_NOT_FOUND = 404;
public static final int SC_METHOD_NOT_ALLOWED = 405;
public static final int SC_NOT_ACCEPTABLE = 406;
public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
public static final int SC_REQUEST_TIMEOUT = 408;
public static final int SC_CONFLICT = 409;
public static final int SC_GONE = 410;
public static final int SC_LENGTH_REQUIRED = 411;
public static final int SC_PRECONDITION_FAILED = 412;
public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413;
public static final int SC_REQUEST_URI_TOO_LONG = 414;
public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
public static final int SC_EXPECTATION_FAILED = 417;
public static final int SC_INTERNAL_SERVER_ERROR = 500;
public static final int SC_NOT_IMPLEMENTED = 501;
public static final int SC_BAD_GATEWAY = 502;
public static final int SC_SERVICE_UNAVAILABLE = 503;
public static final int SC_GATEWAY_TIMEOUT = 504;
public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
下载文件
1.向浏览器输出消息
2.下载文件
2.1.要获取文件的路径
2.2下载的文件名是啥
2.3设置想办法让浏览器能够支持下载我们需要的东西
2.4获取下载文件的输入流
2.创建缓冲区
2.5获取OutputStream对象
2.6将FileOutputStream流写入到buff缓冲区
2.7使用OutputStream将缓冲区中的数据输出到客户端!
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//要获取文件的路径
// String realPath = this.getServletContext().getRealPath("/1.png");
String realPath = 以上是关于狂神说JavaJavaWeb入门到实战--Servlet详解的主要内容,如果未能解决你的问题,请参考以下文章