javaweb之Servlet javaweb参考文献近三年
yuyutoo 2024-11-05 13:27 9 浏览 0 评论
Servlet,javaweb的基础之一。
主要作用是处理浏览器的请求。
- 接受请求 ServletRequest
- 处理请求 编码
- 响应请求 ServetResponse
Servlet接口:
public interface Servlet {
//生命周期方法,初始化,在Servlet对象创建后执行,仅执行一次
void init(ServletConfig var1) throws ServletException;
//获取Servlet配置信息
ServletConfig getServletConfig();
//生命周期方法,请求,处理,响应
void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
//获取Servlet信息
String getServletInfo();
//生命周期方法,对象销毁前执行,仅执行一次
void destroy();
}
GenericServlet抽象类:
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
//Servlet配置
private transient ServletConfig config;
//获取指定name初始参数value
public String getInitParameter(String name) {
return this.getServletConfig().getInitParameter(name);
}
//获取Servlet配置
public ServletConfig getServletConfig() {
return this.config;
}
//获取Servlet上下文
public ServletContext getServletContext() {
return this.getServletConfig().getServletContext();
}
//初始化,由Tomcat注入Servlet配置信息
public void init(ServletConfig config) throws ServletException {
this.config = config;
//调用本类方法
this.init();
}
//重点方法,自定义Servlet类写此方法,而不是上一方法
public void init() throws ServletException { }
//获取Servlet名称
public String getServletName() {
return this.config.getServletName();
}
}
HttpServlet对象
public abstract class HttpServlet extends GenericServlet {
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try {
//将请求和响应参数强制转为Http类型的请求和响应参数
request = (HttpServletRequest)req;
response = (HttpServletResponse)res;
} catch (ClassCastException var6) {
throw new ServletException(lStrings.getString("http.non_http"));
}
//调用本类的方法
this.service(request, response);
}
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求的方法类型,调用相应的本类方法
String method = req.getMethod();
long lastModified;
if (method.equals("GET")) {
lastModified = this.getLastModified(req);
if (lastModified == -1L) {
//doGet方法
this.doGet(req, resp);
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader("If-Modified-Since");
} catch (IllegalArgumentException var9) {
ifModifiedSince = -1L;
}
if (ifModifiedSince < lastModified / 1000L * 1000L) {
this.maybeSetLastModified(resp, lastModified);
this.doGet(req, resp);
} else {
resp.setStatus(304);
}
}
} else if (method.equals("HEAD")) {
lastModified = this.getLastModified(req);
this.maybeSetLastModified(resp, lastModified);
this.doHead(req, resp);
} else if (method.equals("POST")) {
//doGet方法
this.doPost(req, resp);
} else if (method.equals("PUT")) {
this.doPut(req, resp);
} else if (method.equals("DELETE")) {
this.doDelete(req, resp);
} else if (method.equals("OPTIONS")) {
this.doOptions(req, resp);
} else if (method.equals("TRACE")) {
this.doTrace(req, resp);
} else {
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[]{method};
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(501, errMsg);
}
}
//继承类重写的是此方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_get_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(405, msg);
} else {
resp.sendError(400, msg);
}
}
//继承类重写的是此方法
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(405, msg);
} else {
resp.sendError(400, msg);
}
}
自定义Servlet
@WebServlet(urlPatterns = {"/getmsg"},
//初始化参数设置
initParams = {@WebInitParam(name = "name1",value = "a",description = ""),
@WebInitParam(name = "name2",value = "b",description = "")})
public class MyServlet extends HttpServlet{
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//请求和响应编码设置
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=UTF-8");
//打印Servlet的pattern
System.out.println(req.getHttpServletMapping().getPattern());
//打印请求URL
System.out.println(req.getRequestURL().toString());
//打印初始化参数
resp.getWriter().print(getServletConfig().getInitParameter("name1"));
//响应
resp.getWriter().print("response");
}
@Override
public void init() throws ServletException {
System.out.println(getServletConfig().getServletName());
}
}
重点:
- 一般自定义Servlet继承HttpServlet即可,一般重写其中的init()、doGet()、doPost()方法;
- Servet是非线程安全的;
- @WebServlet中参数:loadOnStartUp默认-1,Servlet在第一次请求时才会创建,修改为非负值时为加载时创建并初始化,0优先级最高;
- 路径通配符:* ,*只能在首或者尾,不能在中间,例:/*(匹配所有请求) 、*.do(匹配do结尾的请求)、/servlet/* (匹配/servlet/后的所有请求),在请求优先级中,具体的urlPattern优先于通配符的;
- 需重写doGet或者doPost或者其他的方法中的一个或多个,否则浏览器报405错误;
- urlPattern必须以"/"开头;
- “/"请求默认的DefaultServlet,另默认index.html、index.htm、index.jsp;
- Servlet是单例模式,只在创建时加载一次;
- 编码设置:req.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=UTF-8");
Servlet案例:
抽象AbsServlet类,对请求URL地址处理调用不同的方法,并做转发和重定向定义。
//自定义抽象类,对请求路径中的方法调用不同的方法
//调用方法后根据返回String值作不同的处理:转发、重定向
public abstract class AbsServlet extends HttpServlet {
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求URL路径
StringBuffer requestURL = req.getRequestURL();
//获取最后/之后的方法名称
String methodName=requestURL.substring(requestURL.lastIndexOf("/")+1);
//反射调用相应的方法
Method method = null;
String result = null;
try {
method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
result = (String)method.invoke(this, req, resp);
} catch (Exception e) {
e.printStackTrace();
}
//针对返回值做转发和重定向处理
if(result.contains(":")){
int indexOf = result.indexOf(":");
String first = result.substring(0, indexOf);
String path = result.substring(indexOf + 1);
if("forward".equals(first)){
//转发
req.getRequestDispatcher(path).forward(req,resp);
}else if ("redirect".equals(first)){
//重定向
resp.sendRedirect(req.getContextPath()+path);
}else{
throw new RuntimeException("当前操作不支持");
}
}
//空符符跳到主页
else if("".equals(result) || result.trim().isEmpty()){
resp.sendRedirect(req.getContextPath()+"/index.jsp");
}else {
req.getRequestDispatcher(result).forward(req,resp);
}
}
}
//所有请求urlPattern均需声明
@WebServlet(urlPatterns = {"/getCount/add","/getCount/delete","/getCount/select"})
public class BServlet extends AbsServlet {
public String add(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
//转发,地址不变,同一次请求
// return "forward:/getCound/delete";
//重定向,地址发生改变,不同的请求
// return "redirect:/getCount/select";
//重定向主页
return "";
}
public String delete(HttpServletRequest req,HttpServletResponse resp){
try {
resp.getWriter().print("delete");
} catch (IOException e) {
e.printStackTrace(); }
//重定向delete.html文件
return “delete.html”;
}
public String select(HttpServletRequest req,HttpServletResponse resp){
try {
resp.getWriter().print("select");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
关于转发和重定向:
1.转发:req.getRequestDispatcher("/xxx").forward(req,resp);
转发,是请求请发,浏览器发出一次请求后,将请求的参数(rep,resp)转发到另一个请求,因此参数是共享的;
方法在服务器端内部将请求转发给另外一个资源,浏览器只知道发出了请求并得到了响应结果,并不知道在服务器程序内部发生了转发行为,因此URL地址是不会发生改变。
一个转发行为实际上浏览器只有一次请求。
转发的URL是相对当前web目录的根目录。
2.重定向:resp.sendRedirect("/xxx");
重定向,是响应方式,实际上是当前请求告诉浏览器去请求另一个路径,以重定向前后浏览器实际上是发生了两次请求,两次请求不共享参数,浏览器URL地址会发生改变。
重定向中的URL是相对于整个站点。
相关推荐
- 【Socket】解决UDP丢包问题
-
一、介绍UDP是一种不可靠的、无连接的、基于数据报的传输层协议。相比于TCP就比较简单,像写信一样,直接打包丢过去,就不用管了,而不用TCP这样的反复确认。所以UDP的优势就是速度快,开销小。但是随之...
- 深入学习IO多路复用select/poll/epoll实现原理
-
Linux服务器处理网络请求有三种机制,select、poll、epoll,本文打算深入学习下其实现原理。0.结论...
- 25-1-Python网络编程-基础概念
-
1-网络编程基础概念1-1-基本概念1-2-OSI七层网络模型OSI(开放系统互联)七层网络模型是国际标准化组织(ISO)提出的网络通信分层架构,用于描述计算机网络中数据传输的过程。...
- Java NIO多路复用机制
-
NIO多路复用机制JavaNIO(Non-blockingI/O或NewI/O)是Java提供的用于执行非阻塞I/O操作的API,它极大地增强了Java在处理网络通信和文件系统访问方面的能力。N...
- Python 网络编程完全指南:从零开始掌握 Socket 和网络工具
-
Python网络编程完全指南:从零开始掌握Socket和网络工具在现代应用开发中,网络编程是不可或缺的技能。Python提供了一系列高效的工具和库来处理网络通信、数据传输和协议操作。本指南将从...
- Rust中的UDP编程:高效网络通信的实践指南
-
在实时性要求高、允许少量数据丢失的场景中,UDP(用户数据报协议)凭借其无连接、低延迟的特性成为理想选择。Rust语言凭借内存安全和高性能的特点,为UDP网络编程提供了强大的工具支持。本文将深入探讨如...
- Python 网络编程的基础复习:理解Socket的作用
-
计算机网络的组成部分在逻辑上可以划分为这样的结构五层网络体系应用层:应用层是网络协议的最高层,解决的是具体应用问题...
- 25-2-Python网络编程-TCP 编程示例
-
2-TCP编程示例应用程序通常通过“套接字”(socket)向网络发出请求或者应答网络请求,使主机间或者一台计算机上的进程间可以通信。Python语言提供了两种访问网络服务的功能。...
- linux下C++ socket网络编程——即时通信系统(含源码)
-
一:项目内容本项目使用C++实现一个具备服务器端和客户端即时通信且具有私聊功能的聊天室。目的是学习C++网络开发的基本概念,同时也可以熟悉下Linux下的C++程序编译和简单MakeFile编写二:需...
- Python快速入门教程7:循环语句
-
一、循环语句简介循环语句用于重复执行一段代码块,直到满足特定条件为止。Python支持两种主要的循环结构:for循环和while循环。...
- 10分钟学会Socket通讯,学不会你打我
-
Socket通讯是软硬件直接常用的一种通讯方式,分为TCP和UDP通讯。在我的职业生涯中,有且仅用过一次UDP通讯。而TCP通讯系统却经常写,正好今天写了一个TCP通讯的软件。总结一下内容软件使用C#...
- Python 高级编程之网络编程 Socket(六)
-
一、概述Python网络编程是指使用Python语言编写的网络应用程序。这种编程涉及到网络通信、套接字编程、协议解析等多种方面的知识。...
- linux网络编程Socket之RST详解
-
产生RST的三个条件:1.目的地为某端口的SYN到达,然而该端口上没有正在监听的服务器;2.TCP想取消一个已有的连接;3.TCP接收到一个根本不存在的连接上的分节;现在模拟上面的三种情况:cl...
- Python中实现Socket通讯(附详细代码)
-
套接字(socket)是一种在计算机网络中进行进程间通信的方法,它允许不同主机上的程序通过网络相互通信。套接字是网络编程的基础,几乎所有的网络应用程序都使用某种形式的套接字来实现网络功能。套接字可以用...
你 发表评论:
欢迎- 一周热门
-
-
前端面试:iframe 的优缺点? iframe有那些缺点
-
带斜线的表头制作好了,如何填充内容?这几种方法你更喜欢哪个?
-
漫学笔记之PHP.ini常用的配置信息
-
其实模版网站在开发工作中很重要,推荐几个参考站给大家
-
推荐7个模板代码和其他游戏源码下载的网址
-
[干货] JAVA - JVM - 2 内存两分 [干货]+java+-+jvm+-+2+内存两分吗
-
正在学习使用python搭建自动化测试框架?这个系统包你可能会用到
-
织梦(Dedecms)建站教程 织梦建站详细步骤
-
【开源分享】2024PHP在线客服系统源码(搭建教程+终身使用)
-
2024PHP在线客服系统源码+完全开源 带详细搭建教程
-
- 最近发表
- 标签列表
-
- mybatis plus (70)
- scheduledtask (71)
- css滚动条 (60)
- java学生成绩管理系统 (59)
- 结构体数组 (69)
- databasemetadata (64)
- javastatic (68)
- jsp实用教程 (53)
- fontawesome (57)
- widget开发 (57)
- vb net教程 (62)
- hibernate 教程 (63)
- case语句 (57)
- svn连接 (74)
- directoryindex (69)
- session timeout (58)
- textbox换行 (67)
- extension_dir (64)
- linearlayout (58)
- vba高级教程 (75)
- iframe用法 (58)
- sqlparameter (59)
- trim函数 (59)
- flex布局 (63)
- contextloaderlistener (56)