用 eclipse 创建一个简单的 meaven spring springMvc mybatis 项目

   

 

下面是整体步骤:

1: 先创建一个Maven 项目:

选择跳过骨架:

因为要搭建的是 web 项目  所以这个地方选择 war 包; 

点击完成 这样就完成 Maven项目的搭建:

接下俩 先把 Maven的pom.xml 需要的依赖 添加上:

<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 报错的话 ; 看一下 报什么错;

这里说: web.xml is missing and <failOnMissingWebXml> is set to true ;

翻译一下: web.xml 文件 缺失 并且 <缺失webxml就失败> 这个元素被设为 true  ; 所以会报错:

因为咱们开头的时候 是 跳过 使用骨架 所以 现在目录结构中没有 web.xml文件; 所以下一步就把项目转成动态web 项目:

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 &lt; #{endSize}  
        </if>
        ) b where 1 = 1
        <if test="startSize != null and startSize != ''">
            and b.rn &gt;= #{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">&times;</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">&times;</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

posted @ 2017-06-19 16:00  三目鸟  阅读(2944)  评论(0编辑  收藏  举报