我目前正在用Java进行一些web开发项目,我已经实现了一个前端控制器,该任务是根据路径实例化新的控制器。
那么,用户何时运行呢?q=user/login-ex。前端控制器应该安装UserController,我正试图用这段代码来做这件事。
String q = request.getParameter("q");
try {
String[] page = q.split("/");
// Make first char upper, to match class name conventions.
page[0] = (page[0].substring(0, 1).toUpperCase() + page[0].substring(1).toLowerCase()).trim();
Class contDes = Class.forName("dk.elvar.rocks." + page[0]+ "Controller");
Constructor co = contDes.getConstructor();
co.newInstance(request, response, page);
这导致
java.lang.NoSuchMethodException: dk.elvar.rocks.UserController.<init>()
at java.lang.Class.getConstructor0(Class.java:2706)
at java.lang.Class.getConstructor(Class.java:1657)
at dk.elvar.rocks.FrontController.doGet(FrontController.java:35)
我试着在谷歌上查了一下,错误是,在加载的对象中声明一个构造函数,使类公开,已经存在了。
用户控制器:
public class UserController extends HttpServlet {
private final String USERNAME = "Martin";
private final String PASSWORD = "David";
private static final long serialVersionUID = 1L;
HttpServletRequest request;
HttpServletResponse response;
public UserController(HttpServletRequest request, HttpServletResponse response, String[] action) {
this.request = request;
this.response = response;
if(action[1].equalsIgnoreCase("login")) {
this.renderLoginAction();
}
if(action[1].equalsIgnoreCase("val-login")) {
this.validateLoginAction();
}
}
您可能会得到此异常,因为该类没有默认构造函数。您可以通过将参数传递给getConstructor
方法来获得带有参数的构造函数:
Constructor co = contDes.getConstructor(
HttpServletRequest.class,
HttpServletResponse.class,
String[].class);
co.newInstance(request, response, page);
通常不建议使用其他默认构造函数,因为web.xml或struts-config.xml使用反射来实例化servlet。
如果您想获得类的实例而不是默认构造函数,
Class userController = Class.forName("<packages.>UserController");
Constructor userControllerConstructor = userController.class.getConstructor(HttpServletRequest.class, HttpServletResponse.class, String[].class);
UserController userControllerObj = (UserController)constructor.newInstance(request,response, action);