我正在基于控制器反射建模。我想知道您是否同意我的实施以及可以加强的内容。
我从反思开始,我想知道我是否使用了良好的做法。
示例:www.sample.com/Main?mvc=user/edit/5
看到它:
public class StartController extends HttpServlet {
@Override
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String vars = req.getParameter("mvc");
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
MainController main = new MainController();
main.RESTProcess(req, resp, context, vars);
}
}
public class MainController extends Controller {
public void RESTProcess(HttpServletRequest req, HttpServletResponse resp, ApplicationContext context, String vars)
throws IOException, ServletException
{
String[] url;
int nvars;
String controller = null;
String action = null;;
String[] params = null;
int i;
int n;
String controllerName;
String actionName;
if(vars == null || "".equals(vars.trim()))
{
this.redirect(resp,"home");
}
else
{
url = vars.split("/");
nvars = url.length;
if(nvars > 0)
{
controller = url[0].trim(); //users
if(nvars > 1)
{
action = url[1].trim(); //edit
if(nvars > 2)
{
n = 0;
params = new String[nvars - 2]; //array[0] = 5 (iduser)
for(i = 2; i < nvars; i++)
{
params[n] = url[i];
n++;
}
}
}
controllerName = this.getFirstUpper(controller) + "Controller"; //HomeController, UserController pattern
if(!controllerName.equals("Controller"))
{
actionName = "action" + this.getFirstUpper(action); //actionIndex, actionEdit pattern
if(!action.equals("action"))
{
try
{
Class classe = Class.forName("com.sample.controller." + controllerName);
try
{
Constructor c = classe.getConstructor(HttpServletRequest.class, HttpServletResponse.class, String[].class);
try
{
Object obj = c.newInstance(req, resp, context, params);
Method m = classe.getMethod(actionName, null);
m.invoke(obj, null);
System.out.println(obj.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
else
{
this.redirect(resp,"home");
}
}
}
public String getFirstUpper(String str)
{
Integer x = str.length();
str = str.substring(0,1).toUpperCase().concat(str.substring(1, x));
return str;
}
}
public class UserController extends Controller {
private HttpServletRequest req;
private HttpServletResponse resp;
private ApplicationContext context;
private String[] params;
public UserController(HttpServletRequest req, HttpServletResponse resp, ApplicationContext context, String[] params)
{
this.req = req;
this.resp = resp;
this.context = context;
this.params = params;
}
public void actionEdit()
{
Long id = Long.valueOf(this.params[0]);
System.out.println("/home/edit");
}
}