初级SSM框架整合

初级SSM框架整合本次ssm整合是对于初学者来说的第一次整合,里面还有很多地方可以进行优化,这点以后有空再分享。主要是体现整合的思路和过程。1、准备数据/*创建用户表*/CREATETABLE`user`( idBIGINTPRIMARYKEYAUTO_INCREMENT, usernameVARCHAR(50), passwordVARCHAR(50), emailVARCHAR(…

大家好,又见面了,我是你们的朋友全栈君。

本次ssm整合是对于初学者来说的第一次整合,里面还有很多地方可以进行优化,这点以后有空再分享。主要是体现整合的思路和过程。

1、准备数据

/*创建用户表*/
CREATE TABLE `user`(
	id BIGINT PRIMARY KEY AUTO_INCREMENT,
	username VARCHAR(50),
	password VARCHAR(50),
	email VARCHAR(50),
	phoneNum VARCHAR(20)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

/*初始化用户数据*/
insert into `user`(username,password,email,phoneNum) 
values('xiaom','123456','xiaom@qq.com','020-8888888');
insert into `user`(username,password,email,phoneNum) 
values('zhangs','123456','zhangs@qq.com','020-8888888');

[外链图片转存失败(img-lUUAIR4Q-1567593872014)(C:\Users\宏昌\AppData\Roaming\Typora\typora-user-images\1567574368565.png)]

2、创建项目结构

[外链图片转存失败(img-4p2pH1Dm-1567593872015)(C:\Users\宏昌\AppData\Roaming\Typora\typora-user-images\1567574585963.png)]

2.1 创建实体类

package com.itheima.pojo;

public class User { 
   
    private Integer id;//用户id
    private String username;// 用户名称
    private String password;// 用户密码
    private String email;// 用户邮箱
    private String phoneNum;// 用户联系电话

    public Integer getId() { 
   
        return id;
    }

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

    public String getUsername() { 
   
        return username;
    }

    public void setUsername(String username) { 
   
        this.username = username;
    }

    public String getPassword() { 
   
        return password;
    }

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

    public String getEmail() { 
   
        return email;
    }

    public void setEmail(String email) { 
   
        this.email = email;
    }

    public String getPhoneNum() { 
   
        return phoneNum;
    }

    public void setPhoneNum(String phoneNum) { 
   
        this.phoneNum = phoneNum;
    }

    public String toString() { 
   
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", phoneNum='" + phoneNum + '\'' +
                '}';
    }
}



2.2 创建持久层接口

package com.itheima.dao;

import com.itheima.pojo.User;
import java.util.List;

public interface UserDao { 
   
    /** * 查找全部用户 */
    List<Usre> findAllUser();
}

2.3 持久层实现类

package com.itheima.dao;

import com.itheima.pojo.User;

import java.util.List;

public class UserDaoImpl implements UserDao{ 
   

    /** * 查找所有用户 */
    @Override
    public List<User> findAllUser() { 
   
        System.out.println("查找所有人");//测试用
        return null;
    }
}

2.4 业务层接口

package com.itheima.service;

import com.itheima.pojo.User;

import java.util.List;

public interface UserService { 
   
    /** * 查找所有用户 */
    List<User> findAllUser();
}

2.5业务层实现类

package com.itheima.service;

import com.itheima.pojo.User;

import java.util.List;

public class UserServiceImpl implements UserService { 
   
    
    private UserDao userDao;
    
    /** * 查找所有用户 */
    @Override
    public List<User> findAllUser() { 
   
   
        return userDao.findAllUser();
    }
}

3、确保spring能够单独运行

3.1配置pom文件

<?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>com.itheima</groupId>  
  <artifactId>spring_zhenghe</artifactId>  
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <!--spring 版本-->
    <spring.version>5.0.2.RELEASE</spring.version>

  </properties>

  
  <dependencies>
    <!--spring ioc依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
  </dependencies>
</project>

3.2为持久层实现类配置注解

package com.itheima.dao;

import com.itheima.pojo.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("userDao")
public class UserDaoImpl implements UserDao{ 
   

    /** * 查找所有用户 */
    @Override
    public List<User> findAllUser() { 
   
        System.out.println("查找所有人");
        return null;
    }
}

3.3为业务层实现类添加注解

package com.itheima.service;

import com.itheima.dao.UserDao;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService { 
   

    @Autowired
    private UserDao userDao;

    /** * 查找所有用户 */
    @Override
    public List<User> findAllUser() { 
   

        return userDao.findAllUser();
    }
}

3.4编写bean.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">

    <!--配置包扫描dao/service,说明: 第一步:导入context名称空间和约束 第二步:通过<context:component-scan/>标签配置,spring框架在 创建ioc容器的时候,会扫描指定的包和它的子包 -->
    <context:component-scan base-package="com.itheima"></context:component-scan>

</beans>

3.5编写测试类

package com.itheima;

import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class TestSpring { 
   

    @Test
    public void testspring(){ 
   

        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:bean.xml");
        UserService service = (UserService) ac.getBean("userService");
       service.findAllUser();
    }
}

测试结果正确

[外链图片转存失败(img-4B1xV6sH-1567593872016)(C:\Users\宏昌\AppData\Roaming\Typora\typora-user-images\1567584034103.png)]

4、确保Springmvc能够运行

4.1配置pom

<?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>com.itheima</groupId>  
  <artifactId>spring_zhenghe</artifactId>  
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <!--spring 版本-->
    <spring.version>5.0.2.RELEASE</spring.version>
    <!-- jstl标签版本 -->
    <jstl.version>1.2</jstl.version>
    <!--servlet版本-->
    <servlet.version>2.5</servlet.version>
    <!--jsp版本-->
    <jsp.version>2.0</jsp.version>
  </properties>


  <dependencies>
    <!--spring ioc依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!--junit4-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

    <!-- spring webmvc依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- jstl标签依赖 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
    <!--servlet依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>
    <!--jsp依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>${jsp.version}</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <!--配置插件-->
    <plugins>
      <!--maven tomcat插件-->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <!-- tomcat 的端口号 -->
          <port>8080</port>
          <!-- 访问应用的路径 -->
          <path>/ssm</path>
          <!-- URL按UTF-8进行编码,解决中文参数乱码 -->
          <uriEncoding>UTF-8</uriEncoding>
          <!-- tomcat名称 -->
          <server>tomcat7</server>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

4.2编写配置文件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.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-->
    <context:component-scan base-package="com.itheima.ssm.controller"/>

    <!--注解驱动方式配置处理器映射器和处理器适配器-->
    <mvc:annotation-driven/>

    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置视图的公共目录路径-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--配置视图的扩展名称-->
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

4.3 配置web.xml

<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_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>ssm</display-name>

  <!-- 配置字符集编码过滤器 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

    <!-- 指定使用的编码:UTF-8 -->
    <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>

  <!--配置前端控制器:DispatcherServlet-->
  <servlet>
    <servlet-name>ssm</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <!--加载springmvc主配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>

    <!--配置什么时候加载前端控制器,说明: 1.配置大于等于0的整数,表示在web容器启动的时候加载 2.配置小于0的整数,表示在第一次请求到达的时候加载 -->
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>ssm</servlet-name>
    <!--配置拦截的url规则,说明: 1.*.do,表示以.do结尾的请求进入前端控制器 2./,表示所有请求都进入前端控制器 -->
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app>

4.4编写首页显示代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入jstl标签库--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>用户列表jsp页面</title>
    <style>
        table {border:1px solid #000000}
        table th{border:1px solid #000000}
        table td{border:1px solid #000000}
    </style>

    <script>

        // 添加用户
        function add(id) {
            window.location.href="${pageContext.request.contextPath}/add.do";
        }

        // 修改用户
        function get(id) {
            window.location.href="${pageContext.request.contextPath}/get.do?id="+id;
        }
        // 删除用户
        function  removeUser(id) {
            if(confirm("确定要删除吗?")){
                window.location.href="${pageContext.request.contextPath}/remove.do?id="+id;
            }
        }
    </script>
</head>
<body>
用户列表:<button type="button"  οnclick="add()">添加用户</button>
<table cellpadding="0" cellspacing="0" width="80%">
    <tr>
        <th>用户Id</th>
        <th>用户名称</th>
        <th>邮箱</th>
        <th>联系电话</th>
        <th>操作</th>
    </tr>
    <c:forEach items="${users}" var="user">
        <tr>
            <td>${user.id}</td>
            <td>${user.username}</td>
            <td>${user.email}</td>
            <td>${user.phoneNum}</td>
            <td>
                <button type="button"  οnclick="get('${user.id}')">修改</button>
                <button type="button"  οnclick="removeUser('${user.id}')">删除</button>
            </td>
        </tr>
    </c:forEach>
</table>
</body>

</html>


4.5 编写Controller测试类

package com.itheima.controller;

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

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

@Controller
public class UserController { 
   

    @RequestMapping("/list.do")
   public String findAllUser(Model model){ 
   

        List<User> users = new ArrayList<>();

        //测试需要,把用户写死

        User user = new User();
        user.setId(1);
        user.setUsername("张三");
        user.setPassword("123");
        user.setEmail("xiaom@qq.com");
        user.setPhoneNum("020-8888888");

        users.add(user);

        model.addAttribute("users",users);

        return "list";

   }


}

测试结果正确:

[外链图片转存失败(img-Y2ZgzFNL-1567593872018)(C:\Users\宏昌\AppData\Roaming\Typora\typora-user-images\1567585004999.png)]

5、整合Spring框架和SpringMvc框架

5.1web.xml配置监听器

 <!--指定spring配置文件位置-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext.xml</param-value>
  </context-param>

  <!--配置ContextLoaderListener监听器,说明: 1.ContextLoaderListener监听器,监听ServletContext对象的创建。一旦ServletContext对象创建, 它立即帮助我们创建spring容器,并且放入ServletContext域中。 2.该监听器,默认只能加载WEB-INF目录下,名称为applicationContext.xml的配置文件 3.通过context-param标签,配置指定spring的配置文件位置,改变默认行为。 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

6、确保Mybatis框架能够运行

6.1配置pom

<?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>com.itheima</groupId>  
  <artifactId>spring_zhenghe</artifactId>  
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <!--spring 版本-->
    <spring.version>5.0.2.RELEASE</spring.version>
    <!-- jstl标签版本 -->
    <jstl.version>1.2</jstl.version>
    <!--servlet版本-->
    <servlet.version>2.5</servlet.version>
    <!--jsp版本-->
    <jsp.version>2.0</jsp.version>
    <!-- slf4j日志版本 -->
    <slf4j.version>1.7.7</slf4j.version>
    <!-- mybatis版本 -->
    <mybatis.version>3.4.5</mybatis.version>
    <!--mysql驱动版本-->
    <mysql.version>5.1.30</mysql.version>
  </properties>


  <dependencies>
    <!--spring ioc依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!--junit4-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

    <!-- spring webmvc依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- jstl标签依赖 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
    <!--servlet依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>
    <!--jsp依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>${jsp.version}</version>
      <scope>provided</scope>
    </dependency>
    <!-- mybatis依赖 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!-- mysql驱动依赖 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!-- slf4j依赖 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>


  </dependencies>

  <build>
    <!--配置插件-->
    <plugins>
      <!--maven tomcat插件-->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <!-- tomcat 的端口号 -->
          <port>8080</port>
          <!-- 访问应用的路径 -->
          <path>/ssm</path>
          <!-- URL按UTF-8进行编码,解决中文参数乱码 -->
          <uriEncoding>UTF-8</uriEncoding>
          <!-- tomcat名称 -->
          <server>tomcat7</server>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

6.2 编写Mabaties核心配置文件sqlMapConfig.xml

<?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>


    <!-- 配置别名 -->
    <typeAliases>
        <!-- 包扫描的方式,配置自定义别名-->
        <package name="com.itheima.pojo"/>
    </typeAliases>

    <!-- 一个核心配置文件,可以配置多个运行环境,default默认使用哪个运行环境 -->
    <environments default="default">
        <!-- 其中的一个运行环境,通过id来进行标识-->
        <environment id="default">
            <!-- 事务管理器type的取值: 1. JDBC:由JDBC进行事务的管理 2. MANAGED:事务由容器来管理,后期学习Spring框架的时候,所有的事务由容器管理 -->
            <transactionManager type="JDBC"/>
            <!-- 数据源: 1. POOLED:使用mybatis创建的连接池 2. UNPOOLED:不使用连接池,每次自己创建连接 3. JNDI:由服务器提供连接池的资源,我们通过JNDI指定的名字去访问服务器中资源。 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
                <property name="username" value="root"/>
                <property name="password" value="zhc1024"/>
            </dataSource>
        </environment>
    </environments>
    <!--映射器-->
    <mappers>
        <!--指定外面的实体类映射文件,注:不是点号-->
        <package name="com.itheima.dao"/>
    </mappers>
</configuration>

6.3 编写log4j日志文件

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

6.4 编写配置持久层文件编写SQL语句

注:该文件要写在resource文件夹下,并且包名要和UserDao一致

<?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.itheima.dao.UserDao">

    <!--1.查询全部用户列表-->
    <select id="findAllUser" resultType="user">
        select * from `user`
    </select>
</mapper>

6.5 编写测试类

package com.itheima;

import com.itheima.dao.UserDao;
import com.itheima.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMybatis { 
   

    @Test
    public void testMybatis(){ 
   
        InputStream is = null;
        SqlSession sqlSession = null;
        try { 
   
            is = Resources.getResourceAsStream("sqlMapConfig.xml");
            SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();
            SqlSessionFactory build = sfb.build(is);
            sqlSession = build.openSession();
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            List<User> users = mapper.findAllUser();
            System.out.println(users);
        } catch (IOException e) { 
   

        }finally { 
   
           if(sqlSession != null) sqlSession.close();

        }

    }
}

测试结果正确:

[外链图片转存失败(img-qohhhR6u-1567593872020)(C:\Users\宏昌\AppData\Roaming\Typora\typora-user-images\1567586906811.png)]

7、整合spring框架和mybatis框架

7.1 配置pom

<?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>com.itheima</groupId>  
  <artifactId>spring_zhenghe</artifactId>  
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <!--spring 版本-->
    <spring.version>5.0.2.RELEASE</spring.version>
    <!-- jstl标签版本 -->
    <jstl.version>1.2</jstl.version>
    <!--servlet版本-->
    <servlet.version>2.5</servlet.version>
    <!--jsp版本-->
    <jsp.version>2.0</jsp.version>
    <!-- slf4j日志版本 -->
    <slf4j.version>1.7.7</slf4j.version>
    <!-- mybatis版本 -->
    <mybatis.version>3.4.5</mybatis.version>
    <!--mysql驱动版本-->
    <mysql.version>5.1.30</mysql.version>
      <!-- mybatis-spring整合包版本 -->
      <mybatis.spring.version>1.3.1</mybatis.spring.version>
      <!--druid版本-->
      <druid.version>1.0.29</druid.version>
      <!-- aspectj版本号 -->
      <aspectj.version>1.6.12</aspectj.version>
  </properties>


  <dependencies>
    <!--spring ioc依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!--junit4-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

    <!-- spring webmvc依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- jstl标签依赖 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
    <!--servlet依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>
    <!--jsp依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>${jsp.version}</version>
      <scope>provided</scope>
    </dependency>
    <!-- mybatis依赖 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!-- mysql驱动依赖 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!-- slf4j依赖 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

      <!--spring jdbc依赖-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <!--aspectj依赖-->
      <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>1.6.12</version>
      </dependency>

      <!-- mybatis-spring依赖 -->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>${mybatis.spring.version}</version>
      </dependency>
      <!--druid依赖-->
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>${druid.version}</version>
      </dependency>
  </dependencies>

  <build>
    <!--配置插件-->
    <plugins>
      <!--maven tomcat插件-->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <!-- tomcat 的端口号 -->
          <port>8080</port>
          <!-- 访问应用的路径 -->
          <path>/ssm</path>
          <!-- URL按UTF-8进行编码,解决中文参数乱码 -->
          <uriEncoding>UTF-8</uriEncoding>
          <!-- tomcat名称 -->
          <server>tomcat7</server>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

7.2 编写applicationContext-dao.xml文件

编写db.properties配置文件

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/spring?characterEncoding=utf-8
db.username=root
db.password=zhc1024
<?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">

    <!--加载db.properties-->
    <context:property-placeholder location="classpath:db.properties"/>

    <!--配置数据源对象-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!--连接数据库的四个基本要素-->
        <property name="driverClassName" value="${db.driver}"/>
        <property name="url" value="${db.url}"/>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>
    </bean>

    <!--配置SqlSessionFactory对象,说明: 1.让spring框架接管SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据源对象-->
        <property name="dataSource" ref="dataSource"/>
        <!--定义别名-->
        <property name="typeAliasesPackage" value="com.itheima.pojo"></property>
    </bean>

    <!--配置自动扫描mapper映射文件-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定要扫描的包,说明: 1.如果有多个包要扫描。看是否在同一个父包 2.在同一个父包,配置父包即可 3.不在同一个父包,以半角逗号分割 -->
        <property name="basePackage" value="com.itheima.dao"/>
    </bean>
</beans>

7.3编写applicationContext-service.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">

    <!--配置扫描service-->
    <context:component-scan base-package="com.itheima.service"/>

</beans>

7.3编写applicationContext-trans.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: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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源对象-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--配置aop-->
    <aop:config>
        <!--配置切入点表达式-->
        <aop:pointcut id="pt1" expression="execution(* com.itheima.service..*.*(..))"/>
        <!--建立通知与切入点表达式关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
    </aop:config>

    <!--配置通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--配置事务属性-->
        <tx:attributes>
            <!--配置增、删、改事务规则-->
            <tx:method name="insert*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="update*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="del*" propagation="REQUIRED" read-only="false"/>

            <!--配置查询事务规则-->
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
</beans>

7.4编写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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--导入其它子配置文件-->
    <import resource="classpath:applicationContext-dao.xml"/>
    <import resource="classpath:applicationContext-service.xml"/>
    <import resource="classpath:applicationContext-trans.xml"/>

</beans>

7.8改造UserController

package com.itheima.controller;

import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

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

@Controller
public class UserController { 
   

    @Autowired
    private UserService userService;

    @RequestMapping("/list.do")
   public String findAllUser(Model model){ 
   

       /* List<User> users = new ArrayList<>(); //测试需要,把用户写死 User user = new User(); user.setId(1); user.setUsername("张三"); user.setPassword("123"); user.setEmail("xiaom@qq.com"); user.setPhoneNum("020-8888888"); users.add(user); model.addAttribute("users",users); return "list";*/

        List<User> users = userService.findAllUser();

        model.addAttribute("users",users);

        return "list";
    }
}

运行成功:

[外链图片转存失败(img-cIlX8tfm-1567593872023)(C:\Users\宏昌\AppData\Roaming\Typora\typora-user-images\1567588222762.png)]

8.附上全部代码

项目结构:

[外链图片转存失败(img-NCk320Gv-1567593872026)(C:\Users\宏昌\AppData\Roaming\Typora\typora-user-images\1567592095218.png)]

8.1 持久层

package com.itheima.dao;

import com.itheima.pojo.User;

import java.util.List;

public interface UserDao { 
   
    /** * 查找所有用户 */
    List<User> findAllUser();
    /** * 新增用户 */
    void insertUser(User user);

    /** * 修改状态回显 */
    User findUserById(int id);

    /** * 修改用户 */
    void updateUser(User user);

    /** * 删除用户 */
    void deleteUser(int id);
}


8.2 实体类

package com.itheima.pojo;

public class User { 
   
    private Integer id;//用户id
    private String username;// 用户名称
    private String password;// 用户密码
    private String email;// 用户邮箱
    private String phoneNum;// 用户联系电话

    public Integer getId() { 
   
        return id;
    }

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

    public String getUsername() { 
   
        return username;
    }

    public void setUsername(String username) { 
   
        this.username = username;
    }

    public String getPassword() { 
   
        return password;
    }

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

    public String getEmail() { 
   
        return email;
    }

    public void setEmail(String email) { 
   
        this.email = email;
    }

    public String getPhoneNum() { 
   
        return phoneNum;
    }

    public void setPhoneNum(String phoneNum) { 
   
        this.phoneNum = phoneNum;
    }

    public String toString() { 
   
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", phoneNum='" + phoneNum + '\'' +
                '}';
    }
}



8.3 业务层

package com.itheima.service;

import com.itheima.pojo.User;

import java.util.List;

public interface UserService { 
   
    /** 查找全部用户 */
    List<User> findAllUser();

    /** * 新增用户 */
    void insertUser(User user);

    /** * 修改状态回显 */
    User findUserById(int id);

    /** * 修改用户 */
    void updateUser(User user);

    /** * 删除用户 */
    void deleteUser(int id);
}

8.4 业务层实现类

package com.itheima.service;

import com.itheima.dao.UserDao;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService { 
   

    @Autowired
    private UserDao userDao;

    @Override
    public List<User> findAllUser() { 
   
        return userDao.findAllUser();
    }

    @Override
    public void insertUser(User user) { 
   
        userDao.insertUser(user);
    }

    @Override
    public User findUserById(int id) { 
   
        return userDao.findUserById(id);
    }

    @Override
    public void updateUser(User user) { 
   
        userDao.updateUser(user);
    }

    @Override
    public void deleteUser(int id) { 
   
        userDao.deleteUser(id);
    }
}

8.5 控制层

package com.itheima.controller;

import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class UserController { 
   


    @Autowired
    private UserService userService;

    /** * 显示用户 */
    @RequestMapping("list")
    public String showAllUser(Model model){ 
   

        List<User> users = userService.findAllUser();

        model.addAttribute("users",users);

        return "list";
    }
//===========================新增=======================================
    /** * 跳转新增用户 */
    @RequestMapping("add")
    public String add(){ 
   
        return "add";
    }

    /** * 新增 */

    @RequestMapping("insert")
    public String insert(User user){ 
   

        userService.insertUser(user);

        return "redirect:list";
    }
    //========================修改===================================
    //状态回显
    @RequestMapping("get")
    public String getUser(Model model,Integer id){ 
   
        User user = userService.findUserById(id);

        model.addAttribute("user",user);

        return "edit";
    }
    @RequestMapping("edit")
    public String update(User user){ 
   

        userService.updateUser(user);

        return "redirect:list";
    }

    //====================删除=================================
    @RequestMapping("remove")
    public String delUser(Integer id){ 
   

        userService.deleteUser(id);

        return "redirect:list";
    }
}

8.6 显示用户表

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入jstl标签库--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>用户列表jsp页面</title>
    <style>
        table {border:1px solid #000000}
        table th{border:1px solid #000000}
        table td{border:1px solid #000000}
    </style>

    <script>

        // 添加用户
        function add(id) {
            window.location.href="${pageContext.request.contextPath}/add.do";
        }

        // 修改用户
        function get(id) {
            window.location.href="${pageContext.request.contextPath}/get.do?id="+id;
        }
        // 删除用户
        function  removeUser(id) {
            if(confirm("确定要删除吗?")){
                window.location.href="${pageContext.request.contextPath}/remove.do?id="+id;
            }
        }
    </script>
</head>
<body>
    用户列表:<button type="button"  οnclick="add()">添加用户</button>
    <table cellpadding="0" cellspacing="0" width="80%">
        <tr>
            <th>用户Id</th>
            <th>用户名称</th>
            <th>邮箱</th>
            <th>联系电话</th>
            <th>操作</th>
        </tr>
        <c:forEach items="${users}" var="user">
            <tr>
                <td>${user.id}</td>
                <td>${user.username}</td>
                <td>${user.email}</td>
                <td>${user.phoneNum}</td>
                <td>
                    <button type="button"  οnclick="get('${user.id}')">修改</button>
                    <button type="button"  οnclick="removeUser('${user.id}')">删除</button>
                </td>
            </tr>
        </c:forEach>
    </table>
</body>

</html>


8.7 编辑用户表

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>修改用户信息</title>
    <style>
        table {border:1px solid #000000}
        table th{border:1px solid #000000}
        table td{border:1px solid #000000}
    </style>
</head>
<body>
<form id="userForm"
      action="${pageContext.request.contextPath }/edit.do"  method="post">
    修改用户信息:
    <table cellpadding="0" cellspacing="0" width="80%">
        <input type="hidden" name="id" value="${user.id}"/>
        <tr>
            <td>用户名称</td>
            <td><input type="text" name="username" value="${user.username}" /></td>
        </tr>
        <tr>
            <td>邮箱</td>
            <td><input type="text" name="email" value="${user.email}" /></td>
        </tr>
        <tr>
            <td>联系电话</td>
            <td><input type="text" name="phoneNum" value="${user.phoneNum}" /></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="修改" />
            </td>
        </tr>
    </table>

</form>
</body>

</html>

8.8 新增用户表

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>添加用户信息</title>
    <style>
        table {border:1px solid #000000}
        table th{border:1px solid #000000}
        table td{border:1px solid #000000}
    </style>
</head>
<body>
<form id="userForm"
      action="${pageContext.request.contextPath }/insert.do"  method="post">
    添加用户信息:
    <table cellpadding="0" cellspacing="0" width="80%">

        <tr>
            <td>用户名称</td>
            <td><input type="text" name="username" value="" /></td>
        </tr>
        <tr>
            <td>用户密码</td>
            <td><input type="password" name="password" value="" /></td>
        </tr>
        <tr>
            <td>邮箱</td>
            <td><input type="text" name="email" value="" /></td>
        </tr>
        <tr>
            <td>联系电话</td>
            <td><input type="text" name="phoneNum" value="" /></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="添加" />
            </td>
        </tr>
    </table>

</form>
</body>

</html>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/143459.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • java代码质量检查工具_jvm问题排查

    java代码质量检查工具_jvm问题排查wJa是一款结合DAST、SAST、IAST的综合性应用程序安全分析工具,支持对javaweb程序的安全性进行分析,含有反编译,代码审计,调试jar包,代理追踪等用于分析软件安全的功能。

  • conda pycharm 虚拟环境_【AI实战】基础环境搭建(Ubuntu+conda+tensorflow+GPU+PyCharm)[通俗易懂]

    conda pycharm 虚拟环境_【AI实战】基础环境搭建(Ubuntu+conda+tensorflow+GPU+PyCharm)[通俗易懂]为方便日常的深度学习模型开发与测试,在自己笔记本上搭建一个深度学习的基础环境,便于学习AI使用。本人使用的笔记本配置是CPU为8代i5,显卡为GTX1060,内存为8G,基本上可满足日常的AI研究与学习。下面将介绍基础环境的搭建配置过程:1、安装Ubuntu18.04(1)安装操作系统从Ubuntu官网上下载最新的Ubuntu18.04LTS版本的IOS文件,然后使用ImageWrit…

  • python sobel滤波_Sobel滤波器

    python sobel滤波_Sobel滤波器一.sobel滤波器介绍sobel滤波器常用来提取灰度图像的水平边缘(水平特征)和竖直边缘(竖直特征)二.sobel算子纵向算子,提取图像水平边缘↑横向算子,提取图像竖直边缘↑三.实验:python实现sobel算子并将算子作用于图像importcv2importnumpyasnp#GrayscaledefBGR2GRAY(img):b=img[:,:,0].cop…

    2022年10月25日
  • pandas中的drop函数_pandas replace函数

    pandas中的drop函数_pandas replace函数这里写自定义目录标题新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML图表FLowchart流程图导出与导入导出导入新的改变我们对Markdown编辑器进行了一些功能拓展与语法支持,除了标准的Markdown编辑器功能,我们增加了如下几点新功能,帮助你用它写博客:

  • scrapyip池(ip route命令)

    目录一、中间件的使用1-1具体方法详解1-1-1process_request-正常请求调用1-1-2process_response-正常返回调用1-1-3process_exception-捕获错误调用二、Proxy相关官方中间件2-1HttpProxyMiddleware2-2RetryMiddleware2-2-1源码分析…

  • python表白代码大全简单-python告白代码,只属于程序员的浪漫

    python表白代码大全简单-python告白代码,只属于程序员的浪漫不知何时,不知何因,程序员这个行业成为大家茶余饭后取乐的无辜群体。只要说到程序员,脑海中就浮现出刻板印象,标配穿搭:格子衫,牛仔裤,黑框眼镜。当然秃顶也是必须的,更狠的吐槽还有邋里邋遢,不懂浪漫,不知人情世故!开始可能只是幽默玩笑,后面慢慢就越传越多,大家便信以为真!可是程序员真的是这样吗?随着现在编程这个行业的普遍高薪收入,程序员又成为大家关注的焦点,深入的了解后,发现程序员其实是很可爱的一个群…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号