SpringMVC,Spring,Hibernate,Mybatis架构开发搭建之SpringMVC部分

辞职待业青年就是有很多时间来写博客,以前在传统行业技术强度相对不大,不处理大数据,也不弄高并发的,所以学不到什么高端编程技术和架构方法,那么我自己就琢磨搞一个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.jspwelcome-file>
    welcome-file-list>
    
    <filter>
        <filter-name>Spring character encoding filterfilter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        filter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>Spring character encoding filterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:config/applicationContext*.xmlparam-value>
    context-param>

    
    <listener>
        <listener-class>
            org.springframework.web.util.Log4jConfigListener
        listener-class>
    listener>
    
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        listener-class>
    listener>
    
    
    <servlet>
        <servlet-name>newframeservlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        servlet-class>
        <load-on-startup>1load-on-startup>
    servlet>

  <servlet-mapping>
        <servlet-name>newframeservlet-name>
        <url-pattern>*.dourl-pattern>
  servlet-mapping>
 
    
    <context-param>
        <param-name>webAppRootKeyparam-name>
        <param-value>myapp.rootparam-value>
    context-param>

    <context-param>
        <param-name>log4jConfigLocationparam-name>
        <param-value>classpath:log4j.propertiesparam-value>
    context-param>
    <session-config>
        <session-timeout>15session-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>contextConfigLocationparam-name>
        <param-value>/WEB-INF/config/applicationContext-mvc.xmlparam-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">

    
    <mvc:annotation-driven>mvc:annotation-driven>

<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> <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> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8value> list> property> bean> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.lang.Exception">common/errorprop> <prop key="java.lang.Throwable">common/errorprop> props> property> <property name="statusCodes"> <props> <prop key="errors/500">500prop> <prop key="errors/404">404prop> props> property> <property name="warnLogCategory" value="WARN">property> <property name="defaultErrorView" value="../error">property> <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 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 getUsers(UserInfo userInfo,
            @RequestParam String page, @RequestParam String rows)
            throws Exception {

        // 获得总条数
        int totalNum = cUserInfoService.getUserCount();
        // 获得查询到的用户
        List userList = cUserInfoService.getUsers(userInfo, page,
                rows);
        Map mMap = new HashMap();
        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部分就介绍完毕了,如果有任何问题欢迎留言,互相学习互相进步才是写博客的关键,希望踊跃喷我~

 
 
  

转载于:https://www.cnblogs.com/zm112358/p/3238588.html

你可能感兴趣的:(SpringMVC,Spring,Hibernate,Mybatis架构开发搭建之SpringMVC部分)