springMVC hibernate mybatis

来源:互联网 发布:linux用户权限命令 编辑:程序博客网 时间:2024/06/17 22:00

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