一、建立一张简单的User表
1 CREATE TABLE `users` ( 2 `id` int(20) NOT NULL AUTO_INCREMENT, 3 `name` varchar(20) NOT NULL, 4 `age` int(20) DEFAULT NULL, 5 PRIMARY KEY (`id`) 6 ) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8; 7 8 -- ---------------------------- 9 -- Records of users 10 -- ---------------------------- 11 INSERT INTO `users` VALUES ('1', '杜崇', '10'); 12 INSERT INTO `users` VALUES ('2', '黄春宇', '12'); 13 INSERT INTO `users` VALUES ('11', '文杰', '2'); 14 INSERT INTO `users` VALUES ('12', '何亮', '20'); 15 INSERT INTO `users` VALUES ('13', '超哥', '25'); 16 INSERT INTO `users` VALUES ('14', '阿宝', '10');
二、用myeclipse建立一个web工程ssi
2.1、jar包
2.2目录结构
2.3、springmvc的核心servlet ssi-servlet.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xmlns:aop="http://www.springframework.org/schema/aop" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd 9 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 10 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> 11 12 <context:component-scan base-package="org.ssi.controller"/> 13 <!--自动注册解析器和适配器--> 14 <mvc:annotation-driven/> 15 <mvc:default-servlet-handler /> 16 <aop:aspectj-autoproxy proxy-target-class="true" /> 17 <!-- 视图解析器的分配器 --> 18 <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> 19 <!--先检查请求的后缀名,如果没有匹配的,则spring检查请求头里面设置的 ContentType 来找适合的 mediaType来返回一种 mediaType 20 mediaTypes这个属性存储了 你请求后缀名 或者 参数 所对应 的mediaType 21 --> 22 <property name="mediaTypes"> 23 <map> 24 <entry key="atom" value="application/atom+xml"/> 25 <entry key="html" value="text/html"/> 26 <entry key="json" value="application/json"/> 27 </map> 28 </property> 29 <!--具体的解析器 --> 30 <property name="viewResolvers"> 31 <list> 32 <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/> 33 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 34 <property name="prefix" value="/jsp/"/> 35 <property name="suffix" value=".jsp"/> 36 </bean> 37 </list> 38 </property> 39 </bean> 40 41 </beans>
2.4、 web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> 3 <display-name></display-name> 4 <welcome-file-list> 5 <welcome-file>index.jsp</welcome-file> 6 </welcome-file-list> 7 8 <servlet> 9 <servlet-name>ssi</servlet-name> 10 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 11 <load-on-startup>1</load-on-startup> 12 </servlet> 13 14 <servlet-mapping> 15 <servlet-name>ssi</servlet-name> 16 <url-pattern>/</url-pattern> 17 </servlet-mapping> 18 19 <filter> 20 <filter-name>CharacterEncodingFilter</filter-name> 21 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 22 <init-param> 23 <param-name>encoding</param-name> 24 <param-value>utf-8</param-value> 25 </init-param> 26 </filter> 27 28 <filter-mapping> 29 <filter-name>CharacterEncodingFilter</filter-name> 30 <url-pattern>/*</url-pattern> 31 </filter-mapping> 32 33 <listener> 34 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 35 </listener> 36 37 <context-param> 38 <param-name>contextConfigLocation</param-name> 39 <param-value> 40 classpath:applicationContext.xml 41 </param-value> 42 </context-param> 43 44 <session-config> 45 <session-timeout>0</session-timeout> 46 </session-config> 47 </web-app>
2.5、conf.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 <typeAliases> 6 <typeAlias type="org.ssi.model.User" alias="User"/> 7 </typeAliases> 8 </configuration>
2.6、配置spring容器 applicationContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd 8 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd 10 "> 11 <!-- 加载数据库属性配置文件 12 <context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true"/> 13 --> 14 15 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 16 <!-- 17 <property name="driverClassName" value="${jdbc.driver}"></property> 18 <property name="url" value="${jdbc.url}"></property> 19 <property name="password" value="${jdbc.password}"></property> 20 <property name="username" value="${jdbc.username}"></property> 21 --> 22 <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> 23 <property name="url" value="jdbc:mysql://localhost:3306/mybatis"></property> 24 <property name="username" value="root"></property> 25 <property name="password" value="root"></property> 26 <!--maxActive: 最大连接数量--> 27 <property name="maxActive" value="150"/> 28 <!--minIdle: 最小空闲连接--> 29 <property name="minIdle" value="5"/> 30 <!--maxIdle: 最大空闲连接--> 31 <property name="maxIdle" value="20"/> 32 <!--initialSize: 初始化连接--> 33 <property name="initialSize" value="30"/> 34 <!-- 连接被泄露时是否打印 --> 35 <property name="logAbandoned" value="true"/> 36 <!--removeAbandoned: 是否自动回收超时连接--> 37 <property name="removeAbandoned" value="true"/> 38 <!--removeAbandonedTimeout: 超时时间(以秒数为单位)--> 39 <property name="removeAbandonedTimeout" value="10"/> 40 <!--maxWait: 超时等待时间以毫秒为单位 1000等于60秒--> 41 <property name="maxWait" value="1000"/> 42 <!-- 在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位. --> 43 <property name="timeBetweenEvictionRunsMillis" value="10000"/> 44 <!-- 在每次空闲连接回收器线程(如果有)运行时检查的连接数量 --> 45 <property name="numTestsPerEvictionRun" value="10"/> 46 <!-- 1000 * 60 * 30 连接在池中保持空闲而不被空闲连接回收器线程--> 47 <property name="minEvictableIdleTimeMillis" value="10000"/> 48 </bean> 49 50 51 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 52 <property name="configLocation" value="classpath:conf.xml" /> 53 <property name="dataSource" ref="dataSource" /> 54 <property name="mapperLocations" value="classpath:org/ssi/mapper/*.xml" /> 55 </bean> 56 <!-- 配置扫描器 --> 57 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 58 <!-- 扫描org.ssi.dao这个包以及它的子包下的所有映射接口类 --> 59 <property name="basePackage" value="org.ssi.dao" /> 60 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> 61 </bean> 62 63 <!--配置事物 --> 64 <bean id="txManager" 65 class="org.springframework.jdbc.datasource.DataSourceTransactionManager "> 66 <property name="dataSource" ref="dataSource"/> 67 </bean> 68 <!-- 注解事务--> 69 <tx:annotation-driven transaction-manager="txManager" /> 70 <context:annotation-config /> 71 <!-- 72 --> 73 <context:component-scan base-package="org.ssi.service,org.ssi.dao," /> 74 </beans>
2.7、dao接口,不用提供实现类,实现类有mybatis实现
1 package org.ssi.dao; 2 3 import java.util.List; 4 5 import org.ssi.model.User; 6 7 8 public interface UserMapperI { 9 /** 10 * 增 11 * @param user 12 */ 13 public void addUser(User user); 14 /** 15 * 改 16 * @param user 17 */ 18 public void updateUser(User user); 19 /** 20 * 删 21 * @param id 22 */ 23 public void deleteUser(int id); 24 /** 25 * 查 26 * @param id 27 * @return 28 */ 29 public User getUser(int id); 30 /** 31 * 查所有 32 * @return 33 */ 34 public List<User> getAllUsers(); 35 36 }
与配置文件中的类文件以及路径相对应,
2.8、pojo类 user.java
1 package org.ssi.model; 2 3 public class User { 4 5 private int id; 6 private String name; 7 private int age; 8 9 public User(int id, String name, int age) { 10 super(); 11 this.id = id; 12 this.name = name; 13 this.age = age; 14 } 15 16 public User() { 17 super(); 18 } 19 20 public int getId() { 21 return id; 22 } 23 public void setId(int id) { 24 this.id = id; 25 } 26 public String getName() { 27 return name; 28 } 29 public void setName(String name) { 30 this.name = name; 31 } 32 public int getAge() { 33 return age; 34 } 35 public void setAge(int age) { 36 this.age = age; 37 } 38 39 @Override 40 public String toString() { 41 return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; 42 } 43 44 }
2.9、UserMapperI.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3 <!-- 4 为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的 5 例如namespace="org.ssi.dao.UserMapperI"就是org.ssi.dao(包名)+UserMapperI(userMapperI.xml文件去除后缀) 6 --> 7 <mapper namespace="org.ssi.dao.UserMapperI"> 8 <!-- <resultMap>标签用来处理pojo对象的属性与表字段之间的不匹配问题 9 <resultMap id="userResultMap" type="User"> 10 <id property="id" column="userid" /> 11 <result property="name" column="username" /> 12 <result property="age" column="age" /> 13 </resultMap> 14 --> 15 <!-- 16 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的, 17 不能够重复 使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型 18 resultType="org.mybatis.model.User"就表示将查询结果封装成一个User类的对象返回 19 User类就是users表所对应的实体类 20 --> 21 <!-- 22 根据id查询得到一个user对象 23 --> 24 <select id="getUser" parameterType="int" 25 resultType="User"> 26 select * from users where id=#{id} 27 </select> 28 29 <insert id="addUser" parameterType="User" > 30 insert into users(name ,age) values(#{name},#{age}) 31 </insert> 32 33 <delete id="deleteUser" parameterType="int"> 34 delete from users where id=#{id} 35 </delete> 36 37 <update id="updateUser" parameterType="User"> 38 update users set name=#{name},age=#{age} where id=#{id} 39 </update> 40 41 <select id="getAllUsers" resultType="User"> 42 select * from users 43 </select> 44 </mapper>
该xml文件中的各种操作的id必须要跟dao接口中的方法名字一一对应,否侧会报错。
按照以上配置,springmvc整合mybatis的整体架构已经完成,
三、编写代码进行测试
Controller控制器 SsiController.java
1 package org.ssi.controller; 2 3 import java.util.List; 4 5 import javax.servlet.http.HttpServletRequest; 6 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.stereotype.Controller; 9 import org.springframework.web.bind.annotation.PathVariable; 10 import org.springframework.web.bind.annotation.RequestMapping; 11 import org.springframework.web.bind.annotation.RequestMethod; 12 import org.ssi.dao.UserMapperI; 13 import org.ssi.model.User; 14 15 @Controller 16 @RequestMapping(value="/controller") 17 public class SsiController { 18 19 @Autowired 20 private UserMapperI umi; 21 private List<User> ulist; 22 23 @RequestMapping(value="/all",method = RequestMethod.GET) 24 public String uList(HttpServletRequest request){ 25 26 ulist=this.umi.getAllUsers(); 27 for (int i = 0; i < ulist.size(); i++) { 28 System.out.println(ulist.get(i)); 29 } 30 request.setAttribute("ulist",ulist); 31 return "allusers"; 32 33 } 34 35 36 @RequestMapping(value = "/addu", method = RequestMethod.POST) 37 public String addU(User u) { 38 39 this.umi.addUser(u); 40 return "redirect:all"; 41 } 42 43 @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) 44 public String deleteU(HttpServletRequest request,@PathVariable Integer id) { 45 46 this.umi.deleteUser(id); 47 return "redirect:/controller/all"; 48 } 49 50 @RequestMapping(value = "/get/{id}", method = RequestMethod.GET) 51 public String getUserById(HttpServletRequest request,@PathVariable Integer id) { 52 53 User u=this.umi.getUser(id); 54 request.setAttribute("user", u); 55 return "userinfo"; 56 } 57 58 @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) 59 public String updateU(HttpServletRequest request,@PathVariable Integer id,User u) { 60 61 User uu=this.umi.getUser(id); 62 uu.setName(u.getName()); 63 uu.setAge(u.getAge()); 64 this.umi.updateUser(uu); 65 return "redirect:/controller/all"; 66 } 67 } 68 69
3.1、测试新增
index.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>Add User</title> 13 <meta http-equiv="pragma" content="no-cache"> 14 <meta http-equiv="cache-control" content="no-cache"> 15 <meta http-equiv="expires" content="0"> 16 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 17 <meta http-equiv="description" content="This is my page"> 18 <!-- 19 <link rel="stylesheet" type="text/css" href="styles.css"> 20 --> 21 </head> 22 23 <body> 24 25 26 <form action="controller/addu" method="post"> 27 name : <input name="name" type="text"><br> 28 age : <input name="age" type="text"><br> 29 <input type="submit" value="submit"> 30 </form> 31 <br> 32 33 34 </body> 35 </html>
添加前:
添加:
添加后:
点击edit 19 奥巴马
1 userinfo.jsp 2 3 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 4 <% 5 String path = request.getContextPath(); 6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 7 %> 8 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 10 <html> 11 <head> 12 <base href="<%=basePath%>"> 13 14 <title>UserInfo</title> 15 16 <meta http-equiv="pragma" content="no-cache"> 17 <meta http-equiv="cache-control" content="no-cache"> 18 <meta http-equiv="expires" content="0"> 19 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 20 <meta http-equiv="description" content="This is my page"> 21 <!-- 22 <link rel="stylesheet" type="text/css" href="styles.css"> 23 --> 24 25 </head> 26 27 <body> 28 <p align="center"><font size="20">UserInfo Edit</font></p> 29 <div align="center"> 30 <form action="controller/update/${user.id}" method="post"> 31 Name :<input type="text" name="name" value="${user.name}"><br> 32 Age :<input type="text" name="age" value="${user.age }"><br> 33 <input type="submit" value="Usubmit"> 34 </form> 35 </div> 36 </body> 37 </html>