利用反射实现一个Java文件书写多个Servlet,无框架

来源:互联网 发布:mac战网该服务器 编辑:程序博客网 时间:2024/05/22 13:28

1.提交请求的时候,加上一个method的请求参数。

method=getLimitStudent

2.在doGet或者doPost中获得请求参数。

String method = request.getParameter("method");

我们将会根据这个请求参数找到具体的方法,方法名应该和这个参数一样,我的参数为getLimitStudent ,所以我的方法名也是这个。

3.找到这个Java文件声明的类的类类型。

Class<? extends BaseStudent> c1 = this.getClass();

4.通过类类型和方法名找打方法,并执行。

try {Method m = c1.getDeclaredMethod(method, HttpServletRequest.class,HttpServletResponse.class);m.invoke(this, request,response);} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}
其中request,response应该已他们的接口的类类型为标准,接口的类类型要大于参数的类,只要是接口的类类型就可以满足。

5.书写method方法即可。


下面是完整代码:

(为了这个方法可以重用,可以把具体的方法实现新申明一个类,然后继承这个有反射的类,实现重用的效果。)

BaseStudent.java
import java.io.IOException;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class BaseStudent extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String method = request.getParameter("method");Class<? extends BaseStudent> c1 = this.getClass();try {Method m = c1.getDeclaredMethod(method, HttpServletRequest.class,HttpServletResponse.class);m.invoke(this, request,response);} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}

继承该类的类的java文件。

StudentServlet.java

import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.gpf.page.bean.Page;import com.gpf.page.bean.Student;import com.gpf.page.service.StudentService;import com.gpf.page.utils.WEBUtil;@WebServlet("/student")public class StudentServlet extends BaseStudent {private static final long serialVersionUID = 1L;private StudentService stuService = new StudentService();public void getLimitStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {int currentPage = Integer.parseInt(request.getParameter("currentPage"));Page<Student>pageStu = stuService.getLimitStudent(currentPage);pageStu.setPath(WEBUtil.getPath(request));request.setAttribute("pageStu", pageStu);request.getRequestDispatcher("WEB-INF/main.jsp").forward(request, response);}}





阅读全文
0 0