SpringMVC Mybatis整合
阿新 • • 發佈:2018-12-17
工程目錄樹
工程裡共2個配置檔案,分別是spring.xml,是spring和mybatis的配置檔案,還有一個是springMVC的配置檔案,此外有2個資原始檔:jdbc.propertis和log4j.properties.
步驟
建立Maven工程
- New->Maven Project->maven-archetype-webapp
- 右鍵工程->properties->Java Build Path->Libraries-JRE [JavaSE]->edit->1.8
- 右鍵工程->properties->Project Facets->Java->1.8
- Apply and Close
修改pom.xml
新增以下包
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <spring.version>4.3.15.RELEASE</spring.version> <mybatis.version>3.1.1</mybatis.version> <mybatis-spring.version>1.2.3</mybatis-spring.version> <mysql-connector-java.version>5.1.6</mysql-connector-java.version> <druid>1.0.12</druid> <jackson.version>2.5.4</jackson.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector-java.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid}</version> </dependency> <!-- json --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> </dependencies>
建立log4j.propertis
# Global logging configuration
log4j.rootLogger=INFO, CONSOLE
# Console output...
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%5p [%t] - %m%n
修改web.xml
在<web-app></web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 編碼 -->
<filter>
<filter-name>encodingFilter</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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- servlet for spring mvc container -->
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
web.xml指定了2個配置檔案,分別是spring.xml和springMVC.xml.
建立spring.xml
spring.xml的檔案目錄為src/main/resources/
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<context:component-scan base-package="com.service" />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}">
<property name="url" value="${url}">
<property name="username" value="${username}">
<property name="password" value="${password}">
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.pojo" />
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com/mapper/*.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mapper"/>
</bean>
</beans>
建立jdbc.propertis
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/how2java?useUnicode=true&characterEncoding=UTF-8
username=root
password=admin
建立springMVC.xml
SpringMVC.xml的檔案目錄為src/main/resources/
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置掃描的包 -->
<context:annotation-config />
<context:component-scan
base-package="com.controller">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 註冊HandlerMapper、HandlerAdapter兩個對映類 -->
<mvc:annotation-driven />
<!-- 訪問靜態資源 -->
<mvc:default-servlet-handler />
<!-- 檢視解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
建立Category類
package com.pojo;
public class Category {
private int id;
private String name;
public Category(){
}
public Category(String name,int id){
setId(id);
setName(name);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Category [id=" + id + ", name=" + name + "]";
}
}
建立CategoryMapper介面
package com.mapper;
import java.util.List;
import com.pojo.Category;
public interface CategoryMapper {
public int add(Category category);
public void delete(int id);
public Category get(int id);
public Category getFname(String name);
public int update(Category category);
public List<Category> list();
public int count();
}
建立CategoryMapper介面的對映檔案Category.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.CategoryMapper">
<insert id="add" parameterType="Category" >
insert into category_ ( name ) values (#{name})
</insert>
<delete id="delete" parameterType="Category" >
delete from category_ where id= #{id}
</delete>
<select id="get" parameterType="_int" resultType="Category">
select * from category_ where id= #{id}
</select>
<select id="getFname" parameterType="string" resultType="Category">
select * from category_ where name= #{name}
</select>
<update id="update" parameterType="Category" >
update category_ set id= #{id} ,name=#{name} where id=#{id}
</update>
<select id="list" resultType="Category">
select * from category_
</select>
</mapper>
建立CategoryService介面
package com.service;
import java.util.List;
import com.pojo.Category;
public interface CategoryService {
List<Category> list();
}
建立CategoryServiceImpl類
package com.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mapper.CategoryMapper;
import com.pojo.Category;
import com.service.CategoryService;
@Service
public class CategoryServiceImpl implements CategoryService{
@Autowired
CategoryMapper categoryMapper;
public List<Category> list(){
return categoryMapper.list();
}
}
建立CategoryController類
package com.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.pojo.Category;
import com.service.CategoryService;
@Controller
@RequestMapping("")
public class CategoryController {
@Autowired
CategoryService categoryService;
@RequestMapping("listCategory")
public ModelAndView listCategory(){
ModelAndView mav = new ModelAndView();
List<Category> cs= categoryService.list();
mav.addObject("cs", cs);
mav.setViewName("demo");
return mav;
}
}
建立demo.jsp
目錄為src/main/webapp/WEB-INF/
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<table align='center' border='1' cellspacing='0'>
<tr>
<td>id</td>
<td>name</td>
</tr>
<c:forEach items="${cs}" var="c" varStatus="st" >
<tr>
<td>${c.id}</td>
<td>${c.name}</td>
</tr>
</c:forEach>
</table>