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");
     }

 }

SpringMVC实例分析的更多相关文章

  1. RPC原理及RPC实例分析

    在学校期间大家都写过不少程序,比如写个hello world服务类,然后本地调用下,如下所示.这些程序的特点是服务消费方和服务提供方是本地调用关系. 1 2 3 4 5 6 public class ...

  2. java基础学习05(面向对象基础01--类实例分析)

    面向对象基础01(类实例分析) 实现的目标 1.如何分析一个类(类的基本分析思路) 分析的思路 1.根据要求写出类所包含的属性2.所有的属性都必须进行封装(private)3.封装之后的属性通过set ...

  3. (转)实例分析:MySQL优化经验

    [IT专家网独家]同时在线访问量继续增大,对于1G内存的服务器明显感觉到吃力,严重时甚至每天都会死机,或者时不时的服务器卡一下,这个问题曾经困扰了我半个多月.MySQL使用是很具伸缩性的算法,因此你通 ...

  4. sql注入实例分析

    什么是SQL注入攻击?引用百度百科的解释: sql注入_百度百科: 所谓SQL注入,就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令.具 ...

  5. 实例分析ELF文件静态链接

    参考文献: <ELF V1.2> <程序员的自我修养---链接.装载与库>第4章 静态链接 开发平台: [thm@tanghuimin static_link]$ uname ...

  6. 用实例分析H264 RTP payload

    用实例分析H264 RTP payload H264的RTP中有三种不同的基本负载(Single NAL,Non-interleaved,Interleaved) 应用程序可以使用第一个字节来识别. ...

  7. nodejs的模块系统(实例分析exprots和module.exprots)

    前言:工欲善其事,必先利其器.模块系统是nodejs组织管理代码的利器也是调用第三方代码的途径,本文将详细讲解nodejs的模块系统.在文章最后实例分析一下exprots和module.exprots ...

  8. Android Touch事件原理加实例分析

    Android中有各种各样的事件,以响应用户的操作.这些事件可以分为按键事件和触屏事件.而Touch事件是触屏事件的基础事件,在进行Android开发时经常会用到,所以非常有必要深入理解它的原理机制. ...

  9. Camera图像处理原理及实例分析-重要图像概念

    Camera图像处理原理及实例分析 作者:刘旭晖  colorant@163.com  转载请注明出处 BLOG:http://blog.csdn.net/colorant/ 主页:http://rg ...

随机推荐

  1. Day24_多线程第一天

    1.线程 1.概述      宏观来讲      进程:就是正在运行的程序      线程:就是进程的执行路径,执行单元 2.创建并启动线程的两种方式(掌握)      1.定义一个类继承Thread ...

  2. Linux记录从此开始

    Linux记录从此开始~ 希望自己多写代码同时多记录~

  3. 调用外部js文件测试

    test <p><img id="img" onclick="javascript:var s=document.createElement('scri ...

  4. python3 如何使用ip、爬虫

    使用urllib.request.random模块,不说了贴代码 url="*"; iplist=['70.254.226.206:8080'];proxy_support=url ...

  5. 浏览器功能记住账号和密码解决方法(HTML解决方式)

    1.在input标签里应用html5的新特性autocomplete="off"  注:对chrome不管用.其他浏览器没试. 2.如果是一个输入框那就在当前input标签后面(一 ...

  6. #ifndef 的用法

    背景: 头件的中的#ifndef,这是一个很关键的东西.比如你有两个C文件,这两个C文件都include了同一个头文件.而编译时,这两个C文件要一同编译成一个可运行文件,会引起大量的声明冲突,这时候需 ...

  7. DNS学习笔记之DNS理论知识

    DNS: Domain Name System (将域名和ip地址相互转化) 域名是一个范围,例如baidu.com,.com.而www.baidu.com是个主机名,即FQDN: Full Qual ...

  8. ie 8 下post提交提交了两次

    擦你吗呀,IE8! 老子写一个登录功能,IE他妈的给我登录了两次,导致权限校验错误,什么他妈的鬼问题,调了两天....fuck,都是泪水. 解决方案:提交按钮加返回值<input type=&q ...

  9. Search Insert Position

    int searchInsert(int* nums, int numsSize, int target) { ; ); ; int mid; while(low<=high){ mid=(lo ...

  10. Bash条件判断

    bash编程之:条件判断,判定后续操作的前提条件是否满足, bash编程之: 条件判断常用类型: 整数测试:比较两个整数谁大谁小,是否相等: 二元测试: num1 操作符 num2 -eq: 等于 - ...