Eclipse使用Maven建立Web項目+整合SSM框架

1、準備環境css

1.maven:apache-maven-3.5.3html

2.jdk:jdk1.8.0_131java

3.tomcat:apache-tomcat-7.0.68mysql

 

2、配置Maven、jdkweb

一、Window——>Preferences——>Maven——>設置本身的Settingsspring

 

二、Window——>Preferences——>Java——>Installed JREs——>Addsql

 

 

3、新建Maven項目數據庫

一、右擊——>New(或者是File——>New)——>other——>Maven——>Maven Project——>Nextexpress

 

 2.這時候,咱們就成功建立出一個Maven項目了,項目結構以下圖:apache

 

3.右擊項目,選擇Properties進行一些配置:

到這裏,咱們的Maven項目就建好了,接下來,咱們來整合搭建SSM(spring MVC + Spring + Mybatis)

 

 

 4、搭建SSM(spring MVC + Spring + Mybatis)

1.修改pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>

  <name>pack</name>
  <groupId>com.geely</groupId>
  <artifactId>pack</artifactId>
  <version>0.0.1-SNAPSHOT</version>
    <url>http://maven.apache.org</url> 
    
        <!-- 用來設置版本號 -->   
    <properties>   
        <srping.version>4.0.2.RELEASE</srping.version>   
        <mybatis.version>3.2.8</mybatis.version>   
        <slf4j.version>1.7.12</slf4j.version>   
        <log4j.version>1.2.17</log4j.version>   
    </properties>  
  <build>
  <finalName>pack</finalName>
    <plugins>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.7</version>
        <configuration>
          <connectors>
            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
              <port>8888</port>
              <maxIdleTime>30000</maxIdleTime>
            </connector>
          </connectors>
          <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory>
          <contextPath>/</contextPath>
        </configuration>
      </plugin>
    </plugins>
  </build>

    <!-- 用到的jar包 -->   
    <dependencies>  
         
        <!-- 單元測試 -->   
        <dependency>   
            <groupId>junit</groupId>   
            <artifactId>junit</artifactId>   
            <version>4.11</version>   
            <!-- 表示開發的時候引入,發佈的時候不會加載此包 -->     
            <scope>test</scope>   
        </dependency>   
        <!-- java ee包 -->   
        <dependency>   
            <groupId>javax</groupId>   
            <artifactId>javaee-api</artifactId>   
            <version>7.0</version>   
        </dependency>   
        <!-- spring框架包 start -->   
        <dependency>   
            <groupId>org.springframework</groupId>   
            <artifactId>spring-test</artifactId>   
            <version>${srping.version}</version>   
        </dependency>   
        <dependency>   
            <groupId>org.springframework</groupId>   
            <artifactId>spring-core</artifactId>   
            <version>${srping.version}</version>   
        </dependency>   
        <dependency>   
            <groupId>org.springframework</groupId>   
            <artifactId>spring-oxm</artifactId>   
            <version>${srping.version}</version>   
        </dependency>   
        <dependency>   
            <groupId>org.springframework</groupId>   
            <artifactId>spring-tx</artifactId>   
            <version>${srping.version}</version>   
        </dependency>   
        <dependency>   
            <groupId>org.springframework</groupId>   
            <artifactId>spring-jdbc</artifactId>   
            <version>${srping.version}</version>   
        </dependency>   
        <dependency>   
            <groupId>org.springframework</groupId>   
            <artifactId>spring-aop</artifactId>   
            <version>${srping.version}</version>   
        </dependency>   
        <dependency>   
            <groupId>org.springframework</groupId>   
            <artifactId>spring-context</artifactId>   
            <version>${srping.version}</version>   
        </dependency>   
        <dependency>   
            <groupId>org.springframework</groupId>   
            <artifactId>spring-context-support</artifactId>   
            <version>${srping.version}</version>   
        </dependency>   
        <dependency>   
            <groupId>org.springframework</groupId>   
            <artifactId>spring-expression</artifactId>   
            <version>${srping.version}</version>   
        </dependency>   
        <dependency>   
            <groupId>org.springframework</groupId>   
            <artifactId>spring-orm</artifactId>   
            <version>${srping.version}</version>   
        </dependency>   
        <dependency>   
            <groupId>org.springframework</groupId>   
            <artifactId>spring-web</artifactId>   
            <version>${srping.version}</version>   
        </dependency>   
        <dependency>   
            <groupId>org.springframework</groupId>   
            <artifactId>spring-webmvc</artifactId>   
            <version>${srping.version}</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>1.2.2</version>   
        </dependency>   
        <!-- mybatis框架包 end -->   
        <!-- 數據庫驅動 -->   
        <dependency>   
            <groupId>mysql</groupId>   
            <artifactId>mysql-connector-java</artifactId>   
            <version>5.1.35</version>   
        </dependency>   
        <!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 -->   
        <dependency>   
            <groupId>commons-dbcp</groupId>   
            <artifactId>commons-dbcp</artifactId>   
            <version>1.4</version>   
        </dependency>   
        <!-- jstl標籤類 -->   
        <dependency>   
            <groupId>jstl</groupId>   
            <artifactId>jstl</artifactId>   
            <version>1.2</version>   
        </dependency>   
        <!-- log start -->   
        <dependency>   
            <groupId>log4j</groupId>   
            <artifactId>log4j</artifactId>   
            <version>${log4j.version}</version>   
        </dependency>   
        <dependency>   
            <groupId>org.slf4j</groupId>   
            <artifactId>slf4j-api</artifactId>   
            <version>${slf4j.version}</version>   
        </dependency>   
        <dependency>   
            <groupId>org.slf4j</groupId>   
            <artifactId>slf4j-log4j12</artifactId>   
            <version>${slf4j.version}</version>   
        </dependency>   
        <!-- log END -->   
        <!-- Json  -->   
        <!-- 格式化對象,方便輸出日誌 -->   
        <dependency>   
            <groupId>com.alibaba</groupId>   
            <artifactId>fastjson</artifactId>   
            <version>1.2.6</version>   
        </dependency>   
        <dependency>   
            <groupId>org.codehaus.jackson</groupId>   
            <artifactId>jackson-mapper-asl</artifactId>   
            <version>1.9.13</version>   
        </dependency>   
        <!-- 上傳組件包 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>  

</project>
pom.xml

2.在src/main/resources下添加配置文件:applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>   
<beans xmlns="http://www.springframework.org/schema/beans"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"   
    xmlns:context="http://www.springframework.org/schema/context"   
    xmlns:mvc="http://www.springframework.org/schema/mvc"   
    xsi:schemaLocation="http://www.springframework.org/schema/beans     
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd     
                        http://www.springframework.org/schema/context     
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd     
                        http://www.springframework.org/schema/mvc     
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">   
                             
    <!-- 使用註解式注入 -->   
    <context:annotation-config />   
         
    <!-- 自動掃描 -->   
    <context:component-scan base-package="com.geely" />   
         
    <!-- 導入DAO配置 -->   
    <import resource="spring-dao.xml"/>   
         
    <!-- 導入數據庫配置 -->   
    <import resource="spring-db.xml"/>   
         
    <!-- 導入數據庫配置 -->   
    <import resource="spring-tx.xml"/>   
         
</beans>
applicationContext.xml

3.在src/main/resources下配置數據庫鏈接池:jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/vee?useUnicode=true&characterEncoding=utf8
username=root
password=6665508a
#定義初始鏈接數   
initialSize=0   
#定義最大鏈接數   
maxActive=20   
#定義最大空閒   
maxIdle=20   
#定義最小空閒   
minIdle=1   
#定義最長等待時間   
maxWait=60000  
jdbc.properties

4.在src/main/resources下配置日誌:log4j.properties

#定義LOG輸出級別   
log4j.rootLogger=INFO,Console,File   
#定義日誌輸出目的地爲控制檯   
log4j.appender.Console=org.apache.log4j.ConsoleAppender   
log4j.appender.Console.Target=System.out   
#能夠靈活地指定日誌輸出格式,下面一行是指定具體的格式   
log4j.appender.Console.layout = org.apache.log4j.PatternLayout   
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n   
     
#文件大小到達指定尺寸的時候產生一個新的文件   
log4j.appender.File = org.apache.log4j.RollingFileAppender   
#指定輸出目錄   
log4j.appender.File.File = logs/debug.log   
#定義文件最大大小   
log4j.appender.File.MaxFileSize = 10MB   
# 輸出因此日誌,若是換成DEBUG表示輸出DEBUG以上級別日誌   
log4j.appender.File.Threshold = ALL   
log4j.appender.File.layout = org.apache.log4j.PatternLayout   
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
log4j.properties

5.在src/main/resources下配置咱們的ioc注入:spring-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:p="http://www.springframework.org/schema/p"   
    xmlns:context="http://www.springframework.org/schema/context"   
    xmlns:mvc="http://www.springframework.org/schema/mvc"   
    xsi:schemaLocation="http://www.springframework.org/schema/beans     
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd     
                        http://www.springframework.org/schema/context     
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd     
                        http://www.springframework.org/schema/mvc     
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">   
                             
                             
    <!-- DAO接口所在包名,Spring會自動查找其下的類 -->   
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">   
        <!--basePackage指定要掃描的包,在此包之下的映射器都會被搜索到。   
         可指定多個包,包與包之間用逗號或分號分隔-->   
        <property name="basePackage" value="com.geely.dao" />   
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>   
    </bean>                          
                             
</beans>
spring-dao.xml

6.在src/main/resources下配置spring-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:p="http://www.springframework.org/schema/p"   
    xmlns:context="http://www.springframework.org/schema/context"   
    xmlns:mvc="http://www.springframework.org/schema/mvc"   
    xsi:schemaLocation="http://www.springframework.org/schema/beans     
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd     
                        http://www.springframework.org/schema/context     
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd     
                        http://www.springframework.org/schema/mvc     
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">   
     
    <!-- 引入配置文件 -->   
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">   
        <property name="location" value="classpath:jdbc.properties" />   
    </bean>   
         
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">   
        <property name="driverClassName" value="${driver}" />   
        <property name="url" value="${url}" />   
        <property name="username" value="${username}" />   
        <property name="password" value="${password}" />   
        <!-- 初始化鏈接大小 -->   
        <property name="initialSize" value="${initialSize}"></property>   
        <!-- 鏈接池最大數量 -->   
        <property name="maxActive" value="${maxActive}"></property>   
        <!-- 鏈接池最大空閒 -->   
        <property name="maxIdle" value="${maxIdle}"></property>   
        <!-- 鏈接池最小空閒 -->   
        <property name="minIdle" value="${minIdle}"></property>   
        <!-- 獲取鏈接最大等待時間 -->   
        <property name="maxWait" value="${maxWait}"></property>   
    </bean>   
     
    <!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 -->   
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">   
        <property name="dataSource" ref="dataSource" />   
        <!-- 自動掃描mapping.xml文件 -->   
        <property name="mapperLocations" value="classpath:com/geely/mapper/*.xml"></property>   
    </bean>   
         
</beans>
spring-db.xml

7.在src/main/resources下配置spring的事務管理器

<?xml version="1.0" encoding="UTF-8"?>   
<beans xmlns="http://www.springframework.org/schema/beans"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"   
    xmlns:context="http://www.springframework.org/schema/context"   
    xmlns:mvc="http://www.springframework.org/schema/mvc"   
    xsi:schemaLocation="http://www.springframework.org/schema/beans     
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd     
                        http://www.springframework.org/schema/context     
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd     
                        http://www.springframework.org/schema/mvc     
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">   
     
    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->   
    <bean id="transactionManager"   
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
        <property name="dataSource" ref="dataSource" />   
    </bean>   
         
</beans>
spring-tx.xml

 

5、整合spring mvc

1.在web-inf目錄下配置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:p="http://www.springframework.org/schema/p"   
    xmlns:context="http://www.springframework.org/schema/context"   
    xmlns:mvc="http://www.springframework.org/schema/mvc"   
    xsi:schemaLocation="http://www.springframework.org/schema/beans     
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd     
                        http://www.springframework.org/schema/context     
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd     
                        http://www.springframework.org/schema/mvc     
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">   
                             
    <!--避免IE執行AJAX時,返回JSON出現下載文件 -->   
    <bean id="mappingJacksonHttpMessageConverter"   
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">   
        <property name="supportedMediaTypes">   
            <list>   
                <value>text/html;charset=UTF-8</value>   
            </list>   
        </property>   
    </bean>   
         
     <!-- 添加註解驅動 -->     
    <mvc:annotation-driven />   
    <mvc:default-servlet-handler/>   
         
    <!-- 設置使用註解的類所在的包 -->   
    <context:component-scan base-package="com.geely.controller" />   
         
    <!-- 完成請求和註解POJO的映射 -->   
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">   
        <property name="messageConverters">   
            <list>   
                <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON轉換器 -->   
            </list>   
        </property>   
    </bean>   
         
    <!-- 定義跳轉的文件的先後綴 ,視圖模式配置-->   
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">   
        <!-- 這裏的配置個人理解是自動給後面action的方法return的字符串加上前綴和後綴,變成一個 可用的url地址 -->   
        <property name="prefix" value="/WEB-INF/jsp/" />   
        <property name="suffix" value=".jsp" />   
    </bean>   
         
    <!-- SpringMVC上傳文件時,須要配置MultipartResolver處理器-->   
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">     
        <!-- 默認編碼 -->   
        <property name="defaultEncoding" value="utf-8" />     
        <!-- 文件大小最大值 -->   
        <property name="maxUploadSize" value="10485760000" />     
        <!-- 內存中的最大值 -->   
        <property name="maxInMemorySize" value="40960" />     
    </bean>    
     
</beans>
spring-mvc.xml

2.修改web.xml

<?xml version="1.0" encoding="UTF-8"?>   
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns="http://java.sun.com/xml/ns/javaee"   
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"   
    version="3.0">   
    <display-name>Archetype Created Web Application</display-name>   
         
    <welcome-file-list>   
        <welcome-file>/index.jsp</welcome-file>   
    </welcome-file-list>   
         
    <!-- 加載spring bean -->   
    <context-param>   
         <param-name>contextConfigLocation</param-name>   
        <param-value>classpath:applicationContext.xml</param-value>   
    </context-param>   
    <listener>   
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   
    </listener>   
         
    <!-- 編碼過濾器 -->   
    <filter>   
        <filter-name>encodingFilter</filter-name>   
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>   
        <async-supported>true</async-supported>   
        <init-param>   
            <param-name>encoding</param-name>   
            <param-value>UTF-8</param-value>   
        </init-param>   
    </filter>   
    <filter-mapping>   
        <filter-name>encodingFilter</filter-name>   
        <url-pattern>/*</url-pattern>   
    </filter-mapping>   
         
    <!-- Spring MVC servlet -->   
    <servlet>   
        <servlet-name>SpringMVC</servlet-name>   
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>   
        <init-param>   
            <param-name>contextConfigLocation</param-name>   
            <param-value>/WEB-INF/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>   
         
</web-app>
web.xml

6、添加包、接口、類

1.目錄結構圖

package com.geely.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.geely.entity.User;
import com.geely.service.IUserService;

@Controller   
@RequestMapping("/user") 
public class UserController {
    @Resource   
    private IUserService userService;   
         
    @RequestMapping("/userList")   
    public String userList(HttpServletRequest request,Model model){   
        List<User> uList = userService.getAllUser();   
        model.addAttribute("uList", uList);   
        return "userList";   
    }  
    
    
    @RequestMapping("/showUser")   
    public String showUser(HttpServletRequest request,Model model){   
        int userId = Integer.parseInt(request.getParameter("id"));   
        User user = userService.getUserById(userId);   
        model.addAttribute("user", user);   
        return "showUser";   
    }   
         
    @RequestMapping("/addUserUI")   
    public String addUserUI(){   
        return "addUser";   
    }   
         
    @RequestMapping("/addUser")   
    public String addUser(HttpServletRequest request,Model model){   
        User user = new User();   
        user.setName(String.valueOf(request.getParameter("name")));   
        user.setPassword(String.valueOf(request.getParameter("password")));   
        user.setAge(Integer.parseInt(String.valueOf(request.getParameter("age"))));   
        userService.addUser(user);   
        return "redirect:/user/userList";   
    }   
}
UserController
package com.geely.dao;

import java.util.List;
import java.util.Map;

import com.geely.entity.User;

public interface IUserDao {
    public User queryByPrimaryKey(Integer id);   
    
    public List<User> queryUserByBatch(Map<String,Object> params);   
         
    public void insertUser(User user);   
         
    public void insertUserByBatch(List<User> list);   
         
    public void deleteByPrimaryKey(Integer id);   
         
    public void delteUserByBatch(Map<String,Object> params);   
         
    public void updateByPrimaryKey(Integer id);   
     
    public List<User> getAllUser(); 
}
IUserDao
package com.geely.entity;

public class User {
    private int id;
    private String name;
    private String password;
    private int age;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }


}
User
<?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.geely.dao.IUserDao" >     
    <resultMap id="BaseResultMap" type="com.geely.entity.User">   
        <result column="id" property="id" jdbcType="INTEGER" />   
        <result column="name" property="name" jdbcType="VARCHAR" />   
        <result column="password" property="password" jdbcType="VARCHAR" />   
        <result column="age" property="age" jdbcType="INTEGER" />   
    </resultMap>   
     
    <sql id="Base_Column_List">   
        id, name, password, age   
    </sql>   
     
    <!-- 查詢用戶-->   
    <select id="queryByPrimaryKey" resultMap="BaseResultMap"   
        parameterType="java.lang.Integer">   
        select   
        <include refid="Base_Column_List" />   
        from user   
        where id = #{id,jdbcType=INTEGER}   
    </select>   
         
    <!-- 查詢用戶-->   
    <select id="getAllUser" resultMap="BaseResultMap">   
        select   
        <include refid="Base_Column_List" />   
        from user   
    </select>   
         
    <!-- 批量查詢用戶-->   
    <select id="queryUserByBatch" resultMap="BaseResultMap"   
        parameterType="java.util.Map">   
        select   
        <include refid="Base_Column_List" />   
        from user   
        where id in   
        <foreach collection="idList" item="userId" index="index" open="(" separator="," close=")">   
             #{userId,jdbcType=DECIMAL}   
        </foreach>   
    </select>   
         
    <!-- 插入用戶 -->   
    <insert id="insertUser" parameterType="com.geely.entity.User">   
        insert into user     
        <trim prefix="(" suffix=")" suffixOverrides="," >     
          <if test="id != null" >     
            id,     
          </if>     
          <if test="name != null" >     
            name,     
          </if>     
          <if test="password != null" >     
            password,     
          </if>     
          <if test="age != null" >     
            age,     
          </if>     
        </trim>     
        <trim prefix="values (" suffix=")" suffixOverrides="," >     
          <if test="id != null" >     
            #{id,jdbcType=INTEGER},     
          </if>     
          <if test="name != null" >     
            #{name,jdbcType=VARCHAR},     
          </if>     
          <if test="password != null" >     
            #{password,jdbcType=VARCHAR},     
          </if>     
          <if test="age != null" >     
            #{age,jdbcType=INTEGER},     
          </if>     
        </trim>      
    </insert>   
         
    <!-- 批量插入用戶 -->   
    <insert id="insertUserByBatch" parameterType="java.util.List" >   
    insert into USER   
       (ID,   
        NAME,   
        PASSWORD,   
        AGE)   
    select A.* from   
         (   
         <foreach collection="list" item="user" index="index" separator="union">   
             select    
             #{user.id,jdbcType=INTEGER},   
             #{user.name,jdbcType=VARCHAR},   
             #{user.password,jdbcType=VARCHAR},   
             #{user.age,jdbcType=INTEGER}   
              from dual   
         </foreach>   
         ) A   
    </insert>   
     
    <!-- 刪除用戶 -->   
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">   
        delete from user   
        where id = #{id,jdbcType=INTEGER}     
    </delete>   
         
    <!-- 批量刪除用戶 -->   
    <delete id="deleteUserByBatch" parameterType="java.util.Map" >   
     delete from user   
     where id IN    
         <foreach item="ids" collection="iList" open="(" separator="," close=")">   
             #{ids,jdbcType=DECIMAL}   
         </foreach>   
    </delete>   
     
    <!-- 更新用戶 -->   
    <update id="updateByPrimaryKey" parameterType="com.geely.entity.User" >     
        update user     
        <set >     
          <if test="name != null" >     
            name = #{name,jdbcType=VARCHAR},     
          </if>     
          <if test="password != null" >     
            password = #{password,jdbcType=VARCHAR},     
          </if>     
          <if test="age != null" >     
            age = #{age,jdbcType=INTEGER},     
          </if>     
        </set>     
        where id = #{id,jdbcType=INTEGER}    
    </update>   
       
</mapper>
UserMapper.xml
package com.geely.service;

import java.util.List;

import com.geely.entity.User;

public interface IUserService {
     public User getUserById(int userId);   
     
        public void insertUser(User user);   
         
        public void addUser(User user);   
         
        public List<User> getAllUser();   
}
IUserService
package com.geely.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.geely.dao.IUserDao;
import com.geely.entity.User;

@Service("userService")   
public class UserServiceImpl implements IUserService {   
    @Resource   
    private IUserDao userDao;   
         
    public User getUserById(int userId) {   
        return userDao.queryByPrimaryKey(userId);   
    }   
     
    public void insertUser(User user) {   
        userDao.insertUser(user);   
    }   
     
    public void addUser(User user) {   
        userDao.insertUser(user);   
    }   
     
     
    public List<User> getAllUser() {   
        return userDao.getAllUser();   
    }   
     
}
UserServiceImpl

 7.新建視圖

1.在WEB-INF文件夾下新建jsp文件夾

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>   
<%   
String path = request.getContextPath();  
String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+ "/";%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">   
<html>   
  <head>   
    <base href="<%=basePath%>">   
         
    <title>My JSP 'userinfo.jsp' starting page</title>   
         
    <meta http-equiv="pragma" content="no-cache">   
    <meta http-equiv="cache-control" content="no-cache">   
    <meta http-equiv="expires" content="0">       
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">   
    <meta http-equiv="description" content="This is my page">   
    <!-- 
    <link rel="stylesheet" type="text/css" href="styles.css"> 
    -->   
     
  </head>   
       
  <body>   
    <form id="addUser" action="<%=basePath %>user/addUser" method="post">    
        name: <input id="name" name="name" /><br/>    
        password: <input id="password" name="password" /><br/>   
         age: <input id="age" name="age" /><br/>   
        <input type="submit" value="添加新用戶"/>    
    </form>   
  </body>   
</html>
addUser.jsp

到此,框架成。

相關文章
相關標籤/搜索