- 创建Servlet、命名为BaseServlet继承HttpServlet,只需要覆写一个方法,即service方法
- 写你需要用到的Servlet,比方:UserServlet | DepartmentServlet | EmployeeServlet等 但是他们不用再去继承HttpServlet,而是要去继承BaseServlet
以下BaseServlet,没有采用注解。依旧是使用web.xml作为配置
代码语言:javascript复制package cn.javabs.commons;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//@WebServlet(name = "BaseServlet",urlPatterns = {"/baseServlet"})
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uri = req.getRequestURI();
System.out.println("uri:" uri);//uri: /userServlet/addUser
int position = uri.lastIndexOf('/');
System.out.println("position:" position); // position: 12
String methodName = uri.substring(position 1);//position 1: 最后一个斜线后的字母,也就是我们想要单词的首字母
System.out.println("methodName:" methodName);// methodName: /addUser
// ----
System.out.println("this代表的是:" this);//this代表的是:cn.javabs.commons.UserServlet@49220d
try {
// 不会忽略访问权限修饰符 只识别public修饰的方法
// method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
// 会忽略访问权限修饰符
Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
System.out.println("method:" method);
String pageName = (String) method.invoke(this,req,resp);
System.out.println("pageName:" pageName);
if (pageName==null || pageName.equals("")){
resp.sendRedirect(req.getContextPath() "/404.jsp");
}else{
// 判断 返回得字符串中是否又冒号存在!
if (pageName.contains(":")){
// 以冒号分割 pageName
String[] datas = pageName.split(":");
System.out.println("数组的长度:" datas.length);
System.out.println("冒号左边的数据:" datas[0]);
System.out.println("冒号右边的数据:" datas[1]);
// 进行判断 固定的字符串"forward" 与 我们得到的左侧数据 进行判断是否相同(忽略大小写)
if("forward".equalsIgnoreCase(datas[0])){
req.getRequestDispatcher("/" datas[1] ".jsp").forward(req,resp);
}
// 进行判断 固定的字符串"redirect" 与 我们得到的左侧数据 进行判断是否相同(忽略大小写)
else if("redirect".equalsIgnoreCase(datas[0])){
resp.sendRedirect(req.getContextPath() "/" datas[1] ".jsp");
}
}else{// 没有冒号,即代表没有指定是转发或者重定向、一律按照转发处理!
req.getRequestDispatcher("/" pageName ".jsp").forward(req,resp);
}
}
} catch (NoSuchMethodException e) {
throw new RuntimeException("BaseServlet出现了NoSuchMethodException异常" e);
} catch (IllegalAccessException e) {
throw new RuntimeException("BaseServlet出现了IllegalAccessException异常" e);
} catch (InvocationTargetException e) {
throw new RuntimeException("BaseServlet出现了InvocationTargetException异常" e);
}
}
}
以下Servlet,全部是继承的BaseServlet,也可以理解为是测试使用的Servlet
页面
代码语言:javascript复制<%--
Created by IntelliJ IDEA.
User: Mryang
Date: 2019/4/26
Time: 14:01
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/userServlet/addUser">添加用户</a>
<a href="${pageContext.request.contextPath}/userServlet/editUser">编辑用户</a>
<a href="${pageContext.request.contextPath}/userServlet/delUser">删除用户</a>
<a href="${pageContext.request.contextPath}/userServlet/findUser">查询用户</a>
<hr/>
<a href="${pageContext.request.contextPath}/userServlet/xxx">没有对应的方法</a>
<hr/>
<a href="${pageContext.request.contextPath}/departmentServlet/addDept">添加部门注解</a>
<a href="${pageContext.request.contextPath}/bookServlet/addBook">添加图书配置文件</a>
<hr/>
</body>
</html>
以下是测试的Servlet(有配置文件的,也有注解方式的)
第一个UserServlet
代码语言:javascript复制package cn.javabs.web.servlet;
import cn.javabs.commons.BaseServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UserServlet extends BaseServlet {
/**
* 添加用户
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public String addUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("添加用户方法被index.jsp调用执行了");
// request.getRequestDispatcher("/main.jsp").forward(request,response);
// 会将return的内容字符串发送给BaseServlet中得PageName 变量接受接受得
return "forward:main";
}
/**
* 编辑用户
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
protected String editUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("编辑用户方法被index.jsp调用执行了");
// response.sendRedirect(request.getContextPath() "/success.jsp");
// 会将return的内容字符串发送给BaseServlet中得PageName 变量接受接受得
return "redirect:success";
}
/**
* 删除用户
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
protected String delUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("删除用户方法被index.jsp调用执行了");
return "right";
}
/**
* 查询用户
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
protected String findUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("查询用户方法被index.jsp调用执行了");
return "";
}
}
第二个BookServlet
代码语言:javascript复制package cn.javabs.web.servlet;
import cn.javabs.commons.BaseServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class BookServlet extends BaseServlet {
public String addBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("添加图书成功");
return "success";
}
public String editBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
return "redirect:main";
}
}
第三个测试Servlet,我们采用注解的方式:
代码语言:javascript复制package cn.javabs.web.servlet;
import cn.javabs.commons.BaseServlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = {"/departmentServlet/*"})
public class DepartmentServlet extends BaseServlet {
public String addDept(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("添加部门成功");
return "success";
}
public String editDept(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
return "redirect:main";
}
}
配置文件 web.xml
代码语言:javascript复制<?xml version="1.0" encoding="UTF-8"?>
<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">
<!--BaseServlet的配置-->
<servlet>
<servlet-name>BaseServlet</servlet-name>
<servlet-class>cn.javabs.commons.BaseServlet</servlet-class>
</servlet>
<!--注意:没有使用通配符-->
<servlet-mapping>
<servlet-name>BaseServlet</servlet-name>
<url-pattern>/baseServlet</url-pattern>
</servlet-mapping>
<!--UserServlet的配置-->
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>cn.javabs.web.servlet.UserServlet</servlet-class>
</servlet>
<!--注意:url中的属性值后需要有通配符-->
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/userServlet/*</url-pattern>
</servlet-mapping>
<!--BookServlet的配置-->
<servlet>
<servlet-name>BookServlet</servlet-name>
<servlet-class>cn.javabs.web.servlet.BookServlet</servlet-class>
</servlet>
<!--注意:url中的属性值后需要有通配符-->
<servlet-mapping>
<servlet-name>BookServlet</servlet-name>
<url-pattern>/bookServlet/*</url-pattern>
</servlet-mapping>
</web-app>
图解
图1:
图2:
图3:
以上代码开发详解视频:
https://v.qq.com/x/page/j0864o8oze1.html