一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|編程技術|正則表達式|

服務器之家 - 編程語言 - JAVA教程 - 詳解SpringMVC和MyBatis框架開發環境搭建和簡單使用

詳解SpringMVC和MyBatis框架開發環境搭建和簡單使用

2020-09-25 15:07Android小屋 JAVA教程

這篇文章主要介紹了詳解SpringMVC和MyBatis框架開發環境搭建和簡單使用,具有一定的參考價值,感興趣的小伙伴們可以參考一下

1、下載SpringMVC框架架包,下載地址:

點擊下載

點擊打開地址如圖所示,點擊下載即可


詳解SpringMVC和MyBatis框架開發環境搭建和簡單使用

然后把相關的jar復制到lib下導入

2、MyBatis(3.4.2)下載

點擊下載

MyBatis中文文檔地址

點擊查看

下載解壓之后把jar復制到lib下導入,大概是這樣子的

詳解SpringMVC和MyBatis框架開發環境搭建和簡單使用

3、jdbc連接庫還沒有下載。。。這個是5.1.41版本的。。。

點擊下載

詳解SpringMVC和MyBatis框架開發環境搭建和簡單使用

解壓之后這樣子。。。

4、fastjson 阿里巴巴的json解析庫

點擊下載

版本是1.2.24 這個是托管到了github上面的,地址是:點擊進入

5、創建WebProject

詳解SpringMVC和MyBatis框架開發環境搭建和簡單使用

注意下一步有個選項,如果不勾選,默認是不會生成web.xml的

詳解SpringMVC和MyBatis框架開發環境搭建和簡單使用

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&amp;characterEncoding=utf-8&amp;useSSL=false&amp;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哎。。。

現在差不多是這樣子咯

詳解SpringMVC和MyBatis框架開發環境搭建和簡單使用

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

詳解SpringMVC和MyBatis框架開發環境搭建和簡單使用

11、東西寫完了不叫最后一步,最后一步應該自己測試一下,google瀏覽器自帶Postman檢查一下接口的正確性

詳解SpringMVC和MyBatis框架開發環境搭建和簡單使用

因為我的數據庫我已經自己注冊了,所以提示是正確的,另外附上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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 70岁多老妇人特黄a级毛片 | 动漫白丝袜美女羞羞 | 亚洲精品中文 | 日韩精品欧美国产精品亚 | 久久婷婷五月综合色丁香 | 男女18一级大黄毛片免 | 四虎永久在线精品波多野结衣 | 99热国产这里只有精品 | 亚洲偷窥图区色 | 好男人好资源在线观看免费 | 美女扒开屁股 | 日本一区二区视频在线观看 | 亚洲+国产+图片 | 好大好硬好湿好紧h | 俄罗斯一级淫片 | 99热这里只有精品国产免费 | 久久亚洲精品中文字幕60分钟 | 香蕉久久一区二区不卡无毒影院 | 国产青草视频在线观看免费影院 | www.4虎影院 w7w7w7w7w免费 | 国产一卡2卡3卡四卡国色天香 | 男女男精品视频网站 | 亚洲欧美日韩综合在线播放 | 干露露视频 性感写真 | 黄情视频 | 耽美调教高h | 亚洲欧美天堂 | 好大好硬抽搐好爽想要 | 久久精品一区二区三区资源网 | 国产小视频在线 | 天美传媒果冻传媒星空传媒 | 王的视频视ivk | 午夜免费体验30分 | 成人精品一区久久久久 | 精品日韩欧美一区二区三区在线播放 | 91在线老师啪国自产 | 亚洲国产免费 | 免费高清特黄a 大片 | 跪在老师脚下吃丝袜脚 | 欧美一区二区三区在线观看免费 | 天堂激情网 |