在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

SpringMVC整合mybatis实例代码

2016-7-29 15:34| 发布者: zhangjf| 查看: 700| 评论: 0

摘要: MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。 一、逆向工程生成基础信息 ?xml version=1.0 encoding=UTF-8?!DOCTYPE generato ...

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。

一、逆向工程生成基础信息

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE generatorConfiguration
  3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  5. <generatorConfiguration>
  6. <context id="testTables" targetRuntime="MyBatis3">
  7. <commentGenerator>
  8. <!-- 是否去除自动生成的注释 true:是 : false:否 -->
  9. <property name="suppressAllComments" value="true" />
  10. </commentGenerator>
  11. <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
  12. <jdbcConnection driverClass="com.mysql.jdbc.Driver"
  13. connectionURL="jdbc:mysql://localhost:3307/mybatis" userId="root"
  14. password="jalja">
  15. </jdbcConnection>
  16. <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
  17. NUMERIC 类型解析为java.math.BigDecimal -->
  18. <javaTypeResolver>
  19. <property name="forceBigDecimals" value="false" />
  20. </javaTypeResolver>
  21. <!-- targetProject:生成PO类的位置 -->
  22. <javaModelGenerator targetPackage="com.jalja.springmvc_mybatis.model.pojo"
  23. targetProject=".src">
  24. <!-- enableSubPackages:是否让schema作为包的后缀 -->
  25. <property name="enableSubPackages" value="false" />
  26. <!-- 从数据库返回的值被清理前后的空格 -->
  27. <property name="trimStrings" value="true" />
  28. </javaModelGenerator>
  29. <!-- targetProject:mapper映射文件生成的位置 -->
  30. <sqlMapGenerator targetPackage="com.jalja.springmvc_mybatis.mapper"
  31. targetProject=".src">
  32. <!-- enableSubPackages:是否让schema作为包的后缀 -->
  33. <property name="enableSubPackages" value="false" />
  34. </sqlMapGenerator>
  35. <!-- targetPackage:mapper接口生成的位置 -->
  36. <javaClientGenerator type="XMLMAPPER"
  37. targetPackage="com.jalja.springmvc_mybatis.mapper"
  38. targetProject=".src">
  39. <!-- enableSubPackages:是否让schema作为包的后缀 -->
  40. <property name="enableSubPackages" value="false" />
  41. </javaClientGenerator>
  42. <!-- 指定数据库表 -->
  43. <table tableName="items"></table>
  44. <table tableName="orders"></table>
  45. <table tableName="orderdetail"></table>
  46. <table tableName="user"></table>
  47. </context>
  48. </generatorConfiguration>
  49. public static void main(String[] arhs) throws Exception{
  50. List<String> warnings = new ArrayList<String>();
  51. boolean overwrite = true;
  52. File configFile = new File("src.main.resources/generator.xml");
  53. ConfigurationParser cp = new ConfigurationParser(warnings);
  54. Configuration config = cp.parseConfiguration(configFile);
  55. DefaultShellCallback callback = new DefaultShellCallback(overwrite);
  56. MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
  57. myBatisGenerator.generate(null);
  58. }
复制代码

二、springMVC与Mybatis整合 各个配置文件

1.项目结构

2、各个文件的核心代码

a.web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://java.sun.com/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  5. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  6. <welcome-file-list>
  7. <welcome-file>index.jsp</welcome-file>
  8. </welcome-file-list>
  9. <context-param>
  10. <param-name>contextConfigLocation</param-name>
  11. <param-value> classpath:spring/applicationContext-*.xml </param-value>
  12. </context-param>
  13. <listener>
  14. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  15. </listener>
  16. <context-param>
  17. <param-name>log4jConfigLocation</param-name>
  18. <param-value>classpath:log4j.properties</param-value>
  19. </context-param>
  20. <context-param>
  21. <param-name>log4jRefreshInterval</param-name>
  22. <param-value>3000</param-value>
  23. </context-param>
  24. <listener>
  25. <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  26. </listener>
  27. <!-- post请求乱码 -->
  28. <filter>
  29. <filter-name>SpringEncodingFilter</filter-name>
  30. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  31. <init-param>
  32. <param-name>encoding</param-name>
  33. <param-value>UTF-8</param-value>
  34. </init-param>
  35. <init-param>
  36. <param-name>forceEncoding</param-name>
  37. <param-value>true</param-value>
  38. </init-param>
  39. </filter>
  40. <filter-mapping>
  41. <filter-name>SpringEncodingFilter</filter-name>
  42. <url-pattern>*.do</url-pattern>
  43. </filter-mapping>
  44. <!-- springMvc前端控制器 -->
  45. <servlet>
  46. <servlet-name>springMvc</servlet-name>
  47. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  48. <init-param>
  49. <!--
  50. contextConfigLocation加载 springMvc的配置文件(处理器适配器 ,映射器)
  51. 如果不配置默认加载的是 /WEB-INF/servlet名称-servlet.xml(springMvc-servlet.xml)
  52. -->
  53. <param-name>contextConfigLocation</param-name>
  54. <param-value>classpath:spring/springmvc.xml</param-value>
  55. </init-param>
  56. <load-on-startup>1</load-on-startup>
  57. </servlet>
  58. <servlet-mapping>
  59. <servlet-name>springMvc</servlet-name>
  60. <!--
  61. 1、*.do :DispatcherServlet 解析所有 *.do 结尾的访问
  62. 2、 / :DispatcherServlet解析所有请求(包括静态资源) 这种配置可以实现restful风格的url
  63. 3、/*: 这种配置最终要转发到一个jsp页面
  64. -->
  65. <url-pattern>*.do</url-pattern>
  66. </servlet-mapping>
  67. <!-- springMvc前端控制器 RestFul
  68. <servlet>
  69. <servlet-name>springMvc_rest</servlet-name>
  70. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  71. <init-param>
  72. <param-name>contextConfigLocation</param-name>
  73. <param-value>classpath:spring/applicationContext-springmvc.xml</param-value>
  74. </init-param>
  75. <load-on-startup>1</load-on-startup>
  76. </servlet>
  77. <servlet-mapping>
  78. <servlet-name>springMvc_rest</servlet-name>
  79. <url-pattern>/</url-pattern>
  80. </servlet-mapping>
  81. -->
  82. <session-config>
  83. <session-timeout>30</session-timeout>
  84. </session-config>
  85. </web-app>
复制代码

b、config/mybatis/applicationContext-mybatis.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
  3. <configuration>
  4. <!--
  5. 各个属性
  6. properties:
  7. setting(全局配置参数配置):mybatis运行时可以调整一些运行参数 例如:开启二级缓存、开启延迟加载
  8. typeAliases(类型别名): 在mapper.xml中定义parameterType 参数类型 resultType 返回类型时
  9. 需要指定类型的路径 不方便开发,我们开一针对 这些类型给其指定别名
  10. typeHandler(类型处理器):在mybatis 中是通过typeHandler 完成 jdbc类型与java类型的转化 ,mybatis 提供的处理器已可满足 开发需求
  11. objectFactory(对象工厂):
  12. plugins(插件):
  13. environments(环境集合属性对象):
  14. environment(环境子属性对象):
  15. transactionManager(事务管理):
  16. dataSource(数据源):
  17. mappers(映射器):
  18. -->
  19. <!-- 对事务的管理和连接池的配置 -->
  20. <!-- 延迟加载 -->
  21. <settings>
  22. <!-- 打开延迟加载 -->
  23. <setting name="lazyLoadingEnabled" value="true"/>
  24. <!-- 积极加载改为消极加载 -->
  25. <setting name="aggressiveLazyLoading" value="false"/>
  26. <!-- 开启二级缓存 -->
  27. <setting name="cacheEnabled" value="true"/>
  28. </settings>
  29. <typeAliases>
  30. <!-- 针对单个别名定义 -->
  31. <!-- <typeAlias type="com.jalja.myBatis.model.User" alias="user"/> -->
  32. <!--批量别名的定义 mybatis 自动扫描包中的类 别名就是类名(首字母大小写都可以) -->
  33. <package name="com.jalja.springmvc_mybatis.model.pojo"/>
  34. <package name="com.jalja.springmvc_mybatis.model.custom"/>
  35. <package name="com.jalja.springmvc_mybatis.model.vo"/>
  36. </typeAliases>
  37. <!--加载映射文件 -->
  38. <!-- <mappers> <mapper resource="com/jalja/spring_mybatis/mapper/UserMapper.xml"/> -->
  39. <!-- 和spring整合后 可以去掉
  40. <package name="com.jalja.spring_mybatis.mapper"/> </mappers>-->
  41. </configuration>
复制代码

c、config/spring/applicationContext-dao.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
  6. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  7. xsi:schemaLocation="http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
  9. http://www.springframework.org/schema/beans
  10. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context-3.2.xsd
  13. http://www.springframework.org/schema/mvc
  14. http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  15. http://www.springframework.org/schema/tx
  16. http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
  17. http://www.springframework.org/schema/cache
  18. http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
  19. <!-- 引入jdbc配置文件 -->
  20. <context:property-placeholder location="classpath:jdbc.properties"/>
  21. <!-- 对JDBC配置进行解密
  22. <bean id="propertyConfigurer" class="cn.com.sinobpo.project.wfjb.utils.EncryptablePropertyPlaceholderConfigurer">
  23. <property name="locations">
  24. <list>
  25. <value>classpath:resources/config/jdbc.properties</value>
  26. </list>
  27. </property>
  28. </bean> -->
  29. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  30. <property name="driverClassName">
  31. <value>${jdbc_driverClassName}</value>
  32. </property>
  33. <property name="url">
  34. <value>${jdbc_url}</value>
  35. </property>
  36. <property name="username">
  37. <value>${jdbc_username}</value>
  38. </property>
  39. <property name="password">
  40. <value>${jdbc_password}</value>
  41. </property>
  42. <!-- 连接池最大使用连接数 -->
  43. <property name="maxActive">
  44. <value>20</value>
  45. </property>
  46. <!-- 初始化连接大小 -->
  47. <property name="initialSize">
  48. <value>1</value>
  49. </property>
  50. <!-- 获取连接最大等待时间 -->
  51. <property name="maxWait">
  52. <value>60000</value>
  53. </property>
  54. <!-- 连接池最大空闲 -->
  55. <property name="maxIdle">
  56. <value>20</value>
  57. </property>
  58. <!-- 连接池最小空闲 -->
  59. <property name="minIdle">
  60. <value>3</value>
  61. </property>
  62. <!-- 自动清除无用连接 -->
  63. <property name="removeAbandoned">
  64. <value>true</value>
  65. </property>
  66. <!-- 清除无用连接的等待时间 -->
  67. <property name="removeAbandonedTimeout">
  68. <value>180</value>
  69. </property>
  70. <!-- 连接属性 -->
  71. <property name="connectionProperties">
  72. <value>clientEncoding=UTF-8</value>
  73. </property>
  74. </bean>
  75. <!-- spring和MyBatis完美整合 -->
  76. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  77. <property name="dataSource" ref="dataSource"/>
  78. <property name="configLocation" value="classpath:mybatis/applicationContext-mybatis.xml"/>
  79. </bean>
  80. <!--使用 mapper 代理 的方式 mapper扫描器 -->
  81. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  82. <!-- 扫描包路径 如果需要扫描多个包 ,中间使用半角逗号隔开 -->
  83. <property name="basePackage" value="com.jalja.springmvc_mybatis.mapper"/>
  84. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
  85. </bean>
  86. <!--声明式 事务管理 使用jdbc的事务管理 -->
  87. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  88. <property name="dataSource" ref="dataSource"></property>
  89. </bean>
  90. <!-- 配置事务通知-->
  91. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  92. <tx:attributes>
  93. <tx:method name="update*" propagation="REQUIRED"/>
  94. <tx:method name="save*" propagation="REQUIRED"/>
  95. <tx:method name="delete*" propagation="REQUIRED"/>
  96. <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
  97. <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
  98. </tx:attributes>
  99. </tx:advice>
  100. <!-- 配置事务的切点,并把事务切点和事务属性不关联起来AOP -->
  101. <aop:config>
  102. <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.jalja.springmvc_mybatis.service.impl.*.*(..))"/>
  103. </aop:config>
  104. </beans>
复制代码

d、config/spring/applicationContext-service.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
  6. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  7. xsi:schemaLocation="http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
  9. http://www.springframework.org/schema/beans
  10. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context-3.2.xsd
  13. http://www.springframework.org/schema/mvc
  14. http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  15. http://www.springframework.org/schema/tx
  16. http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
  17. http://www.springframework.org/schema/cache
  18. http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
  19. <bean id="itemsService" class="com.jalja.springmvc_mybatis.service.impl.ItemsServiceImpl"></bean>
  20. </beans>
复制代码

e、config/spring/springmvc.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
  6. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  7. xsi:schemaLocation="http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  9. http://www.springframework.org/schema/beans
  10. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  13. http://www.springframework.org/schema/mvc
  14. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
  15. http://www.springframework.org/schema/tx
  16. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  17. http://www.springframework.org/schema/cache
  18. http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
  19. <!--注解 处理器 映射器 -->
  20. <!-- 映射器 org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping springmvc3.1以前-->
  21. <!-- 映射器 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping springmvc3.1以后 -->
  22. <!-- 适配器 org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter springmvc3.1以前-->
  23. <!-- 适配器 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter springmvc3.1以后 -->
  24. <!--配置映射器和 适配器
  25. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
  26. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
  27. <!-- 开启注解 映射器和 适配器 这种方式默认加载了很多参数绑定的方法 例如 json转换解析器-->
  28. <mvc:annotation-driven/>
  29. <!-- 配置 Handler
  30. <bean class="com.jalja.springmvc_mybatis.controller.UserController"/>-->
  31. <!-- 注解 配置 基于组建扫描的方式 -->
  32. <context:component-scan base-package="com.jalja.springmvc_mybatis.controller" />
  33. <!-- 配置自定义参数解析器 -->
  34. <mvc:annotation-driven conversion-service="conversionService"/>
  35. <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
  36. <property name="converters">
  37. <list>
  38. <!-- 日期类型转换 -->
  39. <bean class="com.jalja.springmvc_mybatis.converter.CustomDateConverter"></bean>
  40. </list>
  41. </property>
  42. </bean>
  43. <!-- 全局异常处理器 -->
  44. <bean class="com.jalja.springmvc_mybatis.exception.CustomExceptionResolver"/>
  45. <!-- 文件上传 -->
  46. <!-- 支持上传文件 -->
  47. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  48. <!-- 文件大小 5M -->
  49. <property name="maxUploadSize" value="5242880"/>
  50. </bean>
  51. <!-- 使用 restFul 风格 编程 照成 的 静态资源 访问 问题 -->
  52. <!-- <mvc:resources mapping="/js/**" location="/resources/js/"/> -->
  53. <!-- springMVC拦截器的配置 -->
  54. <mvc:interceptors>
  55. <mvc:interceptor>
  56. <mvc:mapping path="/**" />
  57. <bean class="com.jalja.springmvc_mybatis.interceptor.LoginInterceptor" />
  58. </mvc:interceptor>
  59. </mvc:interceptors>
  60. <!-- 视图映射 jsp解析 默认使用jstl-->
  61. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  62. <!-- 默认使用 -->
  63. <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  64. <property name="prefix" value="/WEB-INF/jsp/" />
  65. <property name="suffix" value=".jsp" />
  66. </bean>
  67. </beans>
复制代码

f、config/jdbc.properties

  1. jdbc_driverClassName=com.mysql.jdbc.Driver
  2. jdbc_url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8
  3. jdbc_username=root
  4. jdbc_password=111111
复制代码

g、config/log4j.properties

  1. #在开发环境下的日志级别 要设置成debug,生成环境设置成info 或error
  2. log4j.rootLogger=debug, stdout
  3. log4j.logger.org.apache.ibatis=debug
  4. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  5. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  6. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
复制代码

h、com/jalja/springmvc_mybatis/controller/ItemsController.java

  1. package com.jalja.springmvc_mybatis.controller;
  2. import java.io.File;
  3. import java.util.List;
  4. import java.util.UUID;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.web.bind.annotation.PathVariable;
  9. import org.springframework.web.bind.annotation.RequestBody;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RequestMethod;
  12. import org.springframework.web.bind.annotation.RequestParam;
  13. import org.springframework.web.bind.annotation.ResponseBody;
  14. import org.springframework.web.multipart.MultipartFile;
  15. import com.jalja.springmvc_mybatis.exception.CustomException;
  16. import com.jalja.springmvc_mybatis.model.custom.ItemsCustom;
  17. import com.jalja.springmvc_mybatis.service.ItemsService;
  18. /**
  19. * 商品
  20. * @author PC003
  21. *conterver参数转换器 springMvc提供了很多参数转换器
  22. */
  23. @Controller
  24. @RequestMapping("/items") //窄化请求映射
  25. public class ItemsController {
  26. @Autowired ItemsService itemsService;
  27. @RequestMapping(value="/findItemsList")
  28. public String findItemsList(Model model) throws Exception{
  29. List<ItemsCustom> itemsList=itemsService.findItemsList(null);
  30. System.out.println(itemsList);
  31. model.addAttribute("itemsList", itemsList);
  32. return "itemsList";
  33. }
  34. @RequestMapping(value="/editItems", method={RequestMethod.POST,RequestMethod.GET}) //限制Http请求方式
  35. //@RequestParam 将请求参数 与 形式参数进行绑定 required:指定属性必须传入值 defaultValue:设置默认值
  36. public String editItems(Model model, @RequestParam(value="id",required=true,defaultValue="0") Integer itemsId) throws Exception{
  37. ItemsCustom itemsCustom=itemsService.findItemsById(itemsId);
  38. if(itemsCustom==null){
  39. throw new CustomException("商品不存在");
  40. }
  41. model.addAttribute("itemsCustom", itemsCustom);
  42. return "editItems";
  43. }
  44. @RequestMapping(value="/updateItems")
  45. public String editItemsSubmit(Integer id,ItemsCustom itemsCustom,MultipartFile itemsPic) throws Exception{
  46. String uploadFileName=itemsPic.getOriginalFilename();//获取上传的文件名
  47. if(itemsPic!=null && uploadFileName!=null && !uploadFileName.equals("")){
  48. String imagesPath="E:\develop\upload\images\";
  49. String newFileName=UUID.randomUUID()+uploadFileName.substring(uploadFileName.lastIndexOf("."),uploadFileName.length());
  50. File newFile=new File(imagesPath+newFileName);
  51. itemsPic.transferTo(newFile);//将内存中的数据写入磁盘
  52. itemsCustom.setPic(newFileName);
  53. }
  54. itemsService.updateItemsById(id, itemsCustom);
  55. return "redirect:findItemsList.do"; //重定向
  56. }
  57. //JSON的使用 @ResponseBody:将对像转json输出 @RequestBody:将请求参数转 java对象
  58. @RequestMapping(value="/jsonRequest")
  59. public @ResponseBody ItemsCustom jsonRequest(@RequestBody ItemsCustom itemsCustom) throws Exception{
  60. return itemsCustom;
  61. }
  62. //RestFul 风格 编程 /restFulRequest/{id}:表示将这个位置的参数传到 @PathVariable 指定的名称中
  63. @RequestMapping(value="/restFulRequest/{id}")
  64. public @ResponseBody ItemsCustom restFulRequest(@PathVariable("id") Integer id) throws Exception{
  65. ItemsCustom itemsCustom=itemsService.findItemsById(id);
  66. return itemsCustom;
  67. }
  68. }
复制代码

以上所述是小编给大家介绍的SpringMVC整合mybatis实例代码,希望对大家有所帮助,如果大家想了解更多资讯敬请关注程序员之家网站!

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-4 02:09

Copyright 2015-2025 djqfx

返回顶部