1、下載SpringMVC框架架包,下載地址:
點擊打開地址如圖所示,點擊下載即可
然后把相關的jar復制到lib下導入
2、MyBatis(3.4.2)下載
MyBatis中文文檔地址
下載解壓之后把jar復制到lib下導入,大概是這樣子的
3、jdbc連接庫還沒有下載。。。這個是5.1.41版本的。。。
解壓之后這樣子。。。
4、fastjson 阿里巴巴的json解析庫
版本是1.2.24 這個是托管到了github上面的,地址是:點擊進入
5、創建WebProject
注意下一步有個選項,如果不勾選,默認是不會生成web.xml的
6、項目創建完畢,把之前的包都弄進來。。
web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
<? xml version = "1.0" encoding = "UTF-8" ?> < web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id = "WebApp_ID" version = "3.1" > < display-name >CoolWeb</ display-name > < welcome-file-list > < welcome-file >index.html</ welcome-file > < welcome-file >index.htm</ welcome-file > < welcome-file >index.jsp</ welcome-file > < welcome-file >default.html</ welcome-file > < welcome-file >default.htm</ welcome-file > < welcome-file >default.jsp</ welcome-file > </ welcome-file-list > < servlet > < servlet-name >CoolWeb</ servlet-name > < servlet-class >org.springframework.web.servlet.DispatcherServlet</ servlet-class > < init-param > < param-name >contextConfigLocation</ param-name > <!-- <param-value>classpath:application-context.xml</param-value> --> < param-value >classpath:CoolWeb-servlet.xml</ param-value > </ init-param > <!-- classpath:只會到你的class路徑中查找找文件; classpath*:不僅包含class路徑,還包括jar文件中(class路徑)進行查找. --> < load-on-startup >1</ load-on-startup > </ servlet > <!-- 如果不配置servlet-mapping服務器就無法響應/請求 --> < servlet-mapping > < servlet-name >CoolWeb</ servlet-name > < url-pattern >/</ url-pattern > </ servlet-mapping > </ web-app > |
7、在src下創建CoolWeb-servlet.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<? 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 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-4.3.xsd"> <!-- 開啟SpringMVC注解 --> < context:component-scan base-package = "com.vincent.lwx" /> < mvc:annotation-driven /> </ beans > |
8、在src下編寫ApplicationContext.xml文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<? 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 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-4.3.xsd"> < context:component-scan base-package = "com.vincent.lwx" /> < mvc:annotation-driven /> <!-- User實體類 --> < bean id = "user" class = "com.vincent.lwx.bean.User" /> <!-- 支持上傳文件 --> < bean id = "multipartResolver" class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" > < property name = "defaultEncoding" value = "UTF-8" /> <!-- max size:10M --> < property name = "maxUploadSize" value = "10485760" /> </ bean > </ beans > |
User實體類要在這里注冊
9、在src下編寫mybatis.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> < configuration > < environments default = "development" > < environment id = "development" > < transactionManager type = "JDBC" /> <!-- 配置數據庫連接信息 --> < dataSource type = "POOLED" > < property name = "driver" value = "com.mysql.jdbc.Driver" /> <!-- 注意3306后面是數據庫名稱 autoReconnect自動重連--> < property name = "url" value = "jdbc:mysql://localhost:3306/cool?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true" /> < property name = "username" value = "root" /> < property name = "password" value = "root" /> </ dataSource > </ environment > </ environments > < mappers > < mapper resource = "com/vincent/lwx/dao/UserMapping.xml" /> </ mappers > </ configuration > |
10、log4j.xml配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
<? xml version = "1.0" encoding = "UTF-8" ?> < configuration status = "debug" > < appenders > < Console name = "Console" target = "SYSTEM_OUT" > < ThresholdFilter level = "trace" onMatch = "ACCEPT" onMismatch = "DENY" /> < PatternLayout pattern = "%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n" /> </ Console > < RollingFile name = "RollingFile" fileName = "D:logs/schoolmallapi.log" filePattern = "log/$${date:yyyy-MM}yimoServiceRun-%d{MM-dd-yyyy}-%i.log.gz" > < PatternLayout pattern = "%d{yyyy-MM-dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n" /> < SizeBasedTriggeringPolicy size = "15MB" /> </ RollingFile > </ appenders > < loggers > < root level = "DEBUG" > < appender-ref ref = "RollingFile" /> < appender-ref ref = "Console" /> </ root > </ loggers > <!-- 下面是打印 mybatis語句的配置 --> < logger name = "com.ibatis" additivity = "true" > < level value = "DEBUG" /> </ logger > < logger name = "java.sql.Connection" additivity = "true" > < level value = "DEBUG" /> </ logger > < logger name = "java.sql.Statement" additivity = "true" > < level value = "DEBUG" /> </ logger > < logger name = "java.sql.PreparedStatement" additivity = "true" > < level value = "DEBUG" /> </ logger > < logger name = "java.sql.ResultSet" additivity = "true" > < level value = "DEBUG" /> </ logger > < root > < level value = "DEBUG" /> < appender-ref ref = "CONSOLE" /> <!-- <appender-ref ref="FILE" /> --> <!-- <appender-ref ref="framework" /> --> </ root > </ configuration > |
這個配置貌似有點問題,雖然不影響使用,不過我也沒有去深入研究還,最近還要準備面試Android哎。。。
現在差不多是這樣子咯
11、環境搭建差不多了,現在開始擼代碼,寫一個注冊的動能吧
簡歷一個實體類User.Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
package com.vincent.lwx.bean; import java.io.Serializable; import lombok.Data; import lombok.Getter; import lombok.Setter; /** * @Title: User.java * @Package com.vincent.lwx.bean * @Description: TODO(用一句話描述該文件做什么) * @author Vincent * @date 2017年3月3日 下午6:36:58 * @version V1.0 */ public class User implements Serializable{ /** * 序列化id */ private static final long serialVersionUID = -6375697395831845246L; /** * 用戶id */ private @Getter String user_id; /** * 用戶手機號碼 */ private @Setter @Getter String phone; /** * 密碼 */ private @Setter @Getter String password; /** * 用戶名 */ private @Setter @Getter String nickname; /** * 用戶頭像地址 */ private @Setter @Getter String head; /** * 性別 */ private @Setter @Getter String sex; /** * 生日 */ private @Setter @Getter String birthday; /** * 生活狀態(發表的說說) */ private @Setter @Getter String live_status; } |
編寫MyBatis的實體類映射xml文件,就寫個UserMapping.xml好了,表示為用戶相關的操作
1
2
3
4
5
6
7
8
9
10
11
|
<? 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.vincent.lwx.mapping.UserMapping" > <!-- 根據手機號碼查詢用戶是否存在 --> < select id = "selectUser" parameterType = "String" resultType = "com.vincent.lwx.bean.User" > select * from user where phone = #{phone} </ select > </ mapper > |
我這里只寫了一個,別的還沒寫,注冊之前先查詢一下手機號碼是否已注冊。。
注意這里的id 不能重復,要具有唯一性。parameterType是傳入的參數類型,這里是String類型的phone,如果要傳入多個參數可以使用User對象,或者Map,resultType返回結果類型,我這里是直接返回一個User對象,之前用jdbc直接連接數據庫,返回的東西還要手動封裝,這個快多了。。。
創建MyBatisUtils.java類,用來從數據庫獲取SqlSession對象的,SqlSession執行sql語句,和jdbc的Statement對象差不多感覺。。。也可能我的感覺是錯的,哈哈,還沒看源碼。。。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
package com.vincent.lwx.db; import java.io.IOException; import java.io.Reader; import java.util.Timer; import java.util.TimerTask; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.vincent.lwx.util.EatTimerTask; /** * @Title: MyBatisUtils.java * @Package com.vincent.julie.config * @Description: TODO(????仰????????????ô) * @author Vincent * @date 2017??2??18?? ????12:05:35 * @version V1.0 */ public class MyBatisUtils { private static SqlSessionFactory sqlSessionFactory; private static SqlSession sqlSession; private static long timeInterval; //上一次運行的時間 private static TimerTask task = null ; static { String resource = "mybatis.xml" ; Reader reader = null ; try { reader = Resources.getResourceAsReader(resource); } catch (IOException e) { System.out.println(e.getMessage()); } sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } /** * * @return */ public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } /** * ???sqlSession???? * @return */ public static SqlSession getSqlSession(){ if (task != null ){ task.cancel(); //將原任務從隊列中移除 } task = new EatTimerTask(); timeInterval = System.currentTimeMillis(); //間隔??1小時 long period = 1000 * 60 * 60 ; //測試時間每分鐘一?? //period = 1000 * 60; Timer timer = new Timer(); timer.schedule(task, timeInterval, period); if (sqlSessionFactory == null ){ sqlSessionFactory = MyBatisUtils.getSqlSessionFactory(); } sqlSession = sqlSessionFactory.openSession(); return sqlSession; } } |
這里有個計時器,我發現Tomcat運行一段時間之后(聽說是10小時)如果沒有連接數據庫,會出現異常。。
好,現在來寫UserController.java類,處理客戶端的請求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
package com.vincent.lwx.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.ibatis.session.SqlSession; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.vincent.lwx.bean.ServiceStatus; import com.vincent.lwx.bean.User; import com.vincent.lwx.db.MyBatisUtils; import com.vincent.lwx.util.ResponseUtils; /** * @Title: UserControl.java * @Package com.vincent.lwx.mapping * @Description: TODO(????仰????????????ô) * @author Vincent * @date 2017??3??3?? ????6:28:37 * @version V1.0 */ @Controller public class UserController { private static final Logger logger = LogManager.getLogger(UserController. class ); /** * 注冊 * @param phone * @param password * @param request * @param response */ @RequestMapping (value = "register" , method = RequestMethod.POST) public void registerUser( @RequestParam ( "phone" )String phone, @RequestParam ( "password" )String password,HttpServletRequest request,HttpServletResponse response){ if (hasUserPhone(phone)){ //用戶已存在,無須再次注冊 ResponseUtils.renderJsonDataFail(response, ServiceStatus.RUNTIME_EXCEPTION, "該號碼已被注冊" ); return ; } } /** * 根據手機號碼查詢用戶是否存在 * @param phone * @return */ public boolean hasUserPhone(String phone){ /**sql 語句 完整的包名類名和方法id,*/ String sql = "com.vincent.lwx.mapping.UserMapping.selectUser" ; SqlSession session = MyBatisUtils.getSqlSession(); /**返回一個User對象*/ User user = session.selectOne(sql, phone); if (user!= null ){ //用戶已存在 return true ; } else { //用戶不存在 return false ; } } } |
10、最后一步,讓Tomcat跑起來,好吧,下載Tomcat
這個版本是Tomcat9.0的
如果不會部署的話可以看這里的 部署Tomcat
11、東西寫完了不叫最后一步,最后一步應該自己測試一下,google瀏覽器自帶Postman檢查一下接口的正確性
因為我的數據庫我已經自己注冊了,所以提示是正確的,另外附上user表的sql語句:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
CREATE DETABASE cool; //創建數據庫并指定字符編碼集 CREATE DATABASE cool DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; //創建表 create table user ( user_id int (10) not null primary key auto_increment, phone varchar (11) not null , password varchar (16) not null , nickname varchar (36), head varchar (50), sex varchar (3), birthday varchar (10) default '1992-01-01' , live_status varchar (255) )engine = InnoDB default charset=utf8; //限制最小id=10000 alter table user AUTO_INCREMENT=10000;設置已經存在的表的默認值 //限制手機號碼唯一性 alter table user add unique (phone); 字段值唯一性約束 insert into user (phone, password ) values ( '18696855784' , '555555' ); |
Github地址進入
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/pkandroid/article/details/60157711