記錄本身每一次的成長。html
項目目錄先來一份,僅供參考java
先來上一份pom.xml的配置mysql
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ --> <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> <packaging>war</packaging> <name>spring_MVC_mybatis</name> <groupId>lpp</groupId> <artifactId>spring_MVC_mybatis</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- spring版本號 --> <spring.version>4.2.5.RELEASE</spring.version> <!-- mybatis版本號 --> <mybatis.version>3.2.8</mybatis.version> <!-- mysql驅動版本號 --> <mysql-driver.version>5.1.29</mysql-driver.version> <!-- log4j日誌包版本號 --> <slf4j.version>1.7.18</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <!-- 添加jstl依賴 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- 添加junit4依賴 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <dependency> <!-- spring對測試框架的簡單封裝功能 --> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.2.0.RELEASE</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-context</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-aop</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> <!-- 添加mysql驅動依賴 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-driver.version}</version> </dependency> <!-- 添加數據庫鏈接池依賴 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- 添加fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <!-- 添加日誌相關jar包 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</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> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.0</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> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.0</version> </dependency><dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>RELEASE</version> </dependency> </dependencies> </project>
接下來spring的配置文件,配置文件內容就很少介紹了,不少博客上都會有。記錄一下整合過程吧。web
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-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/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scan base-package="com.lpp.ssm.controller"/> <context:component-scan base-package="com.lpp.ssm.service"/> <bean id="propertyConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/><!--${driverClasss}--> <property name="url" value="jdbc:mysql://localhost:3306/test"/><!--${jdbcUrl}--> <property name="username" value="root"/><!--${username}--> <property name="password" value=""/> <!-- <!–初始化鏈接大小–> <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> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatisConfig.xml"/> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.lpp.ssm.dao"/> <!--<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>--> </bean> <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
而後是mybaits的配置mybatisconfig.xml 作測試用,配置的也都很簡單。spring
<?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> <settings> <setting name="logImpl" value="log4j"/> </settings> <typeAliases> <typeAlias type="com.lpp.ssm.entity.Car" alias="car"/> </typeAliases> </configuration>
mapper.xmlsql
<?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.lpp.ssm.dao.CarMapper"> <select id="selectOneById" resultType="car" parameterType="int"> SELECT id,car_name AS carName,maxSpeed FROM t_car WHERE id = #{id}; </select> </mapper>
com.lpp.ssm.dao下的carMapper接口數據庫
package com.lpp.ssm.dao; import com.lpp.ssm.entity.Car; /** * Created with IntelliJ IDEA. * Description: * User: lpp * Date: 2018-04-28 * Time: 22:38 */ public interface CarMapper { public Car selectOneById(int id); }
com.lpp.ssm.service下的carService類:express
package com.lpp.ssm.service; import com.lpp.ssm.dao.CarMapper; import com.lpp.ssm.entity.Car; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Created with IntelliJ IDEA. * Description: * User: lpp * Date: 2018-04-28 * Time: 23:06 */ @Service public class CarSercice { @Autowired CarMapper carMapper; public Car selectCarById (int id){ return carMapper.selectOneById(id); } }
而後整合SpringMVC 先配置springMVC.xmlapache
<?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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自動掃描 @Controller--> <context:component-scan base-package="com.lpp.ssm.controller"/> <!--避免IE執行AJAX時,返回JSON出現下載文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 啓動SpringMVC的註解功能,完成請求和註解POJO的映射 --> <!--<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter"/> <!– JSON轉換器 –> </list> </property> </bean>--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
而後是web.xmljson
<?xml version="1.0" encoding="UTF-8" ?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <!-- 編碼過濾器 --> <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> <!-- spring監聽器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止spring內存溢出監聽器,好比quartz --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
接下來是實體類
package com.lpp.ssm.entity; /** * Created with IntelliJ IDEA. * Description: * User: lpp * Date: 2018-04-28 * Time: 20:54 */ public class Car { private int id; private String carName; private int maxSpeed; public Car() { } public Car(int id, String carName, int maxSpeed) { this.id = id; this.carName = carName; this.maxSpeed = maxSpeed; } public int getId() { return id; } public String getCarName() { return carName; } public int getMaxSpeed() { return maxSpeed; } public void setId(int id) { this.id = id; } public void setCarName(String carName) { this.carName = carName; } public void setMaxSpeed(int maxSpeed) { this.maxSpeed = maxSpeed; } @Override public String toString() { return "Car{" + "id=" + id + ", carName='" + carName + '\'' + ", maxSpeed=" + maxSpeed + '}'; } }
測試用的controller
package com.lpp.ssm.controller; import com.lpp.ssm.entity.Car; import com.lpp.ssm.service.CarSercice; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import java.util.Map; import java.util.logging.Logger; /** * Created with IntelliJ IDEA. * Description: * User: lpp * Date: 2018-04-27 * Time: 21:26 */ @Controller public class TestContorller { @Autowired CarSercice carSercice; @RequestMapping("/login") public String toLogin(HttpServletRequest request, Model model){ int id = Integer.parseInt(request.getParameter("id")); Car car = carSercice.selectCarById(id); model.addAttribute("id",car.getId()); model.addAttribute("carName",car.getCarName()); model.addAttribute("speed",car.getMaxSpeed()); return "login"; } }
log4j的配置
log4j.rootLogger=DEBUG,Console,File #控制檯日誌 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%p][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n #普通文件日誌 #log4j.appender.File=org.apache.log4j.RollingFileAppender #log4j.appender.File.File=logs/ssm.log #log4j.appender.File.MaxFileSize=10MB #輸出日誌,若是換成DEBUG表示輸出DEBUG以上級別日誌 log4j.appender.File.Threshold=ALL log4j.appender.File.layout=org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern=[%p][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n
jdbc屬性文件
這裏注意每一行行末不要出現空格,不然會出現找不到該屬性或該屬性錯誤的異常。
driverClasss=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/test username=root #password=root #定義初始鏈接數 initialSize=0 #定義最大鏈接數 maxActive=20 #定義最大空閒 maxIdle=20 #定義最小空閒 minIdle=1 #定義最長等待時間 maxWait=60000
最後附上index.jsp和login.jsp的內容,僅供參考。
<%-- Created by IntelliJ IDEA. User: lpp Date: 2018/5/3 Time: 20:16 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form method="post" action="/login"> <input id="id" name="id" type="text"> <button type="submit">submit</button> </form> </body> </html>
<%-- Created by IntelliJ IDEA. User: lpp Date: 2018/4/27 Time: 21:23 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>login</title> </head> <body> <td> <tr>${id}</tr> <tr>${carName}</tr> <tr>${speed}</tr> </td> </body> </html>
而後就結束了。大功告成。
最後提示你們一點,是我出現過的錯誤。在controller中的requestmapping標註的方法中。接受的參數若是用基本類型或者對象接受的話,注意該參數是不能夠爲null的。有可能會出現,前臺傳值並未傳過來,mybatis使用該參數查詢的時候查詢不到,並報錯。
解決方法使用@RequestParam(value = "username",required = false)String username 聲明參數以後,該值就能夠爲null了。
不知道形容的具體是否正確,暫時記錄下來,避免之後踩坑吧。