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是相对于整个站点。