(1)BaseServlet不用在web.xml中配置,因为访问的是他子类的方法,只需要子类在web.xml中配置
/**
* 这个Servlet是用来做父类的,不让通过地址直接访问,所以不进行web.xml配置,还可以设置为abstract类
* 使用方式:在访问子类的地址后加上“?method=(子类中设置的方法)”
*/
public abstract class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决POST表单的中文乱码问题
request.setCharacterEncoding("utf-8");
//接收method属性的值
String methodName = request.getParameter("method");
//通过反射调用方法
try {
//得到当前对象的类对象
Class clazz = this.getClass();//this ??? UserServlet
//通过反射创建对象 Servlet是单实例多线程程序
//Object obj = clazz.newInstance();
//获取方法
Method method = clazz.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
//通过反射调用方法
method.invoke(this,request,response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
(2)继承BaseServlet的子类的Servlet,方法需要为public类型的的,这样BaseServlet中才能获取到方法
/**
使用的Servlet要继承BaseServlet 当发送请求时,先寻找service方法,在父类中再利用反射进入到子类中调用方法
*/
public class EmployeeServlet extends BaseServlet{
public void toShowAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//接收视图层的数据
String empId = request.getParameter("empId");
//调用业务层
DepartmentService departmentService = new DepartmentServiceImpl();
List<Department> deptList = departmentService.findAll();
EmployeeService employeeService1 = new EmployeeServiceImpl();
List<Employee> list1 = employeeService1.findByEmpType(2);
EmployeeService employeeService2 = new EmployeeServiceImpl();
Employee employee = employeeService2.findByEmpId(empId);
//带数据调到empAdd.jsp中
request.setAttribute("deptList",deptList);
request.setAttribute("empType",list1);
request.setAttribute("emp",employee);
request.getRequestDispatcher("/system/empUpdate.jsp").forward(request,response);
}
}
(3)测试类,最好为post请求,如果为get请求需要处理中文乱码问题
<form action="servlet/DepartmentServlet?method=toShowAll" method="post">
<ul class="forminfo">
<li><label>部门编号</label><input name="deptNo" type="text" class="dfinput" /> </li>
<li><label>部门名称</label><input name="deptName" type="text" class="dfinput" /> </li>
<li><label>办公地点</label><input name="location" type="text" class="dfinput" /></li>
<li><label> </label><input name="" type="submit" class="btn" value="确认保存"/></li>
</ul>
</form>