gpt4 book ai didi

tomcat - 我构建我的 servlet 了吗?

转载 作者:行者123 更新时间:2023-11-28 23:56:42 24 4
gpt4 key购买 nike

我开发了一个 Web 应用程序 (WebApplication 1),它有 1 个 servlet 和许多 JSP,这个应用程序具有一定的功能(可以说是 No1)。
在那个应用程序中,在servlet的processRequest(HttpServletRequest request, HttpServletResponse response)方法中,有很多if else语句来检测用户在做什么想做。

小服务程序

public class MyServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException{

init();
HttpSession session = request.getSession(true);
String jspAction = request.getParameter("action");

if(jspAction.equals("home")){

//do sth

RequestDispatcher disp = getServletContext().getRequestDispatcher("/home.jsp");
disp.forward(request, response);

}else if(jspAction.equals("out")){

//do sth

RequestDispatcher disp = getServletContext().getRequestDispatcher("/out.jsp");
disp.forward(request, response);

}//etc..

}
}

在 JSP 链接或表单提交中具有此链接格式 MyServlet?action=out。按照这种方法,此时我有 25 个 if 语句。

所以我的问题是:这是构建我的应用程序的正确方法还是我应该为我想执行的每个功能创建不同的 servlet?

最佳答案

虽然这是一个有效(且非常基本)的解决方案,但最好为此目的使用 MVC 框架,而不是重新发明轮子。中央 servlet 作为应用程序的访问点是一种常见的做法,例如可以在早期的 Java EE design patterns 中找到。 ,作为“前端 Controller ”“调度器 View ”

例如,您应该看看 Spring MVC 或 Struts 2。

关于tomcat - 我构建我的 servlet 了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32434933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com