spring mvc + spring + mybatis整合
了解了下spring mvc 3.2,感觉比之前版本好用,很灵活。顺便与mybatis整合了。
主要实现点:
1. mybatis-3.2.2与spring 3.2.0整合,整合时只需要在applicationContext.xml里配mybatis一些信息,
关键代码:
applicationContext.xml
Xml代码
[*]<context:property-placeholder location="classpath:jdbc.properties"/>
[*]<bean id="dataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource" destroy-method="forceCloseAll">
[*] <property name="driver" value="${jdbc.driver}"/>
[*] <property name="url" value="${jdbc.url}"/>
[*] <property name="username" value="${jdbc.username}"/>
[*] <property name="password" value="${jdbc.password}"/>
[*]</bean>
[*]<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
[*] <property name="dataSource" ref="dataSource"/>
[*]</bean>
[*]<tx:annotation-driven/>
[*]<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
[*] <property name="dataSource" ref="dataSource"/>
[*] <property name="typeAliasesPackage" value="com.jayung.curriculum.domain"/>
[*]</bean>
[*]
[*]<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
[*] <property name="basePackage" value="com.jayung.curriculum.mapper"/>
[*]</bean>
用spring管理mybatis事务,无需写DAO的实现类了,代码很简洁,service层直接调用mybatis的mapper类(相当于DAO接口),增删改操作,只须在service对应的方法上加上@Transactional
Java代码
[*]@Transactional
[*]public void save(Student student) {
[*] studentMapper.insert(student);
[*]}
2. spring mvc
全面使用注解,非常简洁,在编码时,无需在xml与java代码来回切换,一个@Controller和@RequestMapping就代替了大量的xml配置,感觉很好。
写了两个拦截器,一个拦截学生是否登录,一个拦截管理员是否登录,使用spring拦截器代替Filter来检测是否登录,基于RequestMapping拦截比Filter更有效,还可以配置例外拦截白名单。
Xml代码
[*]<mvc:interceptors>
[*] <mvc:interceptor>
[*] <mvc:mapping path="/student/**"/>
[*] <mvc:mapping path="/courses"/>
[*] <bean class="com.jayung.curriculum.web.interceptor.LoginInterceptor"/>
[*] </mvc:interceptor>
[*] <mvc:interceptor>
[*] <mvc:mapping path="/console/**"/>
[*] <bean class="com.jayung.curriculum.web.interceptor.ConsoleInterceptor">
[*] <property name="excludeURIs">
[*] <list>
[*] <value>/console</value>
[*] <value>/console/login</value>
[*] </list>
[*] </property>
[*] </bean>
[*] </mvc:interceptor>
[*]</mvc:interceptors>
3. restful的url
实现类似于iteye的url http://www.iyunv.com/news/28054,
例如:http://localhost:8080/curriculum/student/1234,显示学号为1234的学生信息,http://localhost:8080/curriculum/student/1234/courses,显示学号为1234的所选的课,
http://localhost:8080/curriculum/console/student/1122/edit,编辑学号为1122学生的信息。
以前要实现这样的url,要借助于UrlRewriteFilter,现在用spring mvc可以原生实现这样的url,不过由于目前浏览器只支持post和get两种提交方式,rest全部实现还依赖rest相关包。
Java代码
[*]@RequestMapping("/student/{studentId}")
[*]public String view(@PathVariable String studentId, Model model) {
[*] model.addAttribute("student", studentService.view(studentId));
[*] return "/student/view";
[*]}
demo下载链接
spring_mvc___spring___mybatis.zip (7.1 MB)
页:
[1]