?? 一個小的web項目中的實現方法討論.txt
字號:
一個小的WEB項目中的實現方法討論
最近對一個別人的WEB項目進行維護,看到這樣的實現方法:
1.只有一個Controller的servlet 類
2.一個Service接口
3.一些實現Service接口的類
Controller類負責進行控制,動態產生業務邏輯的類的實例(所有的類需要實現Service接口),然后通過
httpservletrequest.setAttribute("USERLIST", userList);向WEB端賦值,
具體的可以參考部分代碼:
Controller 類(extends HttpServlet )
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
//service name,example for packagename.ServiceName
String serviceName = request.getParameter(Constant.SERVICE);
if (serviceName == null)
throw new ServletException("There isn't service parameter![?service=]");
String targetName = request.getParameter(Constant.TARGET);
//the targeted file name,example for /fileName.jsp
if (targetName == null)
throw new ServletException("There isn't target parameter![?target=]");
ServletContext servletcontext = getServletContext();
try {
//TODO:hashmap to reduce the generated instance?
Class serviceClass = Class.forName(serviceName);
Service service = (Service) serviceClass.newInstance();
service.execute(request, response, servletcontext);
} catch (ClassNotFoundException classnotfoundexception) {
throw new ServletException(classnotfoundexception.getMessage());
} catch (IllegalAccessException illegalaccessexception) {
throw new ServletException(illegalaccessexception.getMessage());
} catch (Exception exception) {
throw new ServletException(exception.getMessage());
}
forward(request, response, targetName);
}
Service 接口
public interface Service {
public abstract void execute(
HttpServletRequest httpservletrequest,
HttpServletResponse httpservletresponse,
ServletContext servletcontext)
throws Exception;
}
一個實現service的類(相當于業務類)
public class StartService implements Service {
public void execute(
HttpServletRequest httpservletrequest,
HttpServletResponse httpservletresponse,
ServletContext servletcontext)
throws Exception {
//test data
List userList = new ArrayList();
httpservletrequest.setAttribute("USERNAME", "TestUser");
httpservletrequest.setAttribute("USERLIST", userList);
}
}
JSP 頁面文件
<%
String userName=(String)request.getAttribute("USERNAME");
List userList=(List)request.getAttribute("USERLIST");
%>
訪問的時候:
/service.Controller?service=StartService&target=/StartPage.jsp
我現在想知道的
1.這種實現方案怎么樣?為什么這么做,有什么好處
2.產生的service 類對象有沒有必要用hashmap保存,以避免產生更多的對象
//TODO:hashmap to reduce the generated instance?
Class serviceClass = Class.forName(serviceName);
Service service = (Service) serviceClass.newInstance();
service.execute(request, response, servletcontext);
3.大家有沒有好的類似的方案(只是針對小型的WEB項目,利用Framework的就不要說了)
謝謝!
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -