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/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/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/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/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>
好的,下面我来为你介绍一下如何使用SSM整合框架实现用户注册功能。 首先,你需要在你的项目中添加Spring、Spring MVC和MyBatis的依赖,可以在pom.xml文件中添加以下依赖: ```xml <!-- Spring依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!-- MyBatis依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> ``` 接下来,你需要在Spring的配置文件中配置数据源和MyBatis的SqlSessionFactory,可以参考以下配置: ```xml <!-- 数据源配置 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="123456" /> </bean> <!-- MyBatis配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.example.entity" /> <property name="mapperLocations" value="classpath*:com/example/dao/*.xml" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 开启事务注解 --> <tx:annotation-driven transaction-manager="transactionManager"/> ``` 其中,数据源的配置根据你自己的实际情况进行修改。typeAliasesPackage用来指定实体类所在的包,mapperLocations用来指定Mapper.xml文件所在的路径。 接下来,你需要编写用户实体类和Mapper接口,例如: ```java public class User { private Integer id; private String username; private String password; // 省略getter和setter方法 } public interface UserMapper { void insert(User user); } ``` 其中,User实体类中的字段根据你自己的实际需求进行修改。UserMapper接口中的insert方法用来插入新的用户记录。 最后,你需要编写用户注册的Controller和Service层代码,例如: ```java @Controller public class UserController { @Autowired private UserService userService; @RequestMapping("/register") public String register(User user) { userService.register(user); return "success"; } } @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public void register(User user) { userMapper.insert(user); } } public interface UserService { void register(User user); } ``` 其中,UserController中的register方法用来接收用户注册的请求,并调用UserService的register方法进行处理。UserService中的register方法则调用UserMapper的insert方法插入新的用户记录。 好了,以上就是使用SSM整合框架实现用户注册功能的基本步骤。当然,具体实现还要根据你自己的实际需求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值