下面是總體步驟:javascript
1: 先建立一個Maven 項目:css
選擇跳過骨架:html
由於要搭建的是 web 項目 因此這個地方選擇 war 包; 前端
點擊完成 這樣就完成 Maven項目的搭建:java
接下倆 先把 Maven的pom.xml 須要的依賴 添加上:mysql
<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.etoak</groupId> <artifactId>mssm02</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format> <spring.version>4.2.5.RELEASE</spring.version> <mybatis.version>3.4.4</mybatis.version> <mybatisspring.version>1.3.1</mybatisspring.version> <jackson.version>2.7.0</jackson.version> <log4j.version>1.2.17</log4j.version> <slf4j.version>1.7.7</slf4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- javaEE --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>7.0</version> </dependency> <!-- servlet start --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- servlet end --> <!-- spring start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-context</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-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-aspects</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-tx</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-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.10.1.RELEASE</version> </dependency> <!-- spring end --> <!-- mybatis start --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatisspring.version}</version> </dependency> <!-- mybatis end --> <!-- 數據庫 start --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.29</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>10.2.0.4.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <!-- 數據庫 end --> <!-- servlet start --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- servlet end --> <!-- json start (fastjson & jackjson) --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.31</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- json end --> <!-- log4j start --> <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> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.4.Final</version> </dependency> <!-- log4j end --> <!-- 上傳組件包 start --> <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.10</version> </dependency> <!-- 上傳組件包 end --> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <skipTests>true</skipTests> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> <finalName>mssm02</finalName> <!-- 這裏是 項目名 --> </build> </project>
若是 看到 pom.xml 報錯的話 ; 看一下 報什麼錯;jquery
這裏說: web.xml is missing and <failOnMissingWebXml> is set to true ;web
翻譯一下: web.xml 文件 缺失 而且 <缺失webxml就失敗> 這個元素被設爲 true ; 因此會報錯:ajax
由於我們開頭的時候 是 跳過 使用骨架 因此 如今目錄結構中沒有 web.xml文件; 因此下一步就把項目轉成動態web 項目:spring
2: 把項目轉換成 動態web 項目:
這裏要要分兩步 進行:
第一步 先 選定 java的版本 和 JavaScript 的版本: 這裏選擇 java 1.8 ; javaScript 1.0 而後 點擊 應用 和 肯定並關閉 ; 注意 必定要關閉;
第二步 再選定 DynimicWebModule 這裏選擇 3.1
兩步分開 才能出現 下一個界面: 會提示要不要進一步配置: 而後 提示 能夠配置xml 文件:
點擊肯定以後: 再看一下項目結構 有什麼變化:
若是 沒有出現上面的變化 ; 從新操做一遍;
這樣會面臨一個問題: 有兩個web目錄: 一個是: webContent 目錄: 一個是 webapp目錄 : 很顯然 若是 有兩個 web 目錄 就顯得比較亂; 若是 兩個只保留一個 ;你會選擇保留哪個? 爲何?
我這裏選擇保留 webapp 緣由: webapp 看起來 要比 webContent 要順眼一些 ; [這樣的理由也能夠呀!] 確實: webapp 和 java ;resources 這些是同一個目錄結構 因此: 保留webapp 整個目錄結構 就很統一; 這就是我以爲 webapp 看起來 要順眼的緣由:
而後就是 拆遷工程了:
拆遷完以後的項目結構以下:
發現了沒? 拆遷完以後 又報錯了 並且 仍是一樣的錯誤 找不到 web.xml文件:
上次找不到web.xml文件 真的是hi沒有web.xml文件; 此次找不到 可不是 真的沒有; 而是有但它仍是報說找不到; 爲何呢? 明明有 , 但它卻說沒有;
會不會是路徑 不對 致使沒有找到?
來看一下 目錄路徑: 找這個部署 路徑
發現了沒? 這個路徑仍是拆遷以前的路徑: 修改一下路徑試試
把 無用的都移除掉; 而後把新的路徑 添加上:
而後回頭再看一下 還報錯不? 若是 還報錯 就須要把pom.xml文件 所有剪貼 而後 再粘貼 一下試試 ; 這樣操做一下 就會沒事的;
至此 : web 項目 的架構也搭建好了:
3: 配置 spring , spring Mvc , Mybatis 配置文件;
按照什麼順序配置呢?
首先確定是先配置: web.xml 這個是web容器的配置:
項目啓動的時候 先啓動它(web容器) 而後 它再去加載初始化項:以此啓動監聽器 過濾器 攔截器 等;
那就按照這個啓動時間的順序 去配置這些 配置文件:
先配置 web.xml: 根據 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>mssm02</display-name> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <!-- 加載順序: 上下文參數 >>> 監聽器 >>> 過濾器 >>> 攔截器 --> <!-- 日誌記錄 --> <context-param> <!-- 日誌配置文件路徑 --> <param-name>log4jConfigLocation</param-name> <param-value>classpath:config/properties/log4j.properties</param-value> </context-param> <context-param> <!-- 日誌頁面的刷新間隔 --> <param-name>log4jRefreshInterval</param-name> <param-value>6000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/xml/application.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>encoding</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>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 放行資源 文件 --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> <url-pattern>*.css</url-pattern> <url-pattern>/assets/*"</url-pattern> <url-pattern>/images/*</url-pattern> </servlet-mapping> <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*:config/xml/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <session-config> <session-timeout>60</session-timeout> </session-config> </web-app>
下面是配置好的目錄結構:
下面是把摺疊的都展開的項目結構:
下面是配置文件的代碼:
application.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!-- 上面 雖然沒有標註版本號 ; 但spring能夠自動配置最合適的版本號 --> <!-- 採用註釋的方式配置bean --> <context:annotation-config /> <!-- 自動掃描註解 --> <context:component-scan base-package="com.etoak.mssm" /> <!--導入DAO配置 --> <import resource="mybatis-dao.xml"/> <!--導入數據庫配置 --> <import resource="mybatis-db.xml"/> <!--導入數據庫事務配置 --> <import resource="spring-tx.xml"/> </beans>
mybatis-dao.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" 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 "> <!-- mapper掃描配置掃描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 掃描com.etoak.mssm這個包以及它的子包下的全部映射接口類 --> <property name="basePackage" value="com.etoak.mssm.emp.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <!-- 若是報錯Invalid bound statement (not found): 請參考: https://my.oschina.net/psuyun/blog/464851 --> </bean> </beans>
mybatis-db.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" 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 "> <!-- 加載oracle.properties文件中的內容 --> <context:property-placeholder location="classpath*:config/properties/oracle.properties" /> <!-- 配置數據源,--> <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> <!-- 配置sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /><!-- 實例化sqlSessionFactory時須要使用上述配置好的數據源以及SQL映射文件 --> <property name="mapperLocations" value="classpath*:mybatis/mappers/**/*.xml" /><!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 --> </bean> <!-- 定義SqlSessionTemplate --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg> </bean> <!-- SqlSession:用於執行持久化操做的對象,相似於jdbc中的Connection。 --> <!-- SqlSessionFactory:建立SqlSession實例的工廠 --> <!-- SqlSessionFactoryBuilder:build方法建立SqlSessionFactory實例。 --> <!-- SqlSessionTemplate:MyBatis提供的持久層訪問模板化的工具,線程安全,可經過構造參數或依賴注入SqlSessionFactory實例。 --> </beans>
spring-tx.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" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
spring-mvc.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/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" > <!-- 開啓註解模式驅動 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 自動掃描web包 ,將帶有註解的類 歸入spring容器管理 --> <context:component-scan base-package="com.etoak.mssm"/> <mvc:resources location="/WEB-INF/pages/" mapping="/pages/**"/> <!-- 視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 解決 IE瀏覽器 不能正常解析 json 問題 --> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=utf-8</value> <value>application/json;charset=utf-8</value> <value>application/x-www-form-urlencoded</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!--配置靜態資源映射,防止靜態資源被攔截後致使controller返回的頁面的js,css失效 --> <!-- <mvc:resources location="/static/css/" mapping="/css/**"></mvc:resources> <mvc:resources location="/static/js/" mapping="/js/**"></mvc:resources> <mvc:resources location="/static/images/" mapping="/images/**"/> --> </beans>
properties:
log4j.rootLogger=DEBUG,Console,Stdout
#[Level] DEBUG
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
#stdout
log4j.appender.Stdout = org.apache.log4j.DailyRollingFileAppender
log4j.appender.Stdout.File = E://logs/log.log
log4j.appender.Stdout.Append = true
log4j.appender.Stdout.Threshold = DEBUG
log4j.appender.Stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.Stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
oracle.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
username=scott
password=tiger
initialSize=0
maxActive=20
maxIdle=20
minIdle=1
maxWait=60000
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; String welcomeHomePagePath = basePath+"welcome/welcomeHome"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"></base> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>indexPage</title> </head> <body> HelloWorld! This is the index page . <br/> <br/> <a href="<%=welcomeHomePagePath %>">Click me to go to welcomeHome page</a> </body> </html>
開貓 ;正常啓動: 出現了下面的頁面:
至此 說明 Maven spring springMVC Mybatis 框架 已經搭建好; 並且 Maven spring 已經能正常使用;
下面 將進一步 測試 spring MVC 和 mybatis 是否能正常使用;
4: 測試 spring MVC 可否 正常使用
寫 controller
WelcomeController.java
package com.etoak.mssm.common.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping(value="/welcome") public class WelcomeController { @RequestMapping(value="/welcomeHome",method=RequestMethod.GET) public String index(){ System.out.println("進來了!"); return "welcome/welcomeHome"; } }
完成 頁面: welcomeHome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; String empHomePagePath = basePath+"emp/empHome"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"></base> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>welcomeHomePage</title> </head> <body> This is welcomeHome page . <br/> <br/> <a href="<%=empHomePagePath %>">Click me to go to Emp Home Page </a> </body> </html>
開貓 測試一下:
點擊跳轉進來了. 這就說明controller 起做用了; spring MVC 配置好了;
這裏可能會有疑問:
index.jsp 和 welcomeHome.jsp 有什麼區別?(也就是說 能從indx.jsp 跳轉到 welcomeHome.jsp 就說明 springMVC 配置好了麼?)
1: 訪問的機制不同: index.jsp 位於 webapp 目錄下面 跟 WEB-INF是平級的; 能夠經過URL 直接訪問;
welcomeHome.jsp 位於 WEB-INF 裏面 只能經過 攔截器 控制跳轉來訪問;
因此 一般的目錄結構中, 都會把 page頁面放在 WEB-INF 裏面 以確保安全;
5:下面來驗證 mybatis 是否配置好了;
mybatis 涉及到 dao, mapper, service ,外加 test 測試案例 因此包結構以下:;
先寫service 層:
如圖: service 層 分兩個包 一個是接口 一個是實現類;
先寫接口:
這裏的增刪該查的參數都是Emp; 是否是有疑問? 若是說增 和 改 的參數是Emp 還好理解, 爲何 刪和查也要是 Emp 呢?
這個對於初學者 可能會有點疑問;等有經驗以後,你就會明白了.這裏我也先說一下爲何.
1: 首先: 刪除 的 ID 和 查詢的 ID 自己就是Emp的ID 這個沒有異議吧? 既然是Emp 的ID ,那我就能夠 emp 來替代Emp的ID, 無非是mapper裏面修改一下 對吧 (mapper 裏面根據 傳入的參數類型 來 組裝 SQL ).
2: 在查詢的時候會有條件查詢; 而這些查詢條件確定都是emp的字段; 對吧. 這樣的話 我就能夠把條件塞進emp中; 只傳一個參數就能夠了,對吧.
3: 固然了 以上只是對單表查詢來講 ;
package com.etoak.mssm.emp.service; import java.util.List; import com.etoak.mssm.emp.entity.Emp; public interface EmpService { public int addEmp(Emp emp); public int deleteEmp(Emp emp); public int updateEmp(Emp emp); public List<Emp> getEmps(Emp emp); public int getCount(Emp emp); }
package com.etoak.mssm.emp.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.etoak.mssm.emp.dao.EmpDao; import com.etoak.mssm.emp.entity.Emp; import com.etoak.mssm.emp.service.EmpService; @Service public class EmpServeiceImpl implements EmpService { @Autowired //採用註解的方式 注入 enpDao private EmpDao empDao ; public int addEmp(Emp emp) { return empDao.addEmp(emp); } @Override public int deleteEmp(Emp emp) { return empDao.deleteEmp(emp); } @Override public int updateEmp(Emp emp) { return empDao.updateEmp(emp); } public List<Emp> getEmps(Emp emp) { return empDao.getEmps(emp); } @Override public int getCount(Emp emp) { return empDao.getCount(emp); } }
dao 層
package com.etoak.mssm.emp.dao; import java.util.List; import com.etoak.mssm.emp.entity.Emp; public interface EmpDao { public int addEmp(Emp emp); public int deleteEmp(Emp emp); public int updateEmp(Emp emp); public List<Emp> getEmps(Emp emp); public int getCount(Emp emp); }
mapper 注意 mapper 層的位置 通常都會把 mapper 寫在 resource 裏面 ,緣由, 下降耦合度 ; 和 目錄結構 清晰;
<?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.etoak.mssm.emp.dao.EmpDao"> <resultMap id="EmpResultMap" type="com.etoak.mssm.emp.entity.Emp"> <id column="empno" property="empno" jdbcType="DOUBLE" /> <result column="ename" property="ename" jdbcType="VARCHAR" /> <result column="job" property="job" jdbcType="VARCHAR" /> <result column="mgr" property="mgr" jdbcType="DOUBLE" /> <result column="hiredate" property="hiredate" jdbcType="DATE" /> <result column="sal" property="sal" jdbcType="DOUBLE" /> <result column="comm" property="comm" jdbcType="DOUBLE" /> <result column="deptno" property="deptno" jdbcType="DOUBLE" /> </resultMap> <!-- CREATE SEQUENCE seqTest ; INCREMENT BY 1 每次加幾個 ;START WITH 1 從1開始計數 ; NOMAXvalue 不設置最大值 ; NOCYCLE 一直累加,不循環 ; CACHE 10 緩存 10 ; - --> <!-- CREATE SEQUENCE seqEmp INCREMENT BY 1 START WITH 1000 NOMAXvalue NOCYCLE CACHE 10 --> <!-- 新增emp --> <insert id="addEmp" parameterType="com.etoak.mssm.emp.entity.Emp"> <!-- insert 元素 沒有 resultType 屬性: http://blog.csdn.net/a281246240/article/details/53463620 --> <selectKey resultType="java.lang.Integer" order="BEFORE" keyProperty="empno"> SELECT seqEmp.Nextval as EMPNO from DUAL </selectKey> insert into emp (empno,ename,job,mgr,hiredate,sal,comm,deptno) values(#{empno,jdbcType=DOUBLE},#{ename,jdbcType=VARCHAR},#{job,jdbcType=VARCHAR},#{mgr,jdbcType=DOUBLE},#{hiredate,jdbcType=DATE},#{sal,jdbcType=DOUBLE},#{comm,jdbcType=DOUBLE},#{deptno,jdbcType=DOUBLE}) </insert> <!-- 刪除emp --> <delete id="deleteEmp" parameterType="com.etoak.mssm.emp.entity.Emp"> delete from emp where empno = #{empno} </delete> <!-- 修改emp --> <update id="updateEmp" parameterType="com.etoak.mssm.emp.entity.Emp"> update emp <set> <if test="ename != null and ename != ''"> ename = #{ename}, </if> <if test="job != null and job != ''"> job = #{job}, </if> <if test="mgr != null and mgr != ''"> mgr = #{mgr}, </if> <if test="hiredate != null "> hiredate = #{hiredate}, </if> <if test="sal != null and sal != ''"> sal = #{sal}, </if> <if test="comm != null and comm != ''"> comm = #{comm}, </if> <if test="deptno != null and deptno != ''"> deptno = #{deptno} </if> </set> where empno = #{empno} </update> <!-- 查看全部的Emp --> <select id="getEmps" parameterType="com.etoak.mssm.emp.entity.Emp" resultMap="EmpResultMap"> select b.* from ( select a.*, rownum rn from ( select * from emp where 1 = 1 <if test="empno != null and empno != ''"> and instr(empno,#{empno}) > 0 </if> <if test="ename != null and ename != ''"> and instr(ename,#{ename}) > 0 </if> <if test="job != null and job != ''"> and instr(job,#{job}) > 0 </if> <if test="mgr != null and mgr != ''"> and instr(mgr,#{mgr}) > 0 </if> <if test="hiredate != null and hiredate != ''"> and hiredate = #{hiredate} </if> <if test="sal != null and sal != ''"> and instr(sal,#{sal}) > 0 </if> <if test="comm != null and comm != ''"> and instr(comm,#{comm}) > 0 </if> <if test="deptno != null and deptno != ''"> and instr(deptno,#{deptno}) > 0 </if> ) a where 1 = 1 <if test="endSize != null and endSize != ''"> and rownum < #{endSize} </if> ) b where 1 = 1 <if test="startSize != null and startSize != ''"> and b.rn >= #{startSize} </if> </select> <select id="getCount" parameterType="com.etoak.mssm.emp.entity.Emp" resultType="java.lang.Integer"> select count(*) from emp where 1 = 1 <if test="empno != null and empno != ''"> and instr(empno,#{empno}) > 0 </if> <if test="ename != null and ename != ''"> and instr(ename,#{ename}) > 0 </if> <if test="job != null and job != ''"> and instr(job,#{job}) > 0 </if> <if test="mgr != null and mgr != ''"> and instr(mgr,#{mgr}) > 0 </if> <if test="hiredate != null and hiredate != ''"> and hiredate = #{hiredate} </if> <if test="sal != null and sal != ''"> and instr(ename,#{ename}) > 0 </if> <if test="comm != null and comm != ''"> and instr(ename,#{ename}) > 0 </if> <if test="deptno != null and deptno != ''"> and instr(ename,#{ename}) > 0 </if> </select> </mapper>
接下來是 測試 案例:
package com.etoak.mssm.emp.test; import java.util.Date; import java.util.List; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.etoak.mssm.emp.entity.Emp; import com.etoak.mssm.emp.service.EmpService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:config/xml/application.xml" })// 若是報錯:程序包org.junit不存在 參考: http://www.cnblogs.com/LiuChunfu/p/5598367.html public class TestCase { @Autowired private EmpService empService; @org.junit.Test public void getOne() { Emp emp = new Emp(); emp.setEmpno(7369); List<Emp> list = empService.getEmps(emp); System.out.println("getOne : "+list); } @org.junit.Test public void getAll() { Emp emp = new Emp(); //emp.setEmpno(7369); List<Emp> list = empService.getEmps(emp); System.out.println("getAll : "+list); } @org.junit.Test public void addOne(){ Emp emp = new Emp(); // emp.setEmpno(7300); emp.setComm(0); emp.setDeptno(10); emp.setEname("張三"); emp.setJob("CEO"); emp.setMgr(0); emp.setSal(1); emp.setHiredate(new Date()); int i = empService.addEmp(emp); System.out.println("addOne : "+i); } }
至此:Mybatis 也配置好了;
接下來 我們的目標是寫一個增刪改查的頁面:
前端使用 bootStrap 吧 ; 這個好看;
下面是總體效果:
1: 打開以後界面
2;條件查詢界面:
3:新增或編輯頁面
再看具體的代碼:
先寫頁面吧;
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; String empHomePagePath = basePath + "emp/empHome"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"></base> <!-- 絕對路徑 有這個以後 後面的均可以是相對路徑 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>empHomePage</title> <!-- 引入 bootStrap --> <link rel="stylesheet" style="text/css" href="static/common/bootstrap/css/bootstrap-theme.min.css" /> <link rel="stylesheet" style="text/css" href="static/common/bootstrap/css/bootstrap.min.css" /> <!-- 引入 bootStrap-table --> <link rel="stylesheet" style="text/css" href="static/common/bootstrap-table/css/bootstrap-table.min.css" /> <!-- 引入 bootStrap-datatimepicker --> <link rel="stylesheet" style="text/css" href="static/common/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css" /> </head> <body> This is empHome page . <br /> <br /> <div class="panel-body" style="padding-bottom: 0px;"> <div class="panel panel-primary"> <!-- 查詢條件 div start --> <div class="panel-heading">查詢條件</div> <div class="panel-body"> <form id="formSearch" class="form-horizontal"> <div class="form-group" style="margin-top: 15px"> <label class="control-label col-sm-1" for="query_empno">員工編號</label> <div class="col-sm-1"> <input type="text" class="form-control" id="query_empno"> </div> <label class="control-label col-sm-1" for="query_ename">員工姓名</label> <div class="col-sm-1"> <input type="text" class="form-control" id="query_ename"> </div> <label class="control-label col-sm-1" for="query_job">工做崗位</label> <div class="col-sm-1"> <input type="text" class="form-control" id="query_job"> </div> <label class="control-label col-sm-1" for="query_deptno">部門編號</label> <div class="col-sm-1"> <input type="text" class="form-control" id="query_deptno"> </div> <label class="control-label col-sm-1" for="query_mgr">直接領導</label> <div class="col-sm-1"> <input type="text" class="form-control" id="query_mgr"> </div> <div class="col-sm-2" style="text-align: left;"> <button type="button" style="margin-left: 50px" id="btn_query" class="btn btn-primary">查詢</button> </div> </div> </form> </div> </div> <!-- 查詢條件 div end --> <div id="toolbar" class="btn-group"> <!-- 按鈕組 div start --> <button id="btn_add" type="button" class="btn btn-default"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增 </button> <button id="btn_edit" type="button" class="btn btn-default"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改 </button> <button id="btn_delete" type="button" class="btn btn-default"> <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>刪除 </button> </div> <!-- 按鈕組 div end --> <table id="tb_emp"></table> <!-- 表格 div start --> </div> <!-- 新增和修改 均可以使用 --> <div class="modal fade bs-example-modal-lg" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <!-- 編輯模態框 start --> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title" id="myModalLabel"></h4> </div> <div class="modal-body"> <div class="panel panel-primary"> <div class='panel-heading'> <h3 class='panel-title'>員工信息:</h3> </div> <div class="panel-body"> <form role="form"> <!-- form 表單 start --> <div class="form-group" style="padding: 10px 5px 15px 20px;"> <div class="col-sm-6"> <label for="new_ename">員工姓名</label> <input type="text" class="form-control " id="new_ename" placeholder="請輸入員工姓名"> </div> <div class="col-sm-6"> <label for="new_job">工做崗位</label> <select class="form-control" id="new_job"> <option value="">請選擇工做崗位</option> <option>ANALYST</option> <option>CEO</option> <option>CLERK</option> <option>MANAGER</option> <option>PRESIDENT</option> <option>SALESMAN</option> </select> </div> </div> <br /> <br /> <div class="form-group" style="padding: 10px 5px 15px 20px;"> <div class="col-sm-6"> <label for="new_deptno">部門編號</label> <select class="form-control" id="new_deptno"> <option value="">請選擇工做部門</option> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> </select> </div> <div class="col-sm-6"> <label for="new_mgr">直接領導</label> <input type="text" class="form-control " id="new_mgr" placeholder="請輸入領導編號"> </div> </div> <br /> <br /> <div class="form-group" style="padding: 10px 5px 15px 20px;"> <div class="col-sm-6"> <label for="new_sal">薪水</label> <div class="input-group"> <span class="input-group-addon">$</span> <input type="text" class="form-control" id="new_sal" placeholder="請輸入薪水"> </div> </div> <div class="col-sm-6"> <label for="new_comm">獎金</label> <div class="input-group"> <span class="input-group-addon">$</span> <input type="text" class="form-control" id="new_comm" placeholder="請輸入獎金"> </div> </div> </div> <br /> <br /> <div class="form-group" style="padding: 10px 5px 15px 20px;"> <div class="col-sm-6"> <label for="new_hiredate" class="control-label">入職日期</label> <div class="input-group date form_date" data-date="" data-date-format="yyyy-mm-dd"> <input id="new_hiredate" class="form-control" size="16" type="text" value="" readonly /> <span class="input-group-addon"> <span class="glyphicon glyphicon-remove"></span> </span> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"> </span> </span> </div> </div> </div> <input type="reset" name="reset" style="display: none;" /> <!-- 隱藏了一個重置按鈕,方便清空表單裏的內容 --> </form> <!-- form 表單 end --> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" onclick="clean()" data-dismiss="modal">關閉</button> <button type="button" id="btn_submit" class="btn btn-primary">提交更改</button> </div> </div> </div> </div> <!-- 編輯模態框 end --> <!--對話模態框 --> <div class="modal fade" id="alertModal" tabindex="-1" role="dialog" aria-labelledby="alertModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title" id="alertModalLabel">注意:</h4> </div> <div class="modal-body"> <div id="alertModalContent"></div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button> <button type="button" class="btn btn-primary" data-dismiss="modal">肯定</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal --> </div> <script type="text/javascript" src="static/common/jquery/jquery.min.js"></script> <!-- 引入jquery.js 必須最早引入Jquery.js --> <script type="text/javascript" src="static/common/bootstrap/js/bootstrap.min.js"></script> <!-- 引入bootStrap.js --> <script type="text/javascript" src="static/common/bootstrap-table/js/bootstrap-table.min.js"></script> <!-- 引入bootStrap-table.js --> <script type="text/javascript" src="static/common/bootstrap-table/js/bootstrap-table-zh-CN.min.js"></script> <script type="text/javascript" src="static/common/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js"></script> <!-- 引入bootStrap-datetimepicker.js --> <script type="text/javascript" src="static/common/bootstrap-datetimepicker/js/bootstrap-datetimepicker.zh-CN.js"></script> <script type="text/javascript" src="static/emp/empHome.js"></script> <!-- 引入emphome.js --> <script type="text/javascript"> $(function() { /* 加載完成就開始執行 */ //1.初始化Table var oTable = new TableInit(); oTable.Init(); //2.初始化Button的點擊事件 var oButtonInit = new ButtonInit(); oButtonInit.Init(); }); </script> </body> </html>
接着是js
//1.初始化Table var TableInit = function() { var oTableInit = new Object(); //初始化Table oTableInit.Init = function() { $('#tb_emp') .bootstrapTable( { url : 'emp/getEmps', //請求後臺的URL(*) contentType : 'application/json;charset=utf-8', method : 'get', //請求方式(*) toolbar : '#toolbar', //工具按鈕用哪一個容器 striped : true, //是否顯示行間隔色 cache : false, //是否使用緩存,默認爲true,因此通常狀況下須要設置一下這個屬性(*) pagination : true, //是否顯示分頁(*) sortable : false, //是否啓用排序 sortOrder : "asc", //排序方式 sidePagination : "server", //分頁方式:client客戶端分頁,server服務端分頁(*) // 若是是服務端分頁,返回的結果必須包含total、rows兩個參數。漏寫或錯寫都會致使表格沒法顯示數據。相反,若是是客戶端分頁,這裏要返回一個集合對象到前端。 pageNumber : 1, //初始化加載第一頁,默認第一頁 pageSize : 10, //每頁的記錄行數(*) pageList : [ 10, 25, 50, 100 ], //可供選擇的每頁的行數(*) queryParams : oTableInit.queryParams,//傳遞參數(*) search : false, //是否顯示錶格搜索, strictSearch : false, showColumns : true, //是否顯示全部的列 showRefresh : true, //是否顯示刷新按鈕 minimumCountColumns : 2, //最少容許的列數 clickToSelect : true, //是否啓用點擊選中行 height : 500, //行高,若是沒有設置height屬性,表格自動根據記錄條數以爲表格高度 uniqueId : "empno", //每一行的惟一標識,通常爲主鍵列 showToggle : true, //是否顯示詳細視圖和列表視圖的切換按鈕 cardView : false, //是否顯示詳細視圖 detailView : false, //是否顯示父子表 columns : [ { checkbox : true }, { field : 'empno', title : '員工編號' }, { field : 'ename', title : '員工姓名' }, { field : 'job', title : '工做崗位' }, { field : 'mgr', title : '直接領導' }, { field : 'hiredate', title : '入職日期', formatter : function(value, index, row) { if (value != null) { return formatDateFromNumber(value); } } }, { field : 'sal', title : '薪水' }, { field : 'comm', title : '獎金' }, { field : 'deptno', title : '部門編號' } ] }); }; //獲得查詢的參數 oTableInit.queryParams = function(params) { var temp = { //這裏的鍵的名字和控制器的變量名必須一直,這邊改動,控制器也須要改爲同樣的 limit : params.limit, //頁面大小 offset : params.offset, //偏移量; 就是當前頁是從第幾個開始的 empno : $("#query_empno").val(), ename : $("#query_ename").val(), job : $("#query_job").val(), deptno : $("#query_deptno").val(), mgr : $("#query_mgr").val() }; return temp; }; return oTableInit; }; // 初始化按鈕 var ButtonInit = function() { var oInit = new Object(); var newEmpData = {}; oInit.Init = function() { /* 新增按鈕添加click事件 */ $("#btn_add").click(function() { $("#myModalLabel").text("新增"); newEmpData.empno = ""; $('#myModal').modal() }); /* 編輯按鈕 添加click 事件 */ $("#btn_edit").click( function() { var arrselections = $("#tb_emp").bootstrapTable( 'getSelections'); if (arrselections.length > 1) { alertModal('注意:','只能刪除一條數據!'); return; } if (arrselections.length <= 0) { alertModal('注意:','請選擇有效數據!'); return; } $("#myModalLabel").text("編輯"); var s = arrselections[0].hiredate; var d = formatDateFromNumber(s); $("#new_job").val(arrselections[0].job); $("#new_ename").val(arrselections[0].ename); $("#new_deptno").val(arrselections[0].deptno); $("#new_sal").val(arrselections[0].sal); $("#new_mgr").val(arrselections[0].mgr); $("#new_comm").val(arrselections[0].comm); $("#new_hiredate").val(d); newEmpData.empno = arrselections[0].empno; $('#myModal').modal(); }); /* 提交按鈕添加click 事件 */ $("#btn_submit").click(function() { newEmpData.ename = $("#new_ename").val(); newEmpData.job = $("#new_job").val(); newEmpData.deptno = $("#new_deptno").val(); newEmpData.mgr = $("#new_mgr").val(); newEmpData.sal = $("#new_sal").val(); newEmpData.comm = $("#new_comm").val(); newEmpData.hiredate = $("#new_hiredate").val(); $('#myModal').modal('hide'); clean(); if( ( newEmpData.ename != null && newEmpData.ename != "" ) && ( newEmpData.deptno != null && newEmpData.deptno != "" ) ){ $.ajax({ type : "post", url : "emp/updateEmp", data : newEmpData, success : function(data) { var z = eval('' + data); switch (z) { case "updateOk": alertModal('消息:','更新數據成功!'); break; case "updateFail": alertModal('注意:','更新數據失敗!'); break; case "addOk": alertModal('消息:','添加數據成功!'); break; case "addFail": alertModal('注意:','添加數據失敗!'); break; default: alert(data); break; } $("#tb_emp").bootstrapTable('refresh'); }, error : function() { alertModal('注意:','服務器後臺出錯了!'); } }); }else{ alertModal('注意:','員工的姓名不能爲空!,員工的部門不能爲空!'); } }); /* 刪除按鈕 添加 click 事件 */ $("#btn_delete").click( function() { var arrselections = $("#tb_emp").bootstrapTable( 'getSelections'); if (arrselections.length > 1) { alertModal('注意:','只能刪除一條數據!'); return; } if (arrselections.length <= 0) { alertModal('注意:','請選擇有效數據!'); return; } newEmpData.empno = arrselections[0].empno; var b = confirm("確認要刪除麼?"); if(b){ $.ajax({ type : "post", url : "emp/deleteEmp", data : newEmpData, success : function(data, status) { if (status == "success") { $("#tb_emp").bootstrapTable('refresh'); var x = eval('' + data); if ('deleteOk' == x) { alertModal('消息:','刪除數據成功!'); } else { alertModal('注意:','刪除數據失敗!'); } } }, error : function() { alertModal('注意:','服務器後臺出錯了!'); }, }); } }); /* 查詢按鈕添加 click 事件 */ $("#btn_query").click(function() { $("#tb_emp").bootstrapTable('refresh'); }); }; return oInit; }; /* 設置 form_date */ $('.form_date').datetimepicker({ format: "yyyy-mm-dd", todayBtn : 'linked', todayHighlight : true, startView : 2, minView : 2 }); function clean() { $("input[type=reset]").trigger("click"); } /* 把數字轉化爲日期 */ function formatDateFromNumber(value){ var d = new Date(); d.setTime(value); var y = (d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1); var t = d.getDate() < 10 ? '0' + d.getDate() : d.getDate(); return d.getFullYear() + "-" + y + "-" + t; } /* alert彈出框 */ function alertModal(title,content){ if('消息:' == title){ $('#alertModalLabel').html('<button type="button" class="btn btn-success" disabled="disabled" >消息</button>'); $('#alertModalContent').html('<div class="alert alert-success">'+content+'</div>'); }else if('注意:' == title ){ $('#alertModalLabel').html('<button type="button" class="btn btn-danger" disabled="disabled" >注意</button>'); $('#alertModalContent').html('<div class="alert alert-danger">'+content+'</div>'); } $('#alertModal').modal(); setTimeout("$('#alertModal').modal('hide')",1000); /* 1 秒 後 模態框 自動 關閉 */ }
再接着是 controller
package com.etoak.mssm.emp.controller; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; 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.ResponseBody; import com.etoak.mssm.emp.entity.Emp; import com.etoak.mssm.emp.service.EmpService; @Controller @RequestMapping("/emp") public class EmpConteoller { @Autowired private EmpService empService ; // 跳轉頁面 @RequestMapping("/empHome") public String empHome(){ return "emp/empHome"; } // 返回前臺 //查詢全部符合條件的Emp @RequestMapping("/getEmps") @ResponseBody public Map<String,Object> getEmps(int limit,int offset,String empno , String ename ,String job,String deptno ,String mgr){ Emp emp = new Emp(); emp.setStartSize(offset); emp.setEndSize(offset+limit); if("" != empno ){emp.setEmpno(Integer.parseInt(empno));} emp.setEname(ename); emp.setJob(job); if("" != deptno ){emp.setDeptno(Integer.parseInt(deptno));} if("" != mgr ){emp.setMgr(Integer.parseInt(mgr));} List<Emp> data = empService.getEmps(emp); int total = empService.getCount(emp); Map<String, Object> map = new HashMap<String, Object>();// 定義map map.put("total", total);// total鍵 存放總記錄數,必須的 map.put("rows", data);// rows鍵 存放每頁記錄 list return map; } //新增或更新員工信息 @RequestMapping("/updateEmp") @ResponseBody public String updateEmp(String empno , String ename ,String job,String deptno ,String mgr,String sal,String comm , String hiredate){ Emp emp = new Emp(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); if(null != empno && "" != empno ){emp.setEmpno(Integer.parseInt(empno));} if(null != ename && "" != ename ) emp.setEname(ename); if(null != job && "" != job ) emp.setJob(job); if(null != deptno && "" != deptno ){emp.setDeptno(Integer.parseInt(deptno));} if(null != mgr && "" != mgr ){emp.setMgr(Integer.parseInt(mgr));} if(null != sal && "" != sal ) emp.setSal(Integer.parseInt(sal)); if(null != hiredate && "" != hiredate ){ try { emp.setHiredate(sdf.parse(hiredate)); } catch (ParseException e) { e.printStackTrace(); } } if(emp.getEmpno() != 0 ){ int r = empService.updateEmp(emp);//更新員工信息 if( r == 1 ){ return "updateOk"; }else{ return "updateFail"; } }else{ int r = empService.addEmp(emp); // 添加一個新員工信息 if( r == 1){ return "addOk"; }else{ return "addFail"; } } } //新增或更新員工信息 @RequestMapping("/deleteEmp") @ResponseBody public String deleteEmp(String empno){ Emp emp = new Emp(); if(null != empno && "" != empno ){emp.setEmpno(Integer.parseInt(empno));} int r = empService.deleteEmp(emp); // 添加一個新員工信息 if( r == 1){ return "deleteOk"; }else{ return "deleteFail"; } } }
至此 整個項目 算是 完成了 ;
運行以下:
下面給出 整個項目的源代碼:
連接: https://pan.baidu.com/s/1kV1bfoF 密碼: kv3v