javaweb之Servlet javaweb参考文献近三年
yuyutoo 2024-11-05 13:27 12 浏览 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是相对于整个站点。
相关推荐
- 墨尔本一华裔男子与亚裔男子分别失踪数日 警方寻人
-
中新网5月15日电据澳洲新快网报道,据澳大利亚维州警察局网站消息,22岁的华裔男子邓跃(Yue‘Peter’Deng,音译)失踪已6天,维州警方于当地时间13日发布寻人通告,寻求公众协助寻找邓跃。华...
- 网络交友须谨慎!美国犹他州一男子因涉嫌杀害女网友被捕
-
伊森·洪克斯克(图源网络,侵删)据美国广播公司(ABC)25日报道,美国犹他州一名男子于24日因涉嫌谋杀被捕。警方表示,这名男子主动告知警局,称其杀害了一名在网络交友软件上认识的25岁女子。雷顿警...
- 一课译词:来龙去脉(来龙去脉 的意思解释)
-
Mountainranges[Photo/SIPA]“来龙去脉”,汉语成语,本指山脉的走势和去向,现比喻一件事的前因后果(causeandeffectofanevent),可以翻译为“i...
- 高考重要考点:range(range高考用法)
-
range可以用作动词,也可以用作名词,含义特别多,在阅读理解中出现的频率很高,还经常作为完形填空的选项,而且在作文中使用是非常好的高级词汇。...
- C++20 Ranges:现代范围操作(现代c++白皮书)
-
1.引言:C++20Ranges库简介C++20引入的Ranges库是C++标准库的重要更新,旨在提供更现代化、表达力更强的方式来处理数据序列(范围,range)。Ranges库基于...
- 学习VBA,报表做到飞 第二章 数组 2.4 Filter函数
-
第二章数组2.4Filter函数Filter函数功能与autofilter函数类似,它对一个一维数组进行筛选,返回一个从0开始的数组。...
- VBA学习笔记:数组:数组相关函数—Split,Join
-
Split拆分字符串函数,语法Split(expression,字符,Limit,compare),第1参数为必写,后面3个参数都是可选项。Expression为需要拆分的数据,“字符”就是以哪个字...
- VBA如何自定义序列,学会这些方法,让你工作更轻松
-
No.1在Excel中,自定义序列是一种快速填表机制,如何有效地利用这个方法,可以大大增加工作效率。通常在操作工作表的时候,可能会输入一些很有序的序列,如果一一录入就显得十分笨拙。Excel给出了一种...
- Excel VBA入门教程1.3 数组基础(vba数组详解)
-
1.3数组使用数组和对象时,也要声明,这里说下数组的声明:'确定范围的数组,可以存储b-a+1个数,a、b为整数Dim数组名称(aTob)As数据类型Dimarr...
- 远程网络调试工具百宝箱-MobaXterm
-
MobaXterm是一个功能强大的远程网络工具百宝箱,它将所有重要的远程网络工具(SSH、Telnet、X11、RDP、VNC、FTP、MOSH、Serial等)和Unix命令(bash、ls、cat...
- AREX:携程新一代自动化回归测试工具的设计与实现
-
一、背景随着携程机票BU业务规模的不断提高,业务系统日趋复杂,各种问题和挑战也随之而来。对于研发测试团队,面临着各种效能困境,包括业务复杂度高、数据构造工作量大、回归测试全量回归、沟通成本高、测试用例...
- Windows、Android、IOS、Web自动化工具选择策略
-
Windows平台中应用UI自动化测试解决方案AutoIT是开源工具,该工具识别windows的标准控件效果不错,但是当它遇到应用中非标准控件定义的UI元素时往往就无能为力了,这个时候选择silkte...
- python自动化工具:pywinauto(python快速上手 自动化)
-
简介Pywinauto是完全由Python构建的一个模块,可以用于自动化Windows上的GUI应用程序。同时,它支持鼠标、键盘操作,在元素控件树较复杂的界面,可以辅助我们完成自动化操作。我在...
- 时下最火的 Airtest 如何测试手机 APP?
-
引言Airtest是网易出品的一款基于图像识别的自动化测试工具,主要应用在手机APP和游戏的测试。一旦使用了这个工具进行APP的自动化,你就会发现自动化测试原来是如此简单!!连接手机要进行...
- 【推荐】7个最强Appium替代工具,移动App自动化测试必备!
-
在移动应用开发日益火爆的今天,自动化测试成为了确保应用质量和用户体验的关键环节。Appium作为一款广泛应用的移动应用自动化测试工具,为测试人员所熟知。然而,在不同的测试场景和需求下,还有许多其他优...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- 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)