1. 程式人生 > >SSM整合(實現全部使用者查詢)

SSM整合(實現全部使用者查詢)

準備

1、建立工程(我建立了一個maven工程)

2、pom檔案匯入依賴:

https://blog.csdn.net/qq_43154385/article/details/84308826

3、工程結構

程式碼

mybatis-config.xml(SqlMapConfig)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>  
    <!-- 定義全域性開關,隻影響mybatis的工作行為 -->
    <settings>
        <!-- 開啟駝峰自動對映開關 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!-- 起別名,給實體類起別名,簡單方便 -->
    <typeAliases>
        <package name="com.buba.witkey.pojo"/>
    </typeAliases>
    <!-- 
       plugins在配置檔案中的位置必須符合要求,否則會報錯,順序如下:
       properties?, settings?, 
       typeAliases?, typeHandlers?, 
       objectFactory?,objectWrapperFactory?, 
       plugins?, 
       environments?, databaseIdProvider?, mappers?
   -->
<plugins>
    <!-- com.github.pagehelper為PageHelper類所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
         
    </plugin>
</plugins>
</configuration>

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:aop="http://www.springframework.org/schema/aop"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    <!-- 0:讀外部的配置檔案 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
    <!-- 1.配置資料來源 ,jdbc|c3p0|dbcp資料來源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!--<property name="driver" value="${db.driver}"></property>-->
        <property name="url" value="${url}"></property>
        <property name="username" value="${user}"></property>
        <property name="password" value="${password}"></property>
        <property name="maxActive" value="${maxActive}"></property>
    </bean>
    
    <!-- 2.sqlSessionFactory
    dataSource:上面宣告過的資料來源
    configLocation:mybatis核心配置檔案的路徑 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>
    
    <!-- 3.掃描dao下所有的介面和mapper對映檔案
           basePackage:持久層的包名
           sqlSessionFactoryBeanName:上面宣告過的sqlSessionFactory -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.buba.witkey.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
    
    <!-- 4.包掃描進行註解的裝配
           base-package:模組名 -->
    <context:component-scan base-package="com.buba.witkey.serviceImpl"></context:component-scan>
    
    <!-- 5.配置事務 -->
    <!-- 5.1事務管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 5.2事務的通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="select*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="del*" propagation="REQUIRED"/>
            <tx:method name="apply*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!-- 5.3事務的aop配置 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.buba.witkey.service.*.*(..))"
            id="txAllMethod"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txAllMethod"/>
    </aop:config>
    

</beans>

springMVC.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-4.0.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">


    <!-- mvc註解驅動 -->
    <mvc:annotation-driven></mvc:annotation-driven>

    
    <!-- 4.真正的後端處理器 -->
    <!-- 類上有@Controller註解的元件才是後端控制器 -->
    <context:component-scan base-package="com.buba.witkey.controller"></context:component-scan>
    
    
    <!-- 5.檢視解析器 -->
    <!-- 根據邏輯檢視解析的物理檢視為:/jsps/邏輯路徑.jsp -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>


    <!-- 放行靜態資源 -->
    <mvc:default-servlet-handler/>
    <!-- <mvc:resources mapping="/easyUI/**" location="/easyUI/" />
    <mvc:resources mapping="/imags/**" location="/imags/"/>
    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/zTree_v3/**" location="/zTree_v3/"/>
    <mvc:resources mapping="/images/**" location="/images/"/>
    -->

</beans>

jdbc.properties

driver=com.mysql.jdbc.Driver
#\u5728\u548Cmysql\u4F20\u9012\u6570\u636E\u7684\u8FC7\u7A0B\u4E2D\uFF0C\u4F7F\u7528unicode\u7F16\u7801\u683C\u5F0F\uFF0C\u5E76\u4E14\u5B57\u7B26\u96C6\u8BBE\u7F6E\u4E3Autf-8
url=jdbc:mysql://localhost:3306/witkey?characterEncoding=utf-8
user=root
password=root

maxActive=3

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" id="WebApp_ID" version="3.0">
    <display-name>party</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <filter>
        <filter-name>characterEncoding</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

UserController

package com.buba.witkey.controller;

import com.buba.witkey.pojo.User;
import com.buba.witkey.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@RequestMapping("/user")
@Controller
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping("/selectAll")
    public String selectAll(Model model){
        List<User> list = userService.selectAll();
        model.addAttribute("list",list);
        return "/showAllUser";
    }
    @RequestMapping("/insertOne")
    public String insertOne(Model model, User user){
        int i = userService.insertOne(user);
        return "redirect:selectAll";
    }

}

UserMapper

package com.buba.witkey.mapper;

import com.buba.witkey.pojo.User;
import java.util.List;

public interface UserMapper {
    List<User> selectAll();
    int insertOne(User user);
}

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="com.buba.witkey.mapper.UserMapper" >
    <select id="selectAll" resultType="com.buba.witkey.pojo.User">
        select * from manager_user
    </select>
    <insert id="insertOne" >
        insert into manager_user values (null,#{userName},#{phone},#{qq},#{password},#{dept})
    </insert>
</mapper>

User

package com.buba.witkey.pojo;

import lombok.Data;

@Data
public class User {
    private Integer id;
    private String userName;
    private String phone;
    private String qq;
    private String password;
    private String dept;
}

UserService

package com.buba.witkey.service;

import com.buba.witkey.pojo.User;

import java.util.List;

public interface UserService {
    List<User> selectAll();

    int insertOne(User user);
}

UserServiceImpl

package com.buba.witkey.serviceImpl;

import com.buba.witkey.mapper.UserMapper;
import com.buba.witkey.pojo.User;
import com.buba.witkey.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public List<User> selectAll() {
        List<User> list = userMapper.selectAll();
        return list;
    }

    @Override
    public int insertOne(User user) {
        int i = userMapper.insertOne(user);
        return i;
    }
}

 

showAllUser.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 醜醜
  Date: 2018/11/20
  Time: 10:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3個meta標籤*必須*放在最前面,任何其他內容都*必須*跟隨其後! -->
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="${pageContext.request.contextPath}/static/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim 和 Respond.js 是為了讓 IE8 支援 HTML5 元素和媒體查詢(media queries)功能 -->
    <!-- 警告:通過 file:// 協議(就是直接將 html 頁面拖拽到瀏覽器中)訪問頁面時 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/html5shiv.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dest/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<%--class="container-fluid"  style="background-color: #4cae4c"--%>
<div class="container">
    <table class="table table-bordered table-striped table-hover table-condensed">
        <thead>
        <tr>
            <th>id</th>
            <th>username</th>
            <th>phone</th>
            <th>qq</th>
            <th>password</th>
            <th>dept</th>
        </tr>
        </thead>
        <tbody>
            <c:forEach var="user" items="${list}">
                <tr>
                    <th>${user.id}</th>
                    <th>${user.userName}</th>
                    <th>${user.phone}</th>
                    <th>${user.qq}</th>
                    <th>${user.password}</th>
                    <th>${user.dept}</th>
                </tr>
            </c:forEach>
        </tbody>
    </table>

</div>


<!-- jQuery (Bootstrap 的所有 JavaScript 外掛都依賴 jQuery,所以必須放在前邊) -->
<script src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.js"></script>
<!-- 載入 Bootstrap 的所有 JavaScript 外掛。你也可以根據需要只加載單個外掛。 -->
<script src="${pageContext.request.contextPath}/static/js/bootstrap.min.js"></script>
</body>
</html>

 

index.jsp

 

<%--
  Created by IntelliJ IDEA.
  User: 醜醜
  Date: 2018/11/20
  Time: 10:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3個meta標籤*必須*放在最前面,任何其他內容都*必須*跟隨其後! -->
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="${pageContext.request.contextPath}/static/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim 和 Respond.js 是為了讓 IE8 支援 HTML5 元素和媒體查詢(media queries)功能 -->
    <!-- 警告:通過 file:// 協議(就是直接將 html 頁面拖拽到瀏覽器中)訪問頁面時 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/html5shiv.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dest/respond.min.js"></script>
    <![endif]-->
    <%--<style>
        ul{
            list-style: none;
        }
        ul li{
            float: left;
            margin-left: 30px;
        }
    </style>--%>

</head>
<body>
<%--class="container-fluid"  style="background-color: #4cae4c"--%>
<div class="container">
    <div style="width: 600px;height:450px;margin: 0 auto;border: 1px solid #269abc;padding: 30px;" >
        <form id="addUserForm" action="${pageContext.request.contextPath}/user/insertOne" method="post" role="form" class="form-horizontal">
            <div class="col-xs-12" style="text-align: center;color: #2aabd2">
                <h1>新增使用者</h1>
                <br>
            </div>
            <div  class="form-group">
                <div class="col-xs-3">
                    <label class="control-label">使用者名稱:</label>
                </div>
                <div class="col-xs-6">
                    <input type="text" name="userName" class="form-control">
                </div>
                <div class="col-xs-3">
                   <span class="help-block"></span>
                </div>
            </div>
            <div  class="form-group">
                <div class="col-xs-3">
                    <label class="control-label">電話:</label>
                </div>
                <div class="col-xs-6">
                    <input type="text" name="phone" class="form-control">
                </div>
                <div class="col-xs-3">
                    <span class="help-block"></span>
                </div>
            </div>
            <div  class="form-group">
                <div class="col-xs-3">
                    <label class="control-label">QQ:</label>
                </div>
                <div class="col-xs-6">
                    <input type="text" name="qq" class="form-control" placeholder="請輸入郵箱">
                </div>
                <div class="col-xs-3">
                    <span class="help-block"></span>
                </div>
            </div>
            <div  class="form-group">
                <div class="col-xs-3">
                    <label class="control-label">密碼:</label>
                </div>
                <div class="col-xs-6">
                    <input type="text" name="password" class="form-control">
                </div>
                <div class="col-xs-3">
                    <span class="help-block"></span>
                </div>
            </div>
            <div  class="form-group">
                <div class="col-xs-3">
                    <label class="control-label">部門:</label>
                </div>
                <div class="col-xs-6">
                    <input type="text" name="dept" class="form-control">
                </div>
                <div class="col-xs-3">
                    <span class="help-block"></span>
                </div>
            </div>
            <div class="col-xs-3 col-xs-offset-9">
                <input type="submit" class="btn btn-primary" value="提交"/>
            </div>
        </form>
    </div>

</div>


<!-- jQuery (Bootstrap 的所有 JavaScript 外掛都依賴 jQuery,所以必須放在前邊) -->
<script src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.js"></script>
<!-- 載入 Bootstrap 的所有 JavaScript 外掛。你也可以根據需要只加載單個外掛。 -->
<script src="${pageContext.request.contextPath}/static/js/bootstrap.min.js"></script>
<script>
    $(function () {
        $("#addUserForm").submit(function () {
            var obj=$("input[name='userName']");
            var objval=obj.val();
            var pas=$("input[name='password']");
            var pasval=pas.val();
            var qqq=$("input[name='qq']");
            var qqqval=qqq.val();
            var pho=$("input[name='phone']");
            var phoval=pho.val();

            if(null==objval||""==objval){
                //校驗失敗
                obj.parent().parent().addClass("has-error");
                obj.parent().next().children().html("使用者名稱不能為空");
                return false;
            }else{
                obj.parent().parent().removeClass("has-error");
                obj.parent().next().children().html("");
            }

            var reg = /^1\d{10}$/;
            if((!reg.test(phoval))|| phoval == ""||phoval==null){
                pho.parent().parent().addClass("has-error");
                pho.parent().next().children().html("手機號格式不正確");
                return false;
            }else{
                pho.parent().parent().removeClass("has-error");
                pho.parent().parent().addClass("has-success");
                pho.parent().next().children().html("");
            }
            //郵箱
            //正則表示式
            var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
            //var emil = document.getElementById("qq"); //要驗證的物件
            if(qqqval === ""||!reg.test(qqqval)){ //輸入不能為空
                qqq.parent().parent().addClass("has-error");
                qqq.parent().next().children().html("正則驗證不通過,格式不對");
                return false;
            }else{
                qqq.parent().parent().removeClass("has-error");
                qqq.parent().parent().addClass("has-success");
                qqq.parent().next().children().html("郵箱可用");
            }
            if(pasval.length<=6||pasval==null||pasval==""){
                pas.parent().parent().addClass("has-error");
                pas.parent().next().children().html("密碼必須大於6位數");
                return false;
            }else{
                pas.parent().parent().removeClass("has-error");
                pas.parent().parent().addClass("has-success");
                pas.parent().next().children().html("");
            }
        });
    });
</script>
</body>
</html>