很久沒有新搭建過框架了,今天搭建一遍。以往都是在eclipse中搭建,今天換Idea吧,目前來說Idea用的還是很多的,但是用習慣了eclipse的朋友,可能會不太習慣 ok.....開始: 註意區分諾~。看不清楚容易出錯↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ ...
很久沒有新搭建過框架了,今天搭建一遍。以往都是在eclipse中搭建,今天換Idea吧,目前來說Idea用的還是很多的,但是用習慣了eclipse的朋友,可能會不太習慣
ok.....開始:
註意區分諾~。看不清楚容易出錯↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
以後再說聚合的事情,
咳咳~~註意哈 別多寫空格~~
ok 項目已經創建好了
接下來就是修改項目信息配置了
這裡創建好文件夾之後,需要配置文件夾屬性,
分割一下
---------------------------------------------------------另一種方式開始--------------------------------------------------------------------------------
---------------------------------------------------------另一種方式結束(上面的方法看懂的可以忽略分割線內的內容)--------------------------------------------------------------------------------
............項目創建完畢。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
啟動測試一下~~
點擊ok結束,這時,
就會出來啟動器,選擇普通啟動,還是maven啟動,就看你了
ok。。。。正文來襲。。。。項目創建好了,開始整合框架~~·~~~怎麼感覺這麼墨跡呢。。弄了那麼多還沒開始~~~ -_-||
開始了 見證奇跡的時刻來了哦
版本: Spring 4.0.2 RELEASE
Spring MVC 4.0.2 RELEASE
MyBatis 3.2.6
Maven引入需要的JAR包
<properties> <!-- spring版本號 --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis版本號 --> <mybatis.version>3.2.6</mybatis.version> <!-- log4j日誌文件管理包版本 --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!-- 表示開發的時候引入,發佈的時候不會載入此包 --> <scope>test</scope> </dependency> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-oxm</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-jdbc</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-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</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.2.2</version> </dependency> <!-- 導入java ee jar 包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- 導入Mysql資料庫鏈接jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <!-- 導入dbcp的jar包,用來在applicationContext.xml中配置資料庫 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL標簽類 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 日誌文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- 格式化對象,方便輸出日誌 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!-- 映入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 上傳組件包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> </dependencies>pom.xml
先進行Spring與MyBatis的整合,,,,,
創建jdbc屬性文件
1 driver=com.mysql.jdbc.Driver 2 url=jdbc:mysql://192.168.1.228:3306/ssmsg 3 username=root 4 password=root 5 #定義初始連接數 6 initialSize=0 7 #定義最大連接數 8 maxActive=20 9 #定義最大空閑 10 maxIdle=20 11 #定義最小空閑 12 minIdle=1 13 #定義最長等待時間 14 maxWait=60000 15 16 17 #註意根據自己的資料庫修改jdbc.properties
然後就是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:p="http://www.springframework.org/schema/p" 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-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自動掃描 --> <context:component-scan base-package="com.jj" /> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化連接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 連接池最大數量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 連接池最大空閑 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 連接池最小空閑 --> <property name="minIdle" value="${minIdle}"></property> <!-- 獲取連接最大等待時間 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mapping/*.xml"></property> </bean> <!-- DAO介面所在包名,Spring會自動查找其下的類 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.jj.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>spring-mybatis.xml
接下來配置上Log4j 來記錄日誌之類的,,我就不詳細解釋了。
1 #定義LOG輸出級別 2 log4j.rootLogger=INFO,Console,File 3 #定義日誌輸出目的地為控制台 4 log4j.appender.Console=org.apache.log4j.ConsoleAppender 5 log4j.appender.Console.Target=System.out 6 #可以靈活地指定日誌輸出格式,下麵一行是指定具體的格式 7 log4j.appender.Console.layout = org.apache.log4j.PatternLayout 8 log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n 9 10 #文件大小到達指定尺寸的時候產生一個新的文件 11 log4j.appender.File = org.apache.log4j.RollingFileAppender 12 #指定輸出目錄 13 log4j.appender.File.File = logs/ssm.log 14 #定義文件最大大小 15 log4j.appender.File.MaxFileSize = 10MB 16 # 輸出所以日誌,如果換成DEBUG表示輸出DEBUG以上級別日誌 17 log4j.appender.File.Threshold = ALL 18 log4j.appender.File.layout = org.apache.log4j.PatternLayout 19 log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%nlog4j.properties
ok下麵咱們進行測試。。為了方便我直接創建了一張簡單的user表
1 /* 2 Navicat MySQL Data Transfer 3 4 Source Server : 本機 5 Source Server Version : 50019 6 Source Host : 192.168.1.228:3306 7 Source Database : ssmsg 8 9 Target Server Type : MYSQL 10 Target Server Version : 50019 11 File Encoding : 65001 12 13 Date: 2017-09-27 16:57:53 14 */ 15 16 SET FOREIGN_KEY_CHECKS=0; 17 18 -- ---------------------------- 19 -- Table structure for `user` 20 -- ---------------------------- 21 DROP TABLE IF EXISTS `user`; 22 CREATE TABLE `user` ( 23 `id` int(11) NOT NULL auto_increment COMMENT 'id', 24 `t_name` varchar(255) default NULL COMMENT '用戶名', 25 `t_pws` varchar(255) default NULL COMMENT '密碼', 26 `t_create_date` varchar(255) default NULL COMMENT '創建時間', 27 `t_status` varchar(255) default NULL COMMENT '狀態', 28 `t_modification_time` varchar(255) default NULL COMMENT '修改時間', 29 `t_file` varchar(255) default NULL COMMENT '圖片', 30 PRIMARY KEY (`id`) 31 ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 32 33 -- ---------------------------- 34 -- Records of user 35 -- ---------------------------- 36 INSERT INTO `user` VALUES ('1', '11', '6512bd43d9caa6e02c990b0a82652dca', '11', '11', '11', null); 37 INSERT INTO `user` VALUES ('4', '12', 'c20ad4d76fe97759aa27a0c99bff6710', '17-9-5 ??1:38', '0', '17-9-5 ??1:38', null); 38 INSERT INTO `user` VALUES ('5', '13', 'c51ce410c124a10e0db5e4b97fc2af39', '17-9-5 ??1:41', '0', '17-9-5 ??1:41', null); 39 INSERT INTO `user` VALUES ('6', '111', '6512bd43d9caa6e02c990b0a82652dca', '17-9-5 ??3:25', '0', '17-9-5 ??3:25', null); 40 INSERT INTO `user` VALUES ('7', '113', '6512bd43d9caa6e02c990b0a82652dca', '17-9-5 ??3:29', '0', '17-9-5 ??3:29', null);user.sql
然後咱們利用Generator,來生成咱們的實體類
然後放到項目中
至於Generator如何使用,自行百度吧,如果實在不會~~可以留言給我~·、
註意一個問題~~~你們有沒有註意到~我的mapping文件夾放在哪了~ -_-!! sorry~~抱歉~~圖我就不換了 你們記得把它放在resources下麵~~~
註意奧 千萬要註意換 別看著圖就上~~照片雖好,LU的多了也傷身~~所以來實際上手,別隻意淫
在我們創建介面實現類的時候,idea可能會出現這個報紅,解決方法為:
解決方法:
File – Settings – Inspections。在Spring Core – Autowring for Bean Class 中將Severity的級別由之前的error改成warning。
給大家貼上圖吧:
ok解決 繼續下一步:
給大家貼上代碼,看著更清晰
1 package com.jj.service; 2 3 import com.jj.pojo.User; 4 5 public interface UserService { 6 7 public User getUser(Integer id);//傳一個id進行查詢 8 }UserService 介面
1 package com.jj.service.impl; 2 3 import com.jj.dao.UserDao; 4 import com.jj.pojo.User; 5 import com.jj.service.UserService; 6 import org.springframework.stereotype.Service; 7 8 import javax.annotation.Resource; 9 10 @Service("userService") 11 public class UserServiceImpl implements UserService{ 12 @Resource 13 private UserDao userDao; 14 15 public User getUser(Integer id) { 16 17 return this.userDao.selectByPrimaryKey(id); 18 } 19 }UserServiceImpl 實現類
1 package com.jj.dao; 2 3 import com.jj.pojo.User; 4 5 public interface UserDao { 6 int deleteByPrimaryKey(Integer id); 7 8 int insert(User record); 9 10 int insertSelective(User record); 11 12 User selectByPrimaryKey(Integer id); 13 14 int updateByPrimaryKeySelective(User record); 15 16 int updateByPrimaryKey(User record); 17 }UserDao
接下來進行測試
第一次測試報錯
因為我個人喜歡叫UserDao 而MyBatis預設是mapper 所以在這裡就將mapping.xml中所有的包結構改對,而我這裡是因為只有一個查詢 所以我就全部刪除了 只留了一個select
再次測試
package com.jj.test; import com.jj.pojo.User; import com.jj.service.UserService; import org.apache.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; @RunWith(SpringJUnit4ClassRunner.class) //表示繼承了SpringJUnit4ClassRunner類 @ContextConfiguration(locations = {"classpath:spring-mybatis.xml"}) public class TestUser { private static Logger logger = Logger.getLogger(TestUser.class);//使用log4j列印日誌 @Resource //註入service private UserService userService; @Test//Junit測試註釋 我想你們懂得 public void getId(){ User user = userService.getUser(1); logger.info(user.toString()); } }UserTest
測試類也寫好了。接下來貼出來運行狀態
========================================上面已經整合好了Spring和MyBatis 接下來是SpringMVC========================================
這裡首先Spring-MVC文件單獨放 代碼:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-3.1.xsd 10 http://www.springframework.org/schema/mvc 11 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 12 <!-- 自動掃描該包,使SpringMVC認為包下用了@controller註解的類是控制器 --> 13 <context:component-scan base-package="com.jj.controller" /> 14 <!--避免IE執行AJAX時,返回JSON出現下載文件 --> 15 <bean id="mappingJacksonHttpMessageConverter" 16 class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> 17 <property name="supportedMediaTypes"> 18 <list> 19 <value>text/html;charset=UTF-8</value> 20 </list> 21 </property> 22 </bean> 23 <!-- 啟動SpringMVC的註解功能,完成請求和註解POJO的映射 --> 24 <bean 25 class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 26 <property name="messageConverters"> 27 <list> 28 <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON轉換器 --> 29 </list> 30 </property> 31 </bean> 32 <!-- 定義跳轉的文件的前尾碼 ,視圖模式配置--> 33 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 34 <!-- 這裡的配置我的理解是自動給後面action的方法return的字元串加上首碼和尾碼,變成一個 可用的url地址 --> 35 <property name="prefix" value="/WEB-INF/jsp/" /> 36 <property name="suffix" value=".jsp" /> 37 </bean> 38 39 <!-- 配置文件上傳,如果沒有使用文件上傳可以不用配置,當然如果不配,那麼配置文件中也不必引入上傳組件包 --> 40 <bean id="multipartResolver" 41 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 42 <!-- 預設編碼 --> 43 <property name="defaultEncoding" value="utf-8" /> 44 <!-- 文件大小最大值 --> 45 <property name="maxUploadSize" value="10485760000" /> 46 <!-- 記憶體中的最大值 --> 47 <property name="maxInMemorySize" value="40960" /> 48 </bean> 49 50 </beans>Spring-mvc.xml
一定要註意包結構~~我這人容易犯低級錯誤
接下來是web.xml主要是配置視圖解析什麼的
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 5 version="3.0"> 6 <display-name>Archetype Created Web Application</display-name> 7 <!-- Spring和mybatis的配置文件 --> 8 <context-param> 9 <param-name>contextConfigLocation</param-name> 10 <param-value>classpath:spring-mybatis.xml</param-value> 11 </context-param> 12 <!-- 編碼過濾器 --> 13 <filter> 14 <filter-name>encodingFilter</filter-name> 15 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 16 <async-supported>true</async-supported> 17 <init-param> 18 <param-name>encoding</param-name> 19 <param-value>UTF-8</param-value> 20 </init-param> 21 </filter> 22 <filter-mapping> 23 <filter-name>encodingFilter</filter-name> 24 <url-pattern>/*</url-pattern> 25 </filter-mapping> 26 <!-- Spring監聽器 --> 27 <listener> 28 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 29 </listener> 30 <!-- 防止Spring記憶體溢出監聽器 --> 31 <listener> 32 <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> 33 </listener> 34 35 <!-- Spring MVC servlet --> 36 <servlet> 37 <servlet-name>SpringMVC</servlet-name> 38 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 39 <init-param> 40 <param-name>contextConfigLocation</param-name> 41 <param-value>classpath:spring-mvc.xml</param-value> 42 </init-param> 43 <load-on-startup>1</load-on-startup> 44 <async-supported>true</async-supported> 45 </servlet> 46 <servlet-mapping> 47 <servlet-name>SpringMVC</servlet-name> 48 <!-- 此處可以可以配置成*.do,對應struts的尾碼習慣 --> 49 <url-pattern>/</url-pattern> 50 </servlet-mapping> 51 <welcome-file-list> 52 <welcome-file>/index.jsp</welcome-file> 53 </welcome-file-list> 54 55 </web-app>web.xml
好 下麵寫controller層
1 package com.jj.controller; 2 3 import com.alibaba.fastjson.JSONObject; 4 import com.jj.model.User; 5 import com.jj.service.UserService; 6 import com.jj.utils.BaseController; 7 import com.jj.utils.Json; 8 import com.jj.utils.TqUtil; 9 import org.apache.log4j.Logger; 10 import org.springframework.stereotype.Controller; 11 import org.springframework.web.bind.annotation.RequestMapping; 12 13 import javax.annotation.Resource; 14 import javax.servlet.http.HttpServletRequest; 15 import javax.servlet.http.HttpServletResponse; 16 17 @Controller 18 @RequestMapping("/userController") 19 public class UserController extends BaseController{ 20 private static Logger logger = Logger.getLogger(UserController.class); 21 @Resource 22 private UserService userService; 23 @RequestMapping("/user") 24 public String getUser(HttpServletRequest request, HttpServletResponse response){ 25 int userId = Integer.parseInt(request.getParameter("id")); 26 User user = userService.getUser(userId); 27 request.getSession().setAttribute("user",user); 28 return "showUser"; 29 30 } 31 @RequestMapping("/tianqi") 32 public void getTqYb(HttpServletRequest request, HttpServletResponse response) { 33 Json j = new Json(); 34 String tq = TqUtil.getTq("北京"); 35 if (tq!=null){ 36 request.getSession().setAttribute("tq",tq); 37 j.setObject(tq); 3