準備說明
jdk、tomcat、idea、mave配置請看我前兩篇,這裏說下mysql以及個人mysql圖像化工具
css
數據庫
html
項目概覽
java
項目構建
--------搭建一個簡單的mave的web項目,構建步驟以下--------
http://www.cnblogs.com/flyins/p/7617078.htmlmysql
--------配置文件--------jquery
該項目須要以來的jar和plugins以下,也就是pom.xml。maven下載完成後,你能夠點擊Maven Projects中看到git
<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> <groupId>com.dsh</groupId> <artifactId>Demo</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>Demo Maven Webapp</name> <url>http://maven.apache.org</url> <!-- 統一管理版本號 --> <properties> <junit.version>4.12</junit.version> <spring.version>4.1.3.RELEASE</spring.version> <mybatis.version>3.2.8</mybatis.version> <mybatis.spring.version>1.2.2</mybatis.spring.version> <mybatis.paginator.version>1.2.15</mybatis.paginator.version> <mysql.version>5.1.32</mysql.version> <slf4j.version>1.6.4</slf4j.version> <jackson.version>2.4.2</jackson.version> <druid.version>1.0.9</druid.version> <httpclient.version>4.3.5</httpclient.version> <jstl.version>1.2</jstl.version> <servlet-api.version>2.5</servlet-api.version> <jsp-api.version>2.0</jsp-api.version> <joda-time.version>2.5</joda-time.version> <commons-lang3.version>3.3.2</commons-lang3.version> <commons-io.version>1.3.2</commons-io.version> <commons-net.version>3.3</commons-net.version> <pagehelper.version>3.4.2-fix</pagehelper.version> <jsqlparser.version>0.9.1</jsqlparser.version> <commons-fileupload.version>1.3.1</commons-fileupload.version> <jedis.version>2.7.2</jedis.version> <solrj.version>4.10.3</solrj.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- Jackson Json處理工具包(springmvc的註解@ResponseBody須要此包) --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- 單元測試 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- 日誌處理 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- Mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <dependency> <groupId>com.github.miemiedev</groupId> <artifactId>mybatis-paginator</artifactId> <version>${mybatis.paginator.version}</version> </dependency> <!-- MySql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- 鏈接池 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</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-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <!-- JSP相關 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servlet-api.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>${jsp-api.version}</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>Demo</finalName> <!-- maven所需依賴。 --> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> <!-- 若是不添加此節點mybatis的mapper.xml文件都會被漏掉。 --> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build> </project>
resources下,粘貼下以下配置文件
spring配置文件applicationContext.xml。主要是用於ioc式建立對象和aop式管理事務。
這裏主要是用到了提供數據源對象github
<?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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 1. 數據源 : DriverManagerDataSource --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!-- 2. mybatis的SqlSession的工廠: SqlSessionFactoryBean dataSource:引用數據源 MyBatis定義數據源,贊成加載配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean> <!-- 3. mybatis自動掃描加載Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory basePackage:指定sql映射文件/接口所在的包(自動掃描) --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.isd.dao"></property> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> <!-- 4. 事務管理 : DataSourceTransactionManager dataSource:引用上面定義的數據源 --> <!-- <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> --> <!-- 5. 使用聲明式事務 transaction-manager:引用上面定義的事務管理器--> <!-- <tx:annotation-driven transaction-manager="txManager" /> --> </beans>
mybatis配置文件mybatis-config.xml
僅僅只有幾行配置,由於項目中使用的 sping和mybatis 實現的,那麼其餘的配置是否就由spring完成了
仔細想一下就知道結果了,使用spring固然會用到的就是spring配置數據源datasource了。那麼mybatis-config.xml內容減小那也是正常了。web
<?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="cacheEnabled" value="true"/> <setting name="lazyLoadingEnabled" value="true"/> <setting name="multipleResultSetsEnabled" value="true"/> <setting name="useColumnLabel" value="true"/> <setting name="useGeneratedKeys" value="true"/> <setting name="defaultExecutorType" value="SIMPLE"/> <setting name="defaultStatementTimeout" value="25000"/> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings> <!-- 實體類,簡稱 -設置別名 --> <typeAliases> <typeAlias alias="Student" type="com.isd.model.Student" /> </typeAliases> <!-- 實體接口映射資源 --> <!-- 說明:若是xxMapper.xml配置文件放在和xxMapper.java統一目錄下,mappers也能夠省略,由於org.mybatis.spring.mapper.MapperFactoryBean默認會去查找與xxMapper.java相同目錄和名稱的xxMapper.xml --> <mappers> </mappers> </configuration>
Log4j,配置文件log4j.properties
經過使用Log4j,咱們能夠控制日誌信息輸送的目的地是控制檯、文件、GUI組件、甚至是套接口服務器、NT的事件記錄器、UNIX Syslog守護進程等spring
# Direct log messages to console 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=%d{ABSOLUTE} %5p %c{1}:%L - %m%n # Root logger option log4j.rootLogger=debug,console
配置web.xml,springmvc的配置文件dispatcher-servlet.xml
dispatcher-servlet.xmlsql
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.isd"/> <!-- 靜態資源的訪問 --> <mvc:resources mapping="/**/*.html" location="/"/> <mvc:resources mapping="/**/*.js" location="/"/> <!--<mvc:resources mapping="/css/**" location="/css/"/>--> <!--<mvc:resources mapping="/images/**" location="/images/"/>--> <!--<mvc:resources mapping="/static/**" location="/static/"/>--> <!-- 開啓註解 --> <mvc:annotation-driven/> <!--ViewResolver 視圖解析器--> <!--用於支持Servlet、JSP視圖解析--> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
---------使用mybatis.generator逆向工程生成model和dao層--------
配置文件generatorConfig.xml
注意的是:先新建一個在src下java目錄,而後轉成sources類型,否則不會被編譯,方法參考http://www.cnblogs.com/flyins/p/7617835.html
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <classPathEntry location="C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\5.1.32\mysql-connector-java-5.1.32.jar" /> <context id="testTables" targetRuntime="MyBatis3"> <commentGenerator> <!-- 是否去除自動生成的註釋 true:是 : false:否 --> <property name="suppressAllComments" value="false" /> </commentGenerator> <!--數據庫鏈接的信息:驅動類、鏈接地址、用戶名、密碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="root"> </jdbcConnection> <!-- 默認false,把JDBC DECIMAL 和 NUMERIC 類型解析爲 Integer,爲 true時把JDBC DECIMAL 和 NUMERIC 類型解析爲java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- targetProject:生成PO類的位置 --> <javaModelGenerator targetPackage="com.isd.model" targetProject="C:\Users\Administrator\IdeaProjects\Demo\src\main\java"> <!-- enableSubPackages:是否讓schema做爲包的後綴 --> <property name="enableSubPackages" value="false" /> <!-- 從數據庫返回的值被清理先後的空格 --> <property name="trimStrings" value="false" /> </javaModelGenerator> <!-- targetProject:mapper映射文件生成的位置 --> <sqlMapGenerator targetPackage="com.isd.dao" targetProject="C:\Users\Administrator\IdeaProjects\Demo\src\main\java"> <!-- enableSubPackages:是否讓schema做爲包的後綴 --> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- targetPackage:mapper接口生成的位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.isd.dao" targetProject="C:\Users\Administrator\IdeaProjects\Demo\src\main\java"> <!-- enableSubPackages:是否讓schema做爲包的後綴 --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 指定數據庫表 --> <table tableName="student" ></table> </context> </generatorConfiguration>
---------給項目配置服務器--------
idea要求若給項目添加tomcat,則必須先配置好默認的tomcat,而後點擊+號纔有tomcat選項,因此先配置全局default的tomcat
而後再給項目配置tomcat服務器
------------------------------------------------------------------------------以上,準備工做結束,項目搭建完畢,準備本身coding吧----------------------------------------------------------------------------------------------
我要點擊按鈕,獲取全部的student。
Dao層
那麼我須要在mapper的xml和java文件中新增此方法:
StudentMapper.xml
<select id="selectAllSudent" resultMap="BaseResultMap" > select <include refid="Base_Column_List" /> from student </select>
StudentMapper.java
List<Student> selectAllSudent();
service層
接口StudentService
package com.isd.service; import com.isd.model.Student; import java.util.List; public interface StudentService { List<Student> getAllStudent(); }
實現StudentServiceImp
package com.isd.service.imp; import com.isd.dao.StudentMapper; import com.isd.model.Student; import com.isd.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class StudentServiceImp implements StudentService { @Autowired private StudentMapper studentDao; public List<Student> getAllStudent() { return studentDao.selectAllSudent(); } }
conttroller層
StudentController
package com.isd.controller; import com.isd.model.Student; import com.isd.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; 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.ResponseBody; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("student") public class StudentController { @Autowired private StudentService studentService; @RequestMapping("getAllStudent") @ResponseBody public Map<String,Object> getAllStudent(){ List<Student> allStudent=studentService.getAllStudent(); Map<String,Object> result=new HashMap<String,Object>(); result.put("status","sucess"); result.put("data",allStudent); return result; } }
web
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>測試系統已經啓動!!!</h1> <button>獲取全部學生</button> <script src="./js/jquery-3.2.1.min.js"></script> <script> var myhost='http://localhost:8080/Demo/'; var getAllStudent=myhost+'student/getAllStudent'; $('button').click(function () { $.post(getAllStudent,function (rep) { console.log(rep) }) }) </script> </body> </html>
效果
總的大概來講呢
spring就是用來提供對象的,利用其ioc/di與aop貫穿於整個項目。爲各個層之間提供對象建立和注入,解耦合。
好比個人這個項目提供了dao層的對象。不過service、controller都有,只不過是用來註解,在默認配置文件applicationContext.xml中感受不出來而已
springMVC是負責controller和jsp的,也就是視圖層的,其默認配置文件是dispatcher-servlet.xml
mybatis是負責數據庫的鏈接(不用jdbc了),與spring整合後,配合spring可提供dao層對象
項目地址https://gitee.com/dingshao/Demo.git