首页 > 新闻动态 >  

新闻动态
NEWS

SpringMVC,Spring,Hibernate,Mybatis架构开辟搭建之SpringMVC

添加时间:2013-8-5 点击量:

  告退待业青年就是有很多时候来写博客,以前在传统行业技巧强度相对不大,不处理惩罚大数据,也不弄高并发的,所以学不到什么高端编程技巧和架构办法,那么我本身就揣摩搞一个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-appversion=2.5xmlns=http://java.sun.com/xml/ns/javaeexmlns:xsi=http://www.w3.org/2001/XMLSchema-instancexsi: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?><beansxmlns=http://www.springframework.org/schema/beansxmlns:xsi=http://www.w3.org/2001/XMLSchema-instancexmlns:context=http://www.springframework.org/schema/contextxmlns:mvc=http://www.springframework.org/schema/mvcxsi: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-scanbase-package=com.tansun.newframe.><context:include-filtertype=annotationexpression=org.springframework.stereotype.Controller/><context:exclude-filtertype=annotationexpression=org.springframework.stereotype.Service/></context:component-scan><!--使注解生效--><beanclass=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter><propertyname=messageConverters><list><refbean=mappingJacksonHttpMessageConverter/><beanclass= org.springframework.http.converter.StringHttpMessageConverter><propertyname= supportedMediaTypes><list><beanclass=org.springframework.http.MediaType><constructor-argindex=0value=text/><constructor-argindex=1value=plain/><constructor-argindex=2value=UTF-8/></bean><beanclass=org.springframework.http.MediaType><constructor-argindex=0value=/><constructor-argindex=1value=/><constructor-argindex=2value=UTF-8/></bean></list></property></bean></list></property></bean><!--springmvc的设备文件,它的定名规矩:web.xml里springmvc模块的名称+“-servlet.xml” 对模型视图名称的解析,即在模型视图名称添加前后缀 例如:Controller里返回一个名为test的逻辑视图名称,按照设备文件, 它终极找到的文件是/panges/test.jsp,即把前后缀拼装为一个路径。--><beanid=viewResolverclass=org.springframework.web.servlet.view.InternalResourceViewResolver><propertyname=prefixvalue=/WEB-INF/pages/></property><propertyname=suffixvalue=.jsp></property></bean><!--jaskson 用于前后台以json情势的数据互换,设置编码集为utf-8编码--><beanid=mappingJacksonHttpMessageConverterclass=org.springframework.http.converter.json.MappingJacksonHttpMessageConverter><propertyname=supportedMediaTypes><list><value>application/json;charset=UTF-8</value></list></property></bean><!--SpringMVC 异常处理惩罚机制--><beanid=exceptionResolverclass=org.springframework.web.servlet.handler.SimpleMappingExceptionResolver><propertyname=exceptionMappings><props><propkey=java.lang.Exception>common/error</prop><propkey=java.lang.Throwable>common/error</prop></props></property><propertyname=statusCodes><props><propkey=errors/500>500</prop><propkey=errors/404>404</prop></props></property><!--设置日记输出级别,不定义则默认不输出警告等错误日记信息--><propertyname=warnLogCategoryvalue=WARN></property><!--默认错误页面,当找不到上方mappings中指定的异常对应视图时,应用本默认设备--><propertyname=defaultErrorViewvalue=../error></property><!--默认HTTP状况码--><propertyname=defaultStatusCodevalue=500></property></bean></beans>

  基于以上设备,springMVC的根蒂根基设备应当算是完成了,简单写一个把握器。

  @Controller 注解为此类为controller

  @RequestMapping 注解类前,可以懂得为恳求URL的一个前置定名,在办法前可以懂得为恳求的后置定名,一下代码的恳求就是/newframe/test/getAllDemo.do

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

  @Controller@RequestMapping(value=/test)publicclassDemoControl { @Resource(name=demoService)publicDemoService cDemoService; @RequestMapping(value=/getAllDemo.do,method=RequestMethod.GET)publicModelAndView getAllDemo(){ ModelAndView tReturn=newModelAndView(test/test_list); List<Demo> mDemos =cDemoService.getAllDemo(); tReturn.addObject(demos, mDemos);returntReturn; }}

  重视,返回值为一个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编程了,落空了应用开源框架的意义,然则也有办法

  publicModelAndView 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) @ResponseBodypublicMap<String, Object>getUsers(UserInfo userInfo, @RequestParam String page, @RequestParam String rows)throwsException {//获得总条数inttotalNum =cUserInfoService.getUserCount();//获得查询到的用户List<UserInfoVo> userList =cUserInfoService.getUsers(userInfo, page, rows); Map<String, Object> mMap =newHashMap<String, Object>(); mMap.put(rows, userList); mMap.put(total, totalNum);returnmMap; }

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

  办法很简单 将查询到的用户的List对象,和总条数返回到页面中,将其封装在一个map中了,哎,就这么简单,这个Map在前台就以Json格局解析了。具体如何解析,那都是前端法度员的工作了,当然了,没前端你就本身解析吧,很简单的。

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

  /用户删除办法@paramid@return@throwsException/@RequestMapping(value= /userDelete.do, method =RequestMethod.POST) @ResponseBodypublicString userDelete(String ids)throwsException { 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);throwe; }returnmReturn; }

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

  MappingJacksonHttpMessageConverter了,如许字符串就会转换为Json格局的数据返回给前台了。简单的String,错杂的Object都有了明白的解决办法,如许就不会有题目了,如许的应用根蒂根基上都是应用在与前台ajax技巧相连络上。

  如许MVC项目组就介绍完毕了,若是有任何题目迎接留言,互相进修互相进步才是写博客的关键,踊跃喷我~

  无论对感情还是对生活,“只要甜不要苦”都是任性而孩子气的,因为我们也不完美,我们也会伤害人。正因为我们都不完美,也因为生活从不是事事如意,所以对这些“瑕疵”的收纳才让我们对生活、对他人的爱变得日益真实而具体。—— 汪冰《世界再亏欠你,也要敢于拥抱幸福》。详情请关注:http://www.gjprj.cn/news1.asp?id=2416

分享到: