这是一种Servlet另一种实现方式,不过我想应该有更好的实习,当作学习研究。
package com.Root.beas;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.Root.Book.Book;
public class BaseServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String className = request.getParameter("className");
String methodName = request.getParameter("method");
try{
Class class1 = Class.forName(className);
Method method = class1.getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
method.invoke(class1.newInstance(), request,response);
}catch(Exception e){
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
<pre name="code" class="java">package com.Root.Book;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Book {
private String Name;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public void addBook(HttpServletRequest request, HttpServletResponse response){
System.out.println("haha");
System.out.println(request.getParameter("Username"));
}
}
<form action="BaseServlet" method = "post">
<input type="hidden" name="className" value = "com.Root.Book.Book">
<input type="hidden" name="method" value = "addBook">
<input type="text" name="Username">
<input type = "submit" value = "提交">
</form>