IDEA版本:IDEA 2017.2.5
JDK版本:JDK1.8
测试数据库表sql自取如下:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` varchar(10) NOT NULL,
`name` varchar(20) default NULL,
`sex` varchar(5) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '张三', '男');
INSERT INTO `user` VALUES ('2', '张三2', '女');
INSERT INTO `user` VALUES ('3', '张三3', '男');
INSERT INTO `user` VALUES ('4', '张三4', '男');
INSERT INTO `user` VALUES ('5', '张三5', '男');
INSERT INTO `user` VALUES ('6', '张三6', '男');
INSERT INTO `user` VALUES ('7', '张三7', '男');
INSERT INTO `user` VALUES ('8', '张三8', '男');
废话不多说,直入正题。
步骤
一:创建Maven webapp项目
把项目文件建起来,如图所示(注意,test目录和main平级),并对文件夹进行标识让IDEA系统系别。
二:配置文件内容
pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>spaceartifactId>
<groupId>testSSMgroupId>
<version>1.0-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<packaging>warpackaging>
<name>kakaname>
<groupId>com.kakagroupId>
<artifactId>kakaartifactId>
<build>
<plugins>
<plugin>
<groupId>org.mortbay.jettygroupId>
<artifactId>maven-jetty-pluginartifactId>
<version>6.1.7version>
<configuration>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>8888port>
<maxIdleTime>30000maxIdleTime>
connector>
connectors>
<webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}
webAppSourceDirectory>
<contextPath>/contextPath>
configuration>
plugin>
<plugin>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-maven-pluginartifactId>
<version>1.3.2version>
plugin>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<configuration>
<source>1.8source>
<target>1.8target>
configuration>
plugin>
plugins>
<finalName>kakafinalName>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.xmlinclude>
<include>**/*.propertiesinclude>
includes>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.xmlinclude>
<include>**/*.propertiesinclude>
includes>
resource>
resources>
build>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<spring.version>4.3.5.RELEASEspring.version>
<mybatis.version>3.4.1mybatis.version>
properties>
<dependencies>
<dependency>
<groupId>javaxgroupId>
<artifactId>javaee-apiartifactId>
<version>7.0version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.8.7version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.41version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
dependencies>
project>
logback.xml(用log4j也行哦~),自行配置输出
<configuration debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%npattern>
encoder>
appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
root>
configuration>
jdbc.properties
jdbc.driverLocation=D:\\mavenRep\\repository\\mysql\\mysql-connector-java\\5.1.29\\mysql-connector-java-5.1.29.jar
jdbc.driverClasss=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/kaka?useUnicode=true&characterEncoding=UTF-8
#username直接声明会与系统jvm冲突,不信你试试~
jdbc.username=xxx
jdbc.password=xxx
开启mybatis逆向工程,生成dao(即mapper)和model(即po)
先写逆向工程配置文件generatorConfig.xml
<generatorConfiguration>
<properties resource="jdbc.properties">properties>
<classPathEntry location="${jdbc.driverLocation}"/>
<context id="default" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
commentGenerator>
<jdbcConnection
driverClass="${jdbc.driverClasss}"
connectionURL="${jdbc.url}"
userId="${jdbc.username}"
password="${jdbc.password}">
jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
javaTypeResolver>
<javaModelGenerator targetPackage="com.kaka.model"
targetProject="src/main/java">
<property name="enableSubPackages" value="false"/>
<property name="constructorBased" value="true"/>
<property name="trimStrings" value="true"/>
<property name="immutable" value="false"/>
javaModelGenerator>
<sqlMapGenerator targetPackage="com.kaka.dao"
targetProject="src/main/java">
<property name="enableSubPackages" value="false"/>
sqlMapGenerator>
<javaClientGenerator targetPackage="com.kaka.dao"
targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="true"/>
javaClientGenerator>
<table tableName="user">table>
context>
generatorConfiguration>
Run/Debug Configuration注册maven运行项
spring-mybatis.xml
<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"
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">
<context:component-scan base-package="com.kaka.service"/>
<context:property-placeholder location="classpath*:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClasss}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com/kaka/dao/*.xml" />
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.kaka.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
beans>
spring-mvc.xml
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.kaka.controller"/>
<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/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>kakadisplay-name>
<description>kaka_Alpha_0.0.1description>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<servlet>
<servlet-name>SpringMVCservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-*.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
<async-supported>trueasync-supported>
servlet>
<servlet-mapping>
<servlet-name>SpringMVCservlet-name>
<url-pattern>*.dourl-pattern>
servlet-mapping>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
web-app>
三:临时测试一下数据访问能否成功
创建如下目录中的UserMapperTest.java文件
四:接下来可以进行web的开发咯~
首先,测试index.jsp
在webapp文件下创建index.jsp文件
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2017/11/11 0011
Time: 20:59
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>测试标题title>
head>
<body>
欢迎大家访问!
body>
html>
然后点击右上角的Edit Configuration…然后点击“+”号
创建tomcat,并部署(如下图所示,记得给汤姆猫起个名字哦)
看到了!成功访问了index.jsp,很激动!!!有木有!!!
最后,我们创建Controller和Service进行最后的冲刺!
UserService.java
package com.kaka.service;
import com.kaka.dao.UserMapper;
import com.kaka.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(String id){
return userMapper.selectByPrimaryKey(id);
}
}
UserController.java
package com.kaka.controller;
import com.kaka.model.User;
import com.kaka.service.UserService;
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;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("getUser")
public ModelAndView getUser(String id){
ModelAndView modelAndView = new ModelAndView();
User user = userService.getUserById(id);
modelAndView.addObject("user",user);
modelAndView.setViewName("user/getUser");
return modelAndView;
}
}
getUser.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2017/11/11 0011
Time: 21:15
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>测试getUsertitle>
head>
<body>
${user.id},${user.name},${user.sex}
body>
html>
Success!
bye~~