詳解SpringMVC和MyBatis框架開發(fā)環(huán)境搭建和簡單實用
1、下載SpringMVC框架架包,下載地址:
點擊打開地址如圖所示,點擊下載即可
然后把相關(guān)的jar復制到lib下導入
2、MyBatis(3.4.2)下載
MyBatis中文文檔地址
下載解壓之后把jar復制到lib下導入,大概是這樣子的
3、jdbc連接庫還沒有下載。。。這個是5.1.41版本的。。。
解壓之后這樣子。。。
4、fastjson 阿里巴巴的json解析庫
版本是1.2.24 這個是托管到了github上面的,地址是:點擊進入
5、創(chuàng)建WebProject
注意下一步有個選項,如果不勾選,默認是不會生成web.xml的
6、項目創(chuàng)建完畢,把之前的包都弄進來。。
web.xml
<?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服務(wù)器就無法響應(yīng)/請求 --> <servlet-mapping> <servlet-name>CoolWeb</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
7、在src下創(chuàng)建CoolWeb-servlet.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/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文件
<?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
<?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" /> <!-- 配置數(shù)據(jù)庫連接信息 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <!-- 注意3306后面是數(shù)據(jù)庫名稱 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配置
<?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哎。。。
現(xiàn)在差不多是這樣子咯
11、環(huán)境搭建差不多了,現(xiàn)在開始擼代碼,寫一個注冊的動能吧
簡歷一個實體類User.Java
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; /** * 生活狀態(tài)(發(fā)表的說說) */ private @Setter@Getter String live_status; }
編寫MyBatis的實體類映射xml文件,就寫個UserMapping.xml好了,表示為用戶相關(guān)的操作
<?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"> <!-- 根據(jù)手機號碼查詢用戶是否存在 --> <select id="selectUser" parameterType="String" resultType="com.vincent.lwx.bean.User"> select * from user where phone = #{phone} </select> </mapper>
我這里只寫了一個,別的還沒寫,注冊之前先查詢一下手機號碼是否已注冊。。
注意這里的id 不能重復,要具有唯一性。parameterType是傳入的參數(shù)類型,這里是String類型的phone,如果要傳入多個參數(shù)可以使用User對象,或者Map,resultType返回結(jié)果類型,我這里是直接返回一個User對象,之前用jdbc直接連接數(shù)據(jù)庫,返回的東西還要手動封裝,這個快多了。。。
創(chuàng)建MyBatisUtils.java類,用來從數(shù)據(jù)庫獲取SqlSession對象的,SqlSession執(zhí)行sql語句,和jdbc的Statement對象差不多感覺。。。也可能我的感覺是錯的,哈哈,還沒看源碼。。。
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(); //將原任務(wù)從隊列中移除 } 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; } }
這里有個計時器,我發(fā)現(xiàn)Tomcat運行一段時間之后(聽說是10小時)如果沒有連接數(shù)據(jù)庫,會出現(xiàn)異常。。
好,現(xiàn)在來寫UserController.java類,處理客戶端的請求
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; } } /** * 根據(jù)手機號碼查詢用戶是否存在 * @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、東西寫完了不叫最后一步,最后一步應(yīng)該自己測試一下,google瀏覽器自帶Postman檢查一下接口的正確性
因為我的數(shù)據(jù)庫我已經(jīng)自己注冊了,所以提示是正確的,另外附上user表的sql語句:
CREATE DETABASE cool; //創(chuàng)建數(shù)據(jù)庫并指定字符編碼集 CREATE DATABASE cool DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; //創(chuàng)建表 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;設(shè)置已經(jīng)存在的表的默認值 //限制手機號碼唯一性 alter table user add unique(phone); 字段值唯一性約束 insert into user(phone,password) values( '18696855784', '555555');
Github地址進入
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
MyBatis注解開發(fā)-@Insert和@InsertProvider的使用
這篇文章主要介紹了MyBatis注解開發(fā)-@Insert和@InsertProvider的使用,具有很好的參考價值,希望對大家有所幫助。2022-07-07spring cloud中微服務(wù)之間的調(diào)用以及eureka的自我保護機制詳解
這篇文章主要介紹了spring cloud中微服務(wù)之間的調(diào)用以及eureka的自我保護機制詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07LinkedList學習示例模擬堆棧與隊列數(shù)據(jù)結(jié)構(gòu)
這篇文章主要介紹了LinkedList學習示例,模擬一個堆棧與隊列數(shù)據(jù)結(jié)構(gòu),大家參考使用吧2014-01-01java web將數(shù)據(jù)導出為Excel格式文件代碼片段
這篇文章主要為大家詳細介紹了java web將數(shù)據(jù)導出為Excel格式文件代碼片段,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-01-01