SSHM框架之MVC部分

以前在传统行业技术强度相对不大,不处理大数据,也不弄高并发的,所以学不到什么高端编程技术和架构方法,那么我自己就琢磨搞一个SSH架构的东西出来,希望可以帮助到一些朋友,也希望大拿给出相应的指导意见。

先从用了什么东西说起吧 SSHM=SpringMVC+Spring+Hibernate+Mybatis,至于为什么要这么搞,我先简要的说下。

SpringMVC 我最初的想法就是,它比struts2小,属于轻量级的MVC框架,而且和spring可以完美结合在一起。

Spring  额 不需要我废话了。

hibernate 主要用来请求数据库事物方面的应用,主要执行DML语句,不过用的比较挫,不太会,希望多指点。

Mybatis 主要用来查询,因为查询这个东西 我还是喜欢用SQL来查询。

spring版本3.1.2,hibernate3,mybatis3.1.1 版本还是比较新的。其他的一些技术也包含进去了比如说poi,jdom,jackson等,就不一一介绍了。

这里插一段,在spring选择版本初期,我是用的3.0.5这个版本,jackson 用的是一个比较低的版本,这两个东西怎样都不兼容,头疼!在实验了多个版本后,发现了jackson 这玩意向下不兼容,我去,有意思,最后确定了spring3.1.2往上与jackson2.1左右的版本才兼容,好吧,就当学习了。

先看下基础web.xml配置吧

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <!-- spring 过滤器统一设置编码 -->
    <filter>
        <filter-name>Spring character encoding filter</filter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>Spring character encoding filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:config/applicationContext*.xml</param-value>
    </context-param>

    <!-- Web 项目 Spring 加载 Log4j 的监听 -->
    <listener>
        <listener-class>
            org.springframework.web.util.Log4jConfigListener
        </listener-class>
    </listener>
    <!-- spring 应用上下文监听器 主要初始化注入 -->
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    
    <!--  Servlet模块同时会加载{servletname}-servlet.xml文件 SpringMVC前值控制模式基础selvlet -->
    <servlet>
        <servlet-name>newframe</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

  <servlet-mapping>
        <servlet-name>newframe</servlet-name>
        <url-pattern>*.do</url-pattern><!-- 是拦截以.do结尾的请求,可自定义 -->
  </servlet-mapping>
 
    <!-- 如果不定义webAppRootKey参数,那么webAppRootKey就是缺省的"webapp.root"。
        但最好设置,以免项目之间的名称冲突。 定义以后,在Web Container启动时将把ROOT的绝对路径写到系统变量里。
        然后log4j的配置文件里就可以用${ myapp.root }来表示Web目录的绝对路径,把log文件存放于webapp中。 
        此参数用于后面的“Log4jConfigListener” -->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>myapp.root</param-value>
    </context-param>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.properties</param-value>
    </context-param>
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

 每个标签是不是都写明白了呢?

 那么我们从springMVC先开始介绍吧,我这里只讲我怎样搭建这个MVC的过程 至于SpringMVC的原理,我不想做过多的介绍,因为这不是本文的重点,并且也不是一句两句话能说明白的,我看到有些文章 几百字+几张图片就说这事springMVC的基本原理,我曾经略读过一些springMVC的源码,里面的复杂程度也不是简单的几句话能描述的清楚的,所以不做介绍,等小弟我真吃透了,在写出来吧,有关资料可以参考spring官网对springMVC的介绍,不是很详细,但是也能明白个大概。

不闲扯了,先看springMVC配置文件,位置:WEN-INF文件夹下,命名方式:以web.xml文件中DispatcherServlet的serlvletname-servlet.xml为公式命名,也可自定义文件名,在DispatcherServlet节点下加如下配置:

<init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/config/applicationContext-mvc.xml</param-value>
</init-param>

MVC配置文件的内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  
                        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
    <mvc:annotation-driven></mvc:annotation-driven>

     <!-- 先扫描controller 后service -->
    <context:component-scan base-package="com.tansun.newframe.*">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Service" />
    </context:component-scan>


    <!-- 使注解生效   -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" />
                 <bean class = "org.springframework.http.converter.StringHttpMessageConverter">
                       <property name = "supportedMediaTypes">
                        <list>
                             <bean class="org.springframework.http.MediaType">
                                 <constructor-arg index="0" value="text"/>
                                  <constructor-arg index="1" value="plain"/>
                                  <constructor-arg index="2" value="UTF-8"/>
                             </bean>
                             <bean class="org.springframework.http.MediaType">
                                  <constructor-arg index="0" value="*"/>
                                  <constructor-arg index="1" value="*"/>
                                  <constructor-arg index="2" value="UTF-8"/>
                             </bean>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>
    <!--
        springmvc的配置文件,它的命名规则:web.xml里springmvc模块的名称+“-servlet.xml”
        对模型视图名称的解析,即在模型视图名称添加前后缀 例如:Controller里返回一个名为test的逻辑视图名称,根据配置文件,
        它最终找到的文件是/panges/test.jsp,即把前后缀拼装为一个路径。
    -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- jaskson 用于前后台以json形式的数据交换,设置编码集为utf-8编码-->
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    

    <!-- SpringMVC 异常处理机制 -->
    <bean id="exceptionResolver"
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.Exception">common/error</prop>
                <prop key="java.lang.Throwable">common/error</prop>
            </props>
        </property>
        <property name="statusCodes">
            <props>
                <prop key="errors/500">500</prop>
                <prop key="errors/404">404</prop>
            </props>
        </property>
        <!-- 设置日志输出级别,不定义则默认不输出警告等错误日志信息 -->
        <property name="warnLogCategory" value="WARN"></property>
        <!-- 默认错误页面,当找不到上面mappings中指定的异常对应视图时,使用本默认配置 -->
        <property name="defaultErrorView" value="../error"></property>
        <!-- 默认HTTP状态码 -->
        <property name="defaultStatusCode" value="500"></property>

    </bean>
    
</beans>  

基于以上配置,springMVC的基础配置应该算是完成了,简单写一个控制器。

@Controller 注解为此类为controller

@RequestMapping 注解类前,可以理解为请求URL的一个前置命名,在方法前可以理解为请求的后置命名,一下代码的请求就是/newframe/test/getAllDemo.do

@Resource就不需要过多说明了吧,用过spring的人都知道是干啥的。

@Controller
@RequestMapping(value="/test")
public class DemoControl {
    
    @Resource(name="demoService")
    public DemoService cDemoService;
    
    @RequestMapping(value="/getAllDemo.do",method=RequestMethod.GET)
    public ModelAndView getAllDemo(){
        ModelAndView tReturn = new ModelAndView("test/test_list");
        List<Demo> mDemos =cDemoService.getAllDemo();
        tReturn.addObject("demos", mDemos);
        return tReturn;
    }
}

注意,返回值为一个ModelAndView对象,构造方法中传入的“test/test_list”是一个JSP的路径,在MVC的配置文件中已经简单介绍过InternalResourceViewResolver这个就是他的应用,他表示执行完毕这个方法后转发(注意是转发)到/newframe/test/test_list.jsp,其中addObject方法设置一对键值,将这对键值设置到HttpRequest中(注意是request中)。如果直接返回"test/test_list"则InternalResourceViewResolver将字符串解析为jsp路径也返回 到/newframe/test/test_list.jsp中。那么怎样在这个方法中拿到request或者是response?其实我个人是不建议这么做的,因为如果使用request或者是response就又变成了J2EE编程了,失去了使用开源框架的意义,但是也有办法

public ModelAndView getAllDemo(HttpRequest request,HttpResponse resopnse) 

这样就可以操作response,request了!

那么spring是如何与jackson相互配合使用的呢? 

jackson是一个开源的 可以将JAVA实体对象转换为JSON形式的数据格式的各种技术,他不需要你写任何代码(当然你也可以写,但是比较麻烦,如果是想要自己用编程的方式来解决我建议可以用apache 的JSONArray,或者是Google的Gson两种技术),只需要你配置到你的springMVC配置文件中,他可以将springMVC与前台的Javascript完美结合在一起,前台可以用jquery 来解析返回的json数据格式。具体配置方法上面已经给出,下面来介绍下controller中是如何应用的。

    @RequestMapping(value = "/getUsers.do", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getUsers(UserInfo userInfo,
            @RequestParam String page, @RequestParam String rows)
            throws Exception {

        // 获得总条数
        int totalNum = cUserInfoService.getUserCount();
        // 获得查询到的用户
        List<UserInfoVo> userList = cUserInfoService.getUsers(userInfo, page,
                rows);
        Map<String, Object> mMap = new HashMap<String, Object>();
        mMap.put("rows", userList);
        mMap.put("total", totalNum);

        return mMap;

    }

这里介绍一个注解@ResponseBody 他的作用是返回值JAVA对象(Obejct)将以响应体返回到前台页面中,这里其实没有response什么大事别理解错了。

方法很简单 将查询到的用户的List对象,和总条数返回到页面中,将其封装在一个map中了,哎,就这么简单,这个Map在前台就以Json格式解析了。具体怎样解析,那都是前端程序员的事情了,当然了,没前端你就自己解析吧,很简单的。

有些人就问了,你这个真是太麻烦了 如果我就返回两个信息,难道也要封装到Object中吗?例如我返回给前台就{["result","1"],["msg","失败!"]},难道我还需要封装到一个对象中?其实编程是很灵活的,Spring的大牛们当然也考虑的这个问题。请参考一下方法!

/**
     * 用户删除方法
     * 
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/userDelete.do", method = RequestMethod.POST)
    @ResponseBody
    public String userDelete(String ids) throws Exception {
        String mReturn = null;
        String mMsg = null;

        try {
            cUserInfoService.userInfoDelete(ids);
            mMsg = CodeTransferUtil.transferCode(DataConst.Del_Success);
            mReturn = JsonUtil.getJsonString(true, mMsg);
        } catch (SysContlException sException) {
            // 记录日志
            LogUtil.info(sException);
            // 编码转换
            mMsg = CodeTransferUtil.transferCode(sException.getMessage());
            // 处理
            mReturn = JsonUtil.getJsonString(false, mMsg);
        } catch (DaoException dException) {
            // 记录日志
            LogUtil.info(dException);
            // 编码转换
            mMsg = CodeTransferUtil.transferCode(dException.getMessage());
            // 处理
            mReturn = JsonUtil.getJsonString(false, mMsg);
        } catch (Exception e) {
            LogUtil.error(e);
            throw e;
        }
        return mReturn;
    }

这段代码就返回了一个Json格式的字符串,那么@ResponseBody注解就将其返回一个字符串,具体spring内部是用StringHttpMessageConverter而非Jackson的

MappingJacksonHttpMessageConverter了,这样字符串就会转换为Json格式的数据返回给前台了。简单的String,复杂的Object都有了明确的解决办法,这样就不会有问题了,这样的应用基本上都是应用在与前台ajax技术相结合上。

这样MVC部分就介绍完毕了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值