IDEA下建立SSM專案--helloSSM
helloSSM
使用IDEA 建立SSM專案
本例子gitHub 地址: https://github.com/hittun/helloSSM/tree/master
安裝 IntelliJ IDEA
- 官網下載: IntelliJ IDEA Ultimate 付費版本。
- 購買、試用或破解
IDEA 基本設定
-
設定外觀和字型大小(選用).
-
設定編輯器的快捷鍵(選用).keymap, 可以選擇為eclipse 模式.
-
程式碼提示和補充功能(選用).
settings -> Editor -> General -> Code Completion -> Case sensitive completion
stringBuffer
IntelliJ IDEA 是不會幫我們提示或是程式碼補充的,但是如果我們輸入StringBuffer
就可以進行程式碼提示和補充.如果想不區分大小寫的話,改為None
項即可. -
設定程式碼檢查等級(選用).
Inspections
為最高等級檢查,可以檢查單詞拼寫,語法錯誤,變數使用,方法之間呼叫等.Syntax
可以檢查單詞拼寫,簡單語法錯誤.None
不設定檢查. -
自動導包(建議).預設 IntelliJ IDEA 是沒有開啟自動 import 包的功能.
settings -> Editor -> General -> Auto Import
Optimize imports on the fly
,勾選該選項,IntelliJ IDEA 將在我們書寫程式碼的時候自動幫我們優化匯入的包,比如自動去掉一些沒有用到的包; 選項-Add unambigupus imports on the fly
, IntelliJ IDEA 將在我們書寫程式碼的時候自動幫我們匯入需要用到的包。但是對於那些同名的包,還是需要手動 Alt + Enter 進行匯入的,IntelliJ IDEA 目前還無法智慧到替我們做判斷. -
省電模式
(可選).IntelliJ IDEA 有一種叫做省電模式
的狀態,開啟這種模式之後 IntelliJ IDEA 會關掉程式碼檢查和程式碼提示等功能.所以一般我也會認為這是一種閱讀模式
-
全域性編碼設定(必須).
File -> Other Settings -> Default Settings -> Editor -> File Encodings
三處Encoding 選為UTF-8. -
工程編碼設定(可選).
File -> Settings->Editor -> File Encodings
同理. -
檔案編碼設定(可選).開啟需要設定編碼的檔案, 在右下角進行設定.
-
Maven設定(建議).
File -> Other Settings -> Default Settings->Build, Execution, Deployment ->Build Tools -> Maven
. Maven home directory - maven 安裝路徑; User settings file - settings.xml 路徑; local repository - 本地倉庫位置. - JDK設定(必須).
File -> Other Settings -> Default Project Structure
參考:
http://blog.csdn.net/yelove1990/article/details/51541327
http://blog.csdn.net/qq_27093465/article/details/52918873
http://blog.csdn.net/frankcheng5143/article/details/50779149
Maven 基本設定
開啟 settings.xml
- 設定本地倉庫位置(建議)
<localRepository>E:\sundry\maven\repo</localRepository>
- 1
- 配置映象(建議)
<!-- 阿里雲倉庫 -->
<mirror>
<id>alimaven</id>
<mirrorOf>central</mirrorOf>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/repositories/central/</url>
</mirror>
<!-- 中央倉庫1 -->
<mirror>
<id>repo1</id>
<mirrorOf>central</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://repo1.maven.org/maven2/</url>
</mirror>
<!-- 中央倉庫2 -->
<mirror>
<id>repo2</id>
<mirrorOf>central</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://repo2.maven.org/maven2/</url>
</mirror>
<mirror>
<id>ibiblio</id>
<mirrorOf>central</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://mirrors.ibiblio.org/pub/mirrors/maven2/</url>
</mirror>
<mirror>
<id>jboss-public-repository-group</id>
<mirrorOf>central</mirrorOf>
<name>JBoss Public Repository Group</name>
<url>http://repository.jboss.org/nexus/content/groups/public</url>
</mirror>
<!-- 中央倉庫在中國的映象 -->
<mirror>
<id>maven.net.cn</id>
<name>oneof the central mirrors in china</name>
<url>http://maven.net.cn/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
- 設定代理(可選)
<proxy>
<id>my-proxy</id>
<active>true</active>
<protocol>http</protocol>
<host>10.18.97.76</host>
<port>3128</port>
<nonProxyHosts>127.0.0.1</nonProxyHosts>
<!--
<username>shihuan</username>
<password>123456</password>
-->
</proxy>
儲存,重啟IDE生效.
使用IDEA 搭建SSM 框架
參考: https://www.cnblogs.com/hackyo/p/6646051.html
需要的環境:
- idea 2017
- jdk 1.8
- Maven 3
步驟1 使用idea新建一個Maven webapp專案
File -> New -> Project -> Maven -> 確認JDK; 勾選Create from archetype; 在列表中選擇 maven-archetype-webapp -> Next -> GroupId:www.hello.com; Artifactid: hellossm; -> Next -> 確認 directory、file、replsitory -> Next -> 確認資訊 -> Finish
報錯: [ERROR] Maven execution terminated abnormally (exit code 1) 這個問題是常見的.檢測是不是網路的問題.右擊專案名 -> remove Modoule -> 退出IDE -> 去工作區間刪除專案 -> 啟動IDE 在歡迎頁面×了該專案 -> 重新進行步驟1.
第一次搭建可能會很慢, 一次未必成功.
建立成功後右上角會提示:Maven projects need to be imported .點選Enable Auto-Import,以後更改pom檔案後就會自動下載依賴包了.
控制檯成功資訊:
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 51.253 s
[INFO] Finished at: 2017-11-23T15:53:18+08:00
[INFO] Final Memory: 19M/172M
[INFO] ------------------------------------------------------------------------
[INFO] Maven execution finished
專案目錄結構:
helloSSM
│ helloSSM.iml
│ pom.xml
│
├─.idea
│ │ compiler.xml
│ │ encodings.xml
│ │ misc.xml
│ │ modules.xml
│ │ workspace.xml
│ │
│ ├─artifacts
│ │ helloSSM_war.xml
│ │ helloSSM_war_exploded.xml
│ │
│ ├─dictionaries
│ │ wuyanhui.xml
│ │
│ ├─inspectionProfiles
│ │ Project_Default.xml
│ │
│ └─libraries
│ Maven__junit_junit_3_8_1.xml
│
└─src
└─main
├─resources
└─webapp
│ index.jsp
│
└─WEB-INF
web.xml
步驟2 搭建目錄結構
helloSSM
│ helloSSM.iml
│ pom.xml
│
├─.idea
│ │ compiler.xml
│ │ encodings.xml
│ │ misc.xml
│ │ modules.xml
│ │ workspace.xml
│ │
│ ├─artifacts
│ │ helloSSM_war.xml
│ │ helloSSM_war_exploded.xml
│ │
│ ├─dictionaries
│ │ wuyanhui.xml
│ │
│ ├─inspectionProfiles
│ │ Project_Default.xml
│ │
│ └─libraries
│ Maven__junit_junit_3_8_1.xml
│
└─src
├─main
│ ├─java
│ │ └─com.hello
│ │ ├─controller
│ │ │ UserController.java
│ │ │
│ │ ├─dao
│ │ │ IUserDao.java
│ │ │
│ │ ├─model
│ │ │ User.java
│ │ │
│ │ └─service
│ │ │ IUserService.java
│ │ │
│ │ └─impl
│ │ UserServiceImpl.java
│ │
│ ├─resources
│ │ │ jdbc.properties
│ │ │ logback.xml
│ │ │ spring-mvc.xml
│ │ │ spring-mybatis.xml
│ │ │
│ │ ├─mapper
│ │ │ UserDao.xml
│ │ │
│ │ └─sql
│ │ helloSSM.sql
│ │
│ └─webapp
│ │ index.html
│ │
│ └─WEB-INF
│ │ web.xml
│ │
│ └─views
└─test
└─java
└─com
└─hello
├─controller
└─dao
IUserDaoTest.java
注意: 新建檔案如果找不到Class 格式.我們把java 資料夾設定為source , 再建立就有.clss 檔案格式了.
我們可以根據對專案的任意目錄進行這五種目錄型別標註,這個知識點非常非常重要,必須會。
-
Sources
一般用於標註類似 src 這種可編譯目錄。有時候我們不單單專案的 src 目錄要可編譯,還有其他一些特別的目錄也許我們也要作為可編譯的目錄,就需要對該目錄進行此標註。只有 Sources 這種可編譯目錄才可以新建 Java 類和包,這一點需要牢記。 ** -
Tests
一般用於標註可編譯的單元測試目錄。在規範的 maven 專案結構中,頂級目錄是 src,maven 的 src 我們是不會設定為 Sources 的,而是在其子目錄 main 目錄下的 java 目錄,我們會設定為 Sources。而單元測試的目錄是 src - test - java,這裡的 java 目錄我們就會設定為 Tests,表示該目錄是作為可編譯的單元測試目錄。一般這個和後面幾個我們都是在 maven 專案下進行配置的,但是我這裡還是會先說說。從這一點我們也可以看出 IntelliJ IDEA 對 maven 專案的支援是比徹底的。 -
Resources
一般用於標註資原始檔目錄。在 maven 專案下,資源目錄是單獨劃分出來的,其目錄為:src - main -resources,這裡的 resources 目錄我們就會設定為 Resources,表示該目錄是作為資源目錄。資源目錄下的檔案是會被編譯到輸出目錄下的。 -
Test Resources
一般用於標註單元測試的資原始檔目錄。在 maven 專案下,單元測試的資源目錄是單獨劃分出來的,其目錄為:src - test -resources,這裡的 resources 目錄我們就會設定為 Test Resources,表示該目錄是作為單元測試的資源目錄。資源目錄下的檔案是會被編譯到輸出目錄下的。 -
Excluded
一般用於標註排除目錄。被排除的目錄不會被 IntelliJ IDEA 建立索引,相當於被 IntelliJ IDEA 廢棄,該目錄下的程式碼檔案是不具備程式碼檢查和智慧提示等常規程式碼功能。
通過上面的介紹,我們知道對於非 maven 專案我們只要會設定 src 即可。
參考: http://blog.csdn.net/qq_27093465/article/details/52912444
步驟3 配置檔案內容
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">
<modelVersion>4.0.0</modelVersion>
<groupId>www.hello.com</groupId>
<artifactId>helloSSM</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>helloSSM Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<!-- 設定專案編碼編碼 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- spring版本號 -->
<spring.version>4.3.5.RELEASE</spring.version>
<!-- mybatis版本號 -->
<mybatis.version>3.4.1</mybatis.version>
</properties>
<dependencies>
<!-- java ee -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
</dependency>
<!-- 單元測試 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- 實現slf4j介面並整合 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.2</version>
</dependency>
<!-- JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
<!-- 資料庫 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
<scope>runtime</scope>
</dependency>
<!-- 資料庫連線池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring整合包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</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-web</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-test</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
<build>
<finalName>helloSSM</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<!-- 設定JDK版本 -->
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
設定好後,Maven會自動更新依賴, 可以注意右下方的資訊.
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
這裡可以控制輸出格式和內容,有興趣的可以自己設定
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
#資料庫地址
jdbc.url=jdbc:mysql://localhost:3306/hellossm?useUnicode=true&characterEncoding=utf8
#使用者名稱
jdbc.username=root
#密碼
jdbc.password=123
#最大連線數
c3p0.maxPoolSize=30
#最小連線數
c3p0.minPoolSize=10
#關閉連線後不自動commit
c3p0.autoCommitOnClose=false
#獲取連線超時時間
c3p0.checkoutTimeout=10000
#當獲取連線失敗重試次數
c3p0.acquireRetryAttempts=2
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.hello.service"/>
<!-- 配置資料庫相關引數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.hello.model"/>
<!-- 掃描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.hello.dao"/>
</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
<?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.hello.controller"/>
<!-- 開啟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=".jsp"/>
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>helloSSM</display-name>
<description>helloSSM_Alpha_0.0.1</description>
<!-- 編碼過濾器 -->
<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: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>
到這裡基本上環境就搭建完成了,下面開始測試
步驟4 測試
先匯入一份資料庫測試檔案
CREATE DATABASE /*!32312 IF NOT EXISTS*/`hellossm` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */;
USE `hellossm`;
/*Table structure for table `user` */
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '使用者ID',
`email` varchar(255) NOT NULL COMMENT '使用者郵箱',
`password` varchar(255) DEFAULT NULL COMMENT '使用者密碼',
`username` varchar(255) DEFAULT NULL COMMENT '使用者暱稱',
`role` varchar(255) DEFAULT NULL COMMENT '使用者身份',
`status` int(1) DEFAULT NULL COMMENT '使用者狀態',
`regTime` datetime DEFAULT NULL COMMENT '註冊時間',
`regIp` varchar(255) DEFAULT NULL COMMENT '註冊IP',
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 CHECKSUM=1;
/*Data for the table `user` */
insert into `user`(`id`,`email`,`password`,`username`,`role`,`status`,`regTime`,`regIp`) values (1,'[email protected]','1223','helloKang','root',1,'2017-03-28 09:40:31','127.0.0.1');
UserController
package com.hello.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hello.model.User;
import com.hello.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* project helloSSM
* authod wuyanhui
* datetime 2017/11/23 16:16
* desc
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private IUserService userService;
@RequestMapping("/showUser.do")
public void selectUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
long userId = Long.parseLong(request.getParameter("id"));
User user = this.userService.selectUser(userId);
ObjectMapper mapper = new ObjectMapper();
response.getWriter().write(mapper.writeValueAsString(user));
response.getWriter().close();
}
}
IUserDao
package com.hello.dao;
import com.hello.model.User;
/**
* project helloSSM
* authod wuyanhui
* datetime 2017/11/23 16:17
* desc
*/
public interface IUserDao {
User selectUser(long id);
}
User
package com.hello.model;
import java.util.Date;
/**
* project helloSSM
* authod wuyanhui
* datetime 2017/11/23 16:17
* desc
*/
public class User {
private long id;
private String email;
private String password;
private String username;
private String role;
private int status;
private Date regTime;
private String regIp;
public User() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getRegTime() {
return regTime;
}
public void setRegTime(Date regTime) {
this.regTime = regTime;
}
public String getRegIp() {
return regIp;
}
public void setRegIp(String regIp) {
this.regIp = regIp;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", email='" + email + '\'' +
", password='" + password + '\'' +
", username='" + username + '\'' +
", role='" + role + '\'' +
", status=" + status +
", regTime=" + regTime +
", regIp='" + regIp + '\'' +
'}';
}
}
IUserService
package com.hello.service;
import com.hello.model.User;
public interface IUserService {
public User selectUser(long userId);
}
UserServiceImpl
package com.hello.service.impl;
import com.hello.dao.IUserDao;
import com.hello.model.User;
import com.hello.service.IUserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* project helloSSM
* authod wuyanhui
* datetime 2017/11/23 16:17
* desc
*/
@Service("userService")
public class UserServiceImpl implements IUserService {
@Resource
private IUserDao userDao;
@Override
public User selectUser(long userId) {
return this.userDao.selectUser(userId);
}
}
UserDao.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.hello.dao.IUserDao">
<select id="selectUser" resultType="User" parameterType="long">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
然後新建個測試類,來測試mybatis
IUserDaoTest
package com.hello.dao;
import com.hello.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* project helloSSM
* authod wuyanhui
* datetime 2017/11/23 16:45
* desc
*/
// 載入spring配置檔案
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-mybatis.xml"})
public class IUserDaoTest {
@Autowired
private IUserDao dao;
@Test
public void testSelectUser() throws Exception {
long id = 1;
User user = dao.selectUser(id);
System.out.println(user.getUsername());
}
}
執行後結果應該是會在控制檯輸出id為1的使用者名稱.
繼續新建個頁面來測試springmvc和mybatis
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", "user/showUser.do", 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>
新建完成後配置專案執行環境,點選Run-Edit Configurations…
點選加號新建執行環境,選擇Tomcat Server-Local
選中新建好的伺服器,右邊選擇Deployment,點選加號-Atifact…
選擇第二項 helloSSM:war exploded
然後在右邊Application context配置你的專案名/hellossm
最後執行專案,專案會開啟裡瀏覽器且訪問http://localhost:8080/hellossm/
,在開啟的頁面中點選按鈕測試,成功的話會在頁面上顯示id為1的使用者資訊{"id":1,"email":"[email protected]","password":"1223","username":"helloKang","role":"root","status":1,"regTime":1490665231000,"regIp":"127.0.0.1"}
IDEA 通過 git 把專案上傳到 gitHub
本地安裝好git,並配置合理的SSH key
IntelliJ IDEA->Performance->Version Control->git 將自己安裝git的可執行檔案路徑填入Path to Git executable
選擇CVS 找到 Share Project 輸入賬號密碼即可.
本例子gitHub 地址: https://github.com/hittun/helloSSM/tree/master
轉自:https://blog.csdn.net/hunter_wyh/article/details/78620547