1. 程式人生 > >SSM框架+thymeleaf實現基本的增刪改查

SSM框架+thymeleaf實現基本的增刪改查

前言

本文使用了SSM框架、thymeleaf和jquery實現了基本的增刪改查。

 

名詞解釋

SSM框架:springMVC、spring、mybatis

thymeleaf:一個與Velocity、FreeMarker類似的模板引擎

jquery:一個快速、簡潔的JavaScript框架

 

程式結構

 

本程式框架是用maven建出來的,具體如圖:

 

程式原始碼

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<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>org.hanzx</groupId> <artifactId>webssm</artifactId
> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>webssm Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>
UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.9</maven.compiler.source> <maven.compiler.target>1.9</maven.compiler.target> <spring.version>4.2.5.RELEASE</spring.version> <mybatis.version>3.2.1</mybatis.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mysql.version>5.1.35</mysql.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- 新增Spring依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!--spring單元測試依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <!-- spring webmvc相關jar --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- mysql驅動包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- alibaba data source 相關jar包--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>0.2.23</version> </dependency> <!-- alibaba fastjson 格式化對 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <!-- logback 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>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>org.logback-extensions</groupId> <artifactId>logback-ext-spring</artifactId> <version>0.1.1</version> </dependency> <!--mybatis依賴 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.0</version> </dependency> <!-- 新增servlet3.0核心包 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.2-b01</version> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--thymeleaf--> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.9.RELEASE</version> </dependency> </dependencies> <build> <finalName>webssm</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>

 

spring配置檔案

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: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">

    <!-- 1.配置jdbc檔案 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations" value="classpath:jdbc.properties"/>
    </bean>

    <!-- 2.掃描的包路徑,這裡不掃描被@Controller註解的類 --><!--使用<context:component-scan/> 可以不再配置<context:annotation-config/> -->
    <context:component-scan base-package="org.hanzx">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <import resource="classpath:spring-mybatis.xml" />
    <!--<import resource="classpath:spring-mvc.xml" />-->
</beans>

 

springMVC配置檔案

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" xmlns:p="http://www.springframework.org/schema/p"
       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">

    <!-- 掃描controller(controller層注入) -->
    <context:component-scan base-package="org.hanzx.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <mvc:annotation-driven />

    <!-- 內容協商管理器  -->
    <!--1、首先檢查路徑副檔名(如my.pdf);2、其次檢查Parameter(如my?format=pdf);3、檢查Accept Header-->
    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <!-- 副檔名至mimeType的對映,即 /user.json => application/json -->
        <property name="favorPathExtension" value="true"/>
        <!-- 用於開啟 /userinfo/123?format=json 的支援 -->
        <property name="favorParameter" value="true"/>
        <property name="parameterName" value="format"/>
        <!-- 是否忽略Accept Header -->
        <property name="ignoreAcceptHeader" value="false"/>

        <property name="mediaTypes"> <!--副檔名到MIME的對映;favorPathExtension, favorParameter是true時起作用  -->
            <value>
                json=application/json
                xml=application/xml
                html=text/html
            </value>
        </property>
        <!-- 預設的content type -->
        <property name="defaultContentType" value="text/html"/>
    </bean>


    <!-- 當在web.xml 中   DispatcherServlet使用 <url-pattern>/</url-pattern> 對映時,能對映靜態資源 -->
    <mvc:default-servlet-handler />
    <!-- 靜態資源對映 -->
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>


    <!-- 對模型檢視新增前後綴 -->
    <!--<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"-->
          <!--p:prefix="/WEB-INF/pages/" p:suffix=".jsp"/>-->

    <bean id="templateResolver"
          class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
        <property name="prefix" value="/WEB-INF/templates/"/>
        <property name="suffix" value=".html"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="order" value="1"/>
        <property name="templateMode" value="HTML5"/>
        <property name="cacheable" value="false"/>
    </bean>

    <bean id="templateEngine"
          class="org.thymeleaf.spring5.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver"/>
    </bean>

    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine"/>
        <property name="characterEncoding" value="UTF-8"/>
    </bean>


</beans>

 

mybatis配置檔案

spring-mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 3.配置資料來源 ,使用的alibba的資料庫-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 基本屬性 url、user、password -->
        <property name="driverClassName" value="${jdbc_driverClassName}"/>
        <property name="url" value="${jdbc_url}"/>
        <property name="username" value="${jdbc_username}"/>
        <property name="password" value="${jdbc_password}"/>

        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="10"/>
        <property name="minIdle" value="10"/>
        <property name="maxActive" value="50"/>

        <!-- 配置獲取連線等待超時的時間 -->
        <property name="maxWait" value="60000"/>
        <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />

        <!-- 配置一個連線在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />

        <property name="validationQuery" value="SELECT 'x'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        <!-- 開啟PSCache,並且指定每個連線上PSCache的大小  如果用Oracle,則把poolPreparedStatements配置為true,mysql可以配置為false。-->
        <property name="poolPreparedStatements" value="false" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />

        <!-- 配置監控統計攔截的filters -->
        <property name="filters" value="wall,stat" />
    </bean>



    <!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描mapping.xml檔案 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>


    <!-- DAO介面所在包名,Spring會自動查詢其下的類 ,自動掃描了所有的XxxxMapper.xml對應的mapper介面檔案,只要Mapper介面類和Mapper對映檔案對應起來就可以了-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="org.hanzx.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
    <!-- 配置事務管理器 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--======= 事務配置 End =================== -->
    <!-- 配置基於註解的宣告式事務 -->
    <!-- enables scanning for @Transactional annotations -->
    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

 

jdbc資料庫連線配置檔案

jdbc.properties

jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/web_test?useUnicode=true&characterEncoding=utf8
jdbc_username=root
jdbc_password=root

 

log配置檔案

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- 儘量別用絕對路徑,如果帶引數不同容器路徑解釋可能不同,以下配置引數在pom.xml裡 -->
    <property name="log.root.level" value="${log.root.level}" /> <!-- 日誌級別 -->
    <property name="log.other.level" value="${log.other.level}" /> <!-- 其他日誌級別 -->
    <property name="log.base" value="${log.base}" /> <!-- 日誌路徑,這裡是相對路徑,web專案eclipse下會輸出到eclipse的安裝目錄下,如果部署到linux上的tomcat下,會輸出到tomcat/bin目錄 下 -->
    <property name="log.moduleName" value="${log.moduleName}" />  <!-- 模組名稱, 影響日誌配置名,日誌檔名 -->
    <property name="log.max.size" value="100MB" /> <!-- 日誌檔案大小,超過這個大小將被壓縮 -->

    <!--控制檯輸出 -->
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <Pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method\(\):%L -%msg%n</Pattern>
        </encoder>
    </appender>

    <!-- 用來儲存輸出所有級別的日誌 -->
    <appender name="file.all" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${log.base}/${log.moduleName}.log</File><!-- 設定日誌不超過${log.max.size}時的儲存路徑,注意如果
            是web專案會儲存到Tomcat的bin目錄 下 -->
        <!-- 滾動記錄檔案,先將日誌記錄到指定檔案,當符合某個條件時,將日誌記錄到其他檔案。 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${log.base}/archive/${log.moduleName}_all_%d{yyyy-MM-dd}.%i.log.zip
            </FileNamePattern>
            <!-- 檔案輸出日誌 (檔案大小策略進行檔案輸出,超過指定大小對檔案備份) -->
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log.max.size}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <!-- 日誌輸出的檔案的格式 -->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method\(\):%L -%msg%n</pattern>
        </layout>
    </appender>

    <!-- 這也是用來儲存輸出所有級別的日誌 -->
    <appender name="file.all.other" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${log.base}/${log.moduleName}_other.log</File>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${log.base}/archive/${log.moduleName}_other_%d{yyyy-MM-dd}.%i.log.zip
            </FileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log.max.size}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{56}.%method\(\):%L -%msg%n</pattern>
        </layout>
    </appender>

    <!-- 只用儲存輸出error級別的日誌 -->
    <appender name="file.error"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${log.base}/${log.moduleName}_err.log</File>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${log.base}/archive/${log.moduleName}_err_%d{yyyy-MM-dd}.%i.log.zip
            </FileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${log.max.size}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{56}.%method\(\):%L - %msg%n</pattern>
        </layout>
        <!-- 下面為配置只輸出error級別的日誌 -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <!-- 不丟失日誌.預設的,如果佇列的80%已滿,則會丟棄TRACT、DEBUG、INFO級別的日誌 -->
    <!-- 更改預設的佇列的深度,該值會影響效能.預設值為256 -->
    <!-- 新增附加的appender,最多隻能新增一個 -->
    <appender name="file.async" class="ch.qos.logback.classic.AsyncAppender">
        <discardingThreshold>0</discardingThreshold>
        <queueSize>256</queueSize>
        <includeCallerData>true</includeCallerData>
        <appender-ref ref="file.all" />
    </appender>

    <appender name="file.async.other" class="ch.qos.logback.classic.AsyncAppender">
        <discardingThreshold>0</discardingThreshold>
        <queueSize>256</queueSize>
        <includeCallerData>true</includeCallerData>
        <appender-ref ref="file.all.other" />
    </appender>

    <!-- 為某個包下的所有類的指定Appender 這裡也可以指定類名稱例如:com.aa.bb.ClassName -->
    <logger name="com.lin" additivity="false">
        <level value="${log.root.level}" />
        <appender-ref ref="stdout" />
        <appender-ref ref="file.async" /><!-- 即com.lin包下級別為 ${log.root.level}的才會使用file.async來列印 -->
        <appender-ref ref="file.error" />
    </logger>

    <!-- root將級別為${log.root.level}及大於${log.root.level}的日誌資訊交給已經配置好的名為“Console”的appender處理,“Console”appender將資訊列印到Console,其它同理 -->
    <root level="${log.root.level}">
        <appender-ref ref="stdout" /> <!--  標識這個appender將會新增到這個logger -->
        <appender-ref ref="file.async.other" />
        <appender-ref ref="file.error" />
    </root>
</configuration>

 

UserController

package org.hanzx.controller;

import org.hanzx.model.User;
import org.hanzx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    private String prefix = "user/";

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value="/getAllUser")
    public String getAllUser(ModelMap modelMap){
        modelMap.put("userList", userService.getAllUser());
        return prefix + "user_list";
    }

    @RequestMapping(value="/getUserDetailForm")
    public String getUserDetailForm(ModelMap modelMap, Integer id){
        if (id != null){
            modelMap.put("user", userService.getUserById(id));
        }
        return prefix + "user_detail";
    }

    @RequestMapping(value="/addUser")
    public String addUser(User user){
        userService.addUser(user);
        return "redirect:getAllUser";
    }

    @RequestMapping(value="/updateUser")
    public String updateUser(User user){
        userService.updateUser(user);
        return "redirect:getAllUser";
    }

    @RequestMapping(value="/deleteUser")
    @ResponseBody
    public String deleteUser(@RequestParam(value = "ids[]") Integer[] ids){
        userService.deleteUser(ids);
        return "true";
    }


}

 

userService

package org.hanzx.service;


import org.hanzx.model.User;

import java.util.List;

public interface UserService {

    List<User> getAllUser();

    void addUser(User user);

    User getUserById(Integer id);

    void updateUser(User user);

    void deleteUser(Integer[] ids);
}

 

userServiceImpl

package org.hanzx.service.impl;

import org.hanzx.dao.UserDao;
import org.hanzx.entity.User;
import org.hanzx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService{

    private final UserDao userDao;

    @Autowired
    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public List<org.hanzx.model.User> getAllUser() {
        List<User> userList = userDao.getAllUser();
        List<org.hanzx.model.User> userModelList = new ArrayList<>();
        for (User user : userList){
            org.hanzx.model.User userModel = new org.hanzx.model.User();
            userModel.setName(user.getName());
            userModel.setId(user.getId());
            userModel.setAge(user.getAge());
            userModelList.add(userModel);
        }
        return userModelList;
    }

    @Override
    public void addUser(org.hanzx.model.User user) {
        User userEntity = new User();
        userEntity.setName(user.getName());
        userEntity.setAge(user.getAge());
        userEntity.setPassword(user.getPassword());
        userDao.addUser(userEntity);
    }

    @Override
    public org.hanzx.model.User getUserById(Integer id) {
        User userEntity = userDao.getUserById(id);
        org.hanzx.model.User user = new org.hanzx.model.User();
        user.setAge(userEntity.getAge());
        user.setId(userEntity.getId());
        user.setName(userEntity.getName());
        user.setPassword(userEntity.getPassword());
        return user;
    }

    @Override
    public void updateUser(org.hanzx.model.User user) {
        User userEntity = userDao.getUserById(user.getId());
        userEntity.setPassword(user.getPassword());
        userEntity.setAge(user.getAge());
        userEntity.setName(user.getName());
        userDao.updateUser(userEntity);
    }

    @Override
    public void deleteUser(Integer[] ids) {
        for (Integer id : ids){
            userDao.deleteUserById(id);
        }
    }
}

 

userDao

package org.hanzx.dao;


import org.hanzx.entity.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserDao {

    List<User> getAllUser();

    void addUser(User user);

    User getUserById(Integer id);

    void updateUser(User user);

    void deleteUserById(Integer id);
}

 

entity User

package org.hanzx.entity;



public class User {

    private Integer id;

    private String name;

    private Integer age;

    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

 

model User

package org.hanzx.model;



public class User {

    private Integer id;

    private String name;

    private Integer age;

    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

 

userMapper.xml

<?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="org.hanzx.dao.UserDao">
    <resultMap id="BaseResultMap" type="org.hanzx.entity.User" >
        <id 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>
    <select id="getAllUser" resultMap="BaseResultMap" >
      SELECT * FROM user;
    </select>

    <insert id="addUser">
        INSERT USER VALUES (null, #{name}, #{age}, #{password});
    </insert>

    <select id="getUserById" resultMap="BaseResultMap">
        SELECT * FROM user WHERE user.id = #{id};
    </select>

    <update id="updateUser">
        UPDATE user SET name = #{name}, age = #{age}, password = #{password} WHERE id = #{id};
    </update>

    <delete id="deleteUserById">
        DELETE FROM user where id = #{id};
    </delete>

</mapper>

 

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!-- 讀取spring配置檔案 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <context-param>
    <param-name>logbackConfigLocation</param-name>
    <param-value>classpath:logback.xml</param-value>
  </context-param>

  <!-- 設計路徑變數值
  <context-param>
      <param-name>webAppRootKey</param-name&