Spring的MVC模块
Spring提供了自己的MVC框架实现,相比Struts、WebWork等MVC模块,Spring的MVC模块显得小巧而灵活。Spring的MVC使用Controller处理用户请求,此处的Controller类似于Struts1.x中的Action。SpringMVC作为Spring框架的一部分,在进行框架整合时不需要像Struts1&2那样特意的去融合到Spring里面,其本身就在Spring里面。
先定义如下各层:
域模型层实体类Cat:
package com.spring.mvc; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name = "tb_cat") public class Cat { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String name; @Temporal(value = TemporalType.TIMESTAMP) private Date createdDate; public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
业务逻辑层接口ICatService:
package com.spring.mvc; import java.util.List; public interface ICatService { public void createCat(Cat cat); public List<Cat> listCats(); public int getCatsCount(); }
业务逻辑层接口的实现类CatServiceImpl:
package com.spring.mvc; import java.util.List; public class CatServiceImpl implements ICatService { private ICatDao catDao; public ICatDao getCatDao() { return catDao; } public void setCatDao(ICatDao catDao) { this.catDao = catDao; } public void createCat(Cat cat) { if (catDao.findCatByName(cat.getName()) != null){ throw new RuntimeException("猫" + cat.getName() + "已经存在。" ); } catDao.createCat(cat); } public int getCatsCount() { return catDao.getCatsCount(); } public List<Cat> listCats() { return catDao.listCats(); } }
数据库持久层接口ICatDao:
package com.spring.mvc; import java.util.List; public interface ICatDao { public void createCat(Cat cat); public Cat findCatByName(String name); public List<Cat> listCats(); public int getCatsCount(); }
数据库持久层实现类CatDaoImpl:
package com.spring.mvc; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class CatDaoImpl extends HibernateDaoSupport implements ICatDao { public void createCat(Cat cat) { this.getHibernateTemplate().persist(cat); } public Cat findCatByName(String name) { List<Cat> catList = this.getHibernateTemplate().find(" select c from Cat c where c.name = ? ", name); if (catList.size() > 0) return catList.get(0); return null; } public int getCatsCount() { return (Integer) this.getSession(true).createQuery(" select count(c) from Cat c ").uniqueResult(); } public List<Cat> listCats() { return this.getHibernateTemplate().find(" select c from Cat c "); } }
SpringMVC的控制层和视图层
SpringMVC的控制层是Controller。Controller是个接口,一般直接继承AbstractController抽象类,并实现handleRequestInternal方法,此方法类似于Struts1.x中的execute()方法。
SpringMVC的视图层使用的是ModelAndView对象。handleRequestInternal方法返回的即时此对象,ModelAndView相当于Struts1.x中的ActionForward。
ModelAndView可以方便的传递参数,例如
return new ModelAndView("cal/listCat","cat",cat);
等价于
request.setAttribute("cat",cat);
return new ModelAndView("cal/listCat");
当传递多个参数时,可以使用Map,例如:
Map map = new HashMap();
map.put("cat",cat);
map.put("catList",catList);
return new ModelAndView("cat/listCat",map);
package com.spring.mvc; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class CatController extends AbstractController { private ICatService catService; @Override protected ModelAndView handleRequestInternal(HttpServletRequest request,HttpServletResponse response) throws Exception { String action = request.getParameter("action"); if ("add".equals(action)) { return this.add(request, response); } return this.list(request, response); } protected ModelAndView list(HttpServletRequest request,HttpServletResponse response) throws Exception { List<Cat> catList = catService.listCats(); request.setAttribute("catList", catList); return new ModelAndView("cat/listCat"); } protected ModelAndView add(HttpServletRequest request,HttpServletResponse response) throws Exception { Cat cat = new Cat(); cat.setName(request.getParameter("name")); cat.setCreatedDate(new Date()); catService.createCat(cat); return new ModelAndView("cat/listCat", "cat", cat); } public ICatService getCatService() { return catService; } public void setCatService(ICatService catService) { this.catService = catService; } }
多业务分发器
如果一个Controller需要处理多种业务逻辑,可以使用MultiActionController。MultiActionController就是一个分发器,相当于Struts1.x中的DispatchAction分发器,能根据某参数值将不同的请求分发到不同的方法上,比如可以设置分发器参数为method,则URL地址访问catMulti.mvc?method=add时将会执行add方法。CatMultiController不需要继承父类的任何方法,只需要定义形如public ModelAndView xxx(HttpServletRequest request,HttpServletResponse response)的方法,当地址栏参数method为xxx时,Spring会通过反射调用xxx()方法。
package com.spring.mvc; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class CatMultiController extends MultiActionController { private ICatService catService; public ICatService getCatService() { return catService; } public void setCatService(ICatService catService) { this.catService = catService; } @SuppressWarnings("unchecked") public ModelAndView add(HttpServletRequest request,HttpServletResponse response) { Cat cat = new Cat(); cat.setName(request.getParameter("name")); cat.setCreatedDate(new Date()); catService.createCat(cat); return this.list(request, response); } @SuppressWarnings("unchecked") public ModelAndView list(HttpServletRequest request,HttpServletResponse response) { List<Cat> catList = catService.listCats(); request.setAttribute("catList", catList); return new ModelAndView("cat/listCat"); } }