2008-05-09
一个小的WEB项目中的实现方法讨论(转载JDON)
最近对一个别人的WEB项目进行维护,看到这样的实现方法:
1.只有一个Controller的servlet 类
2.一个Service接口
3.一些实现Service接口的类
Controller类负责进行控制,动态产生业务逻辑的类的实例(所有的类需要实现Service接口),然后通过
httpservletrequest.setAttribute("USERLIST", userList);向WEB端赋值,
具体的可以参考部分代码:
Controller 类(extends HttpServlet )
我现在想知道的 1.这种实现方案怎么样?为什么这么做,有什么好处 2.产生的service 类对象有没有必要用hashmap保存,以避免产生更多的对象
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;
}
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
//TODO:hashmap to reduce the generated instance? Class serviceClass = Class.forName(serviceName); Service service = (Service) serviceClass.newInstance(); service.execute(request, response, servletcontext);
http://www.jdon.com/jivejdon/thread/17044.html
发表评论
最近加入圈子
最新评论
-
mysql乱码
"JSP的request 默认为ISO8859_1,所以在处理中文的时候, "何 ...
-- by senbao18 -
对synchronized的一点认识
怎么回复了,还删不了?路过,路过,不好意思
-- by dennis_zane -
对synchronized的一点认识
呵呵,JAVA新人。初次发贴!
-- by heshencao







评论排行榜