第一步: 建立maven專案


選擇maven(下圖是用idea自帶的maven,你也可以用你自己下載的maven,directory地址指向你自己的maven就行,setting和repository同理)


剛開始時間比較長,可以看到,用了有7分多鐘, 還是很快的

為了之後能夠快速的下載依賴包,我們要加一個官方庫的映象,因為maven的官方倉庫在國外,太慢了。 我們在你的.m2資料夾下的setting.xml中新增如下程式碼:
<mirror>
<id>alimaven</id>
<mirrorOf>central</mirrorOf>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/repositories/central/</url>
</mirror>
複製程式碼
具體位置如下圖所示

maven包下載好後,專案結構如下

第二步: 建立java包
可以看到, 缺少java包,在main上右鍵新建包


第三步:建立層級結構
到這裡先不要修改java包的狀態, 接著建立其他目錄結構,這麼做的主要目的是方便建立分級結構。
當改變java包的狀態後,service.impl會變成一個包的名字,這時候需要Rename以下這個包,先變成service,然後建立PersonService.java, 在建立impl包, 就好了
如果覺得麻煩可以在建立目錄的時候先不建立impl包



第四步:建立需要的檔案
接下來建立一系列的檔案, 然後在進行配置,先把骨架搭起來

第五步:填充檔案
被標稱黃色的部分是需要注意的, 如果更改了需要做相應的改動, 如果專案目錄跟這個一樣,就不需要改動
PersonController.java
package com.ssm.demo.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssm.demo.entity.Person;
import com.ssm.demo.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
@RequestMapping("/person")
public class PersonController {
@Autowired
private PersonService personService;
@RequestMapping("/selectPerson")
public void selectPerson(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
long personId = Long.parseLong(request.getParameter("id"));
Person person =personService.findPersonById(personId);
ObjectMapper mapper = new ObjectMapper();
response.getWriter().write(mapper.writeValueAsString(person));
response.getWriter().close();
}
}
複製程式碼
PersonMapperDao.java
package com.ssm.demo.dao;
import com.ssm.demo.entity.Person;
import org.springframework.stereotype.Repository;
@Repository
public interface PersonMapperDao {
Person findPersonById(long id);
}
複製程式碼
Person.java
package com.ssm.demo.entity;
public class Person {
private long id;
private String name;
private String email;
private int status;
//getter setter
@Override
public String toString(){
return this.getId()+"---"+this.getName()+"---"+
this.getEmail()+"---"+this.getStatus();
}
}
複製程式碼
PersonService.java
package com.ssm.demo.service;
import com.ssm.demo.entity.Person;
public interface PersonService {
Person findPersonById(long id);
}
複製程式碼
PersonServiceImpl.java
package com.ssm.demo.service.impl;
import com.ssm.demo.dao.PersonMapperDao;
import com.ssm.demo.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PersonServiceImpl implements PersonService {
@Autowired
private PersonMapperDao personMapperDao;
public Person findPersonById(long id) {
return personMapperDao.findPersonById(id);
}
}
複製程式碼
spring-mvc.xml
<?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: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">
<!-- 掃描web相關的bean -->
<context:component-scan base-package="com.ssm.demo"/>
<!-- 開啟SpringMVC註解模式 -->
<mvc:annotation-driven/>
<!-- 靜態資源預設servlet配置 -->
<mvc:default-servlet-handler/>
<!-- 配置jsp 顯示ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".html"/>
</bean>
</beans>
複製程式碼
spring-mybatis.xml
<?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"
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">
<!-- 掃描service包下所有使用註解的型別 -->
<context:component-scan base-package="com.ssm.demo"/>
<!-- 配置資料庫相關引數properties的屬性:${url} -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 資料庫連線池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
</bean>
<!-- 配置SqlSessionFactory物件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入資料庫連線池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 掃描model包 使用別名 -->
<property name="typeAliasesPackage" value="com.ssm.demo.entity"/>
<!-- 掃描sql配置檔案:mapper需要的xml檔案 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 配置掃描Dao介面包,動態實現Dao介面,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 給出需要掃描Dao介面包 -->
<property name="basePackage" value="com.ssm.demo.dao"/>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入資料庫連線池 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置基於註解的宣告式事務 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
複製程式碼
PersonMapper.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">
<!-- 設定為IUserDao介面方法提供sql語句配置 -->
<mapper namespace="com.ssm.demo.dao.PersonMapperDao">
<select id="findPersonById" resultType="Person" parameterType="long">
SELECT * FROM person WHERE id = #{id}
</select>
</mapper>
複製程式碼
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
#資料庫地址
jdbc.url=jdbc:mysql://localhost:3306/資料庫名?useUnicode=true&characterEncoding=utf8
#使用者名稱
jdbc.username=資料庫賬號
#密碼
jdbc.password=資料庫密碼
#最大連線數
c3p0.maxPoolSize=30
#最小連線數
c3p0.minPoolSize=10
#關閉連線後不自動commit
c3p0.autoCommitOnClose=false
#獲取連線超時時間
c3p0.checkoutTimeout=10000
#當獲取連線失敗重試次數
c3p0.acquireRetryAttempts=2
複製程式碼
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<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>Archetype Created Web Application</display-name>
<!-- 編碼過濾器 -->
<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>
<!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置springMVC需要載入的配置檔案-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/config/spring/spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 匹配所有請求,此處也可以配置成 *.do 形式 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
複製程式碼
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<script>
function selectUser() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("test").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "person/selectPerson", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("id=1");
}
</script>
<body>
<p id="test">Hello World!</p>
<button type="button" onclick="selectUser()">onclick test</button>
</body>
</html>
複製程式碼
第六步: 配置tomcat
先clean一下, 然後package一下








輸入請求的跟地址, 專案名

第七步: 資料庫建立, 表的建立, 插入資料
navicat 圖形化介面建立資料庫,然後修改jdbc.properties檔案的資料庫名稱為自己建立的資料庫,然後建立表
CREATE TABLE person (
id int(11) NOT NULL AUTO_INCREMENT,
email varchar(255) NOT NULL,
name varchar(255) NOT NULL,
status int(1) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY email (email) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO person VALUES ('1', '123456qq.com', 'zzz', '0');
SET FOREIGN_KEY_CHECKS=1;
複製程式碼

第八步: 啟動tomcat, 彈出頁面點選按鈕, 會出現查詢內容

