java增强: ssm框架整合

  1. 整合思路: 各组件的关联
  2. 配置整合
  3. ssm使用: jsp + jstl + servlet = mysql 的crud ( 用户信息分页管理 )

part1: 整合ssm

第一步: 使用idea 新建module: java web---> add framework support: maven---> 管理依赖jar包,修改pom.xml

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>

  <!--mybatis-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.17</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

<!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.3.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.10</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.1</version>
        </dependency>

 <!-- jstl 标签库-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

第二步: 在resources文件夹, 添加mybatis, spring的配置文件

<!-- spring配置文件: beans.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       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
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context-4.3.xsd
                http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
                http://www.springframework.org/schema/aop
                http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.dao" />
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"></property>
    </bean>

    <!-- 事务管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="insert*" isolation="DEFAULT" propagation="REQUIRED" />
            <tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" />
            <tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" />
            <tx:method name="select*" isolation="DEFAULT" propagation="REQUIRED" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>
    <!-- 事务通知 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*Service.*(..))" />
    </aop:config>

    <!--连接池: c3p0-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db"></property>
        <property name="user" value="root"></property>
        <property name="password" value="daitoue"></property>
        <property name="initialPoolSize" value="3"></property>
        <property name="maxPoolSize" value="10"></property>
    </bean>

    <!--session工厂-->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
</beans>
<!--mybatis配置文件: mybatis-config.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>
        <typeAlias type="com.bean.User" alias="_user" />
    </typeAliases>

    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>
<!-- mybatis配置文件: 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="users">
    <!-- 获得生成的id字段-->
    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
	insert into users2(name,sex) values(#{name},#{sex})
    </insert>

    <update id="update" >
        update users2 set name=#{name}, sex=#{sex} where id=#{id}
    </update>

    <select id="selectById" resultType="_user" >
        select * from users2 where id=#{id}
    </select>
    <select id="selectAll" resultType="_user" >
        select * from users2
    </select>

    <delete id="delete">
        delete from users2 where id=#{id}
    </delete>
</mapper>

 第三步: 创建javabean  ,实现类(dao层,service层,controller层)

//javabean
public class User {
        //字段
        private int id;
        private int age;
        private String name;
        private String sex;
        
        //构造
        public User() { }
        public User(int age, String name, String sex) {
            this.age = age;
            this.name = name;
            this.sex = sex;
            this.id=id;
        }

        @Override
        public String toString() {
            return "User{" +
                    "age=" + age +
                    ", name='" + name + '\'' +
                    ", sex='" + sex + '\'' +
                    ", id=" + id ;
        }
//get,set...
}

 

//dao层
import com.bean.User;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.List;

@Repository("dao")
public class UserDaoImpl extends SqlSessionDaoSupport {

    public int insert(User user){
        return res = getSqlSession().insert("users.insert",user);
    }

    public User selectById(int id){
        User user = getSqlSession().selectOne("users.selectById",id);
        return user;
    }
    public  List<User> selectUserList(){
        List<User> list = getSqlSession().selectList("users.selectAll");
        return list;
    }

    @Resource
    @Override
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }
}

 

//service层
import com.bean.User;
import com.dao.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userServiceImpl")
public class UserServiceImpl {
    @Autowired
    UserDaoImpl dao;

    public int insert(User user){
       return dao.insert(user);
    }

    public User selectById(int id){
        return dao.selectById(id);
    }

    public List<User> selectUserList(){return  dao.selectUserList();}
}
//controller层
import com.bean.User;
import com.service.UserServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/home")
public class HomeController {

    //属性
    @Resource
    UserServiceImpl service;

    @RequestMapping("/index")
    public String index(){
        System.out.println("/index...");
        return "index" ;
    }

    @RequestMapping("/insert")
    public String insert(){
        System.out.println("insert 表");
        User user = new User(23, "a", "girl");

        int res = service.insert(user);
        System.out.println("res=="+res);
        return "index" ;
    }

    @RequestMapping("/select")
    public String selectOne(ModelMap map,int id){
        System.out.println("select.....");

        User user = service.selectById(id);
        System.out.println(user);
        map.put("user",user);
        return "user" ;
    }
    @RequestMapping("/selectList")
    public String selectList(ModelMap map){
        System.out.println("select list.....");

        List<User> list = service.selectUserList();
        map.put("userList",list);
        return "userList" ;
    }
}

第四步: 配置web.xml,  dispatcher-servlet.xml

<!--web.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!-- 配置spring上下文文件的路径 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:beans.xml</param-value>
    </context-param>
    <!-- 配置监听器,确保web服务器启动时,完成spring配置文件的加载 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
		http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置注解驱动 -->
    <mvc:annotation-driven />
    <!-- 配置扫描包 -->
    <context:component-scan base-package="com" />

    <!-- 内部资源视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsps/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

第五步: 在WEB-INF目录下, 创建userList.jsp文件,  通过浏览器---输入url, 验证ssm

//userList.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>

  <c:forEach items="${userList}" var="user">
      <c:out value="${user.id}" ></c:out>
      <c:out value="${user.name}" ></c:out>
      <c:out value="${user.sex}" ></c:out> <br/>
  </c:forEach>

  </body>
</html>

 mysql中数据如下


part2: ssm框架初步使用

(用户信息分页管理)

第一步: 添加dao, service, controller层实现类

//controller层
import com.bean.User;
import com.service.UserServiceImpl;
import org.apache.ibatis.session.RowBounds;
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 javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/home")
public class HomeController3 {

    //属性
    @Resource
    UserServiceImpl service;
    int pageSize=5;
    int totalPages;
    int endPage;


    /**
     * 删除
     */
    @RequestMapping("/selectAll3")
    public String selectAll3(ModelMap map, int pageNo){
        System.out.println("selectAll3...pageNo="+pageNo);

        //每页的数据
        int start=(pageNo-1)*pageSize;
        RowBounds rowBounds = new RowBounds(start, pageSize);
        List<User> userList=service.selectAllLimit(rowBounds);
        map.put("userList", userList);


        //总页数
        totalPages=service.selectPageCount();
        endPage=(totalPages%pageSize ==0
                ? (totalPages/pageSize)
                : (totalPages/pageSize +1) );
        map.put("endPage",endPage);
        return "userList3";
    }

    @RequestMapping("/showUsers3")
    public String selectAll(ModelMap map, @RequestParam(value = "pageNo",defaultValue = "1") int pageNo ){
        System.out.println("showUsers3....pageNo="+pageNo);

        //每页的数据
        int start=(pageNo-1)*pageSize;
        RowBounds rowBounds = new RowBounds(start, pageSize);
        List<User> userList=service.selectAllLimit(rowBounds);
        map.put("userList",userList);

        //总页数
        totalPages=service.selectPageCount();
        endPage=(totalPages%pageSize ==0
                ? (totalPages/pageSize)
                : (totalPages/pageSize +1) );
        map.put("endPage",endPage);

        System.out.println(userList);
        return "userList3" ;
    }

    //----------------------
    @RequestMapping("/index3")
    public String index(){
        System.out.println("index3.....");
        return "redirect:/home/showUsers3";
    }

    @RequestMapping("/insert3")
    public String insert(){

        System.out.println("insert3 表");
        User user = new User(23, "a", "girl");

        int res = service.insert(user);
        System.out.println("res=="+res);
        return "redirect:/home/showUsers3";
    }


//查询: 一个用户
    @RequestMapping("/select3")
    public String selectOne(ModelMap map, int id){
        System.out.println("select3 one.....");

        User user = service.selectById(id);

        map.put("user",user);

        System.out.println(user);
        return "jsp2/user";
    }
    /**
     * 更新
     */
    @RequestMapping("/update3")
    public String update2(ModelMap map, int id){
        System.out.println("update3...");

        User user = service.selectById(id);
        map.put("user",user);
        return "forms/updateForm3";
    }
    /**
     * 更新
     */
    @RequestMapping("/doUpdate3")
    public String doupdate2(User user){
        System.out.println("处理更新..   update3..."+user);

        service.update(user);
        return "redirect:/home/showUsers3";
    }

    /**
     * add添加
     */
    @RequestMapping("/doAdd3")
    public String doAdd2(User user){
        System.out.println("处理add3..  ..."+user);

        service.insert(user);
        return "redirect:/home/showUsers3";
    }
    /**
     * add添加
     */
    @RequestMapping("/add3")
    public String add2(User user){
        System.out.println("add3..  ..."+user);

        return "forms/addForm3";
    }

    /**
     * 删除
     */
    @RequestMapping("/delete3")
    public String delete2(int id){
        System.out.println("delete3...");
        service.delete(id);
        return "redirect:/home/showUsers3";
    }
}
//service层
import com.bean.User;
import com.dao.UserDaoImpl;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service("userServiceImpl")
public class UserServiceImpl {

    @Autowired
    UserDaoImpl dao;

    public int insert(User user){
       return dao.insert(user);
    }

    public User selectById(int id){
        return dao.selectById(id);
    }

    public List<User> selectAll() {
        return dao.selectAll();
    }

    public void delete(int id) {
        dao.delete(id);
    }

    public void update(User user) {
        dao.update(user);
    }

    /**
     * 分页查询
     * @param rowBounds
     */
    public List<User> selectAllLimit(RowBounds rowBounds) {

        return  dao.selectAllLimit(rowBounds);
    }

    public int selectPageCount() {
        return  dao.selectPageCount();
    }
}
//dao层
import com.bean.User;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;

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

@Repository("dao")
public class UserDaoImpl extends SqlSessionDaoSupport {

    public int insert(User user){
        int res = getSqlSession().insert("users.insert",user);
        return res;
    }

    public User selectById(int id){
        User user = getSqlSession().selectOne("users.selectById",id);
        return user;
    }

    public List<User> selectAll() {
        return  getSqlSession().selectList("users.selectAll");
    }


    @Resource
    @Override
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }

    public void delete(int id) {
        getSqlSession().delete("users.delete",id);
    }

    public void update(User user) {
        getSqlSession().update("users.update",user);
    }

    /**
     * 分页查询
     * @param rowBounds
     * @return
     */
    public List<User> selectAllLimit(RowBounds rowBounds) {
        return getSqlSession().selectList("users.selectAllLimit",rowBounds);
    }

    public int selectPageCount() {
        return getSqlSession().selectOne("users.selectPageCount");
    }
}

第二步: 准备jsp文件

( WEB-INF/jsps/forms: addForm3.jsp,  updateForm3.jsp )  

(WEB-INF/jsps:   userList3.jsp)

表格的css配置如下

        table {
            border-collapse: collapse;
            margin: 0 auto;
            text-align: center;
            width: 50%;
        }

        table td, table th {
            border: 1px solid #cad9ea;
            color: #666;
            height: 30px;
        }

        table thead th {
            background-color: #CCE8EB;
            width: 100px;
        }

        table tr:nth-child(odd) {
            background: #fff;
        }

        table tr:nth-child(even) {
            background: #F5FAFA;
        }
//userList.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>userList2</title>
    <style>引用以上的css配置</style>
</head>
<body>
<a href="/home/add3"><input type="button" value="添加用户"></a>
<table>
    <tr style=" background: lightblue">
        <td>id</td>
        <td>name</td>
        <td>sex</td>
        <td></td>
        <td></td>
    </tr>

    <c:forEach items="${userList}" var="user">
        <tr>
            <td><c:out value="${user.id}"></c:out></td>
            <td><c:out value="${user.name}"></c:out></td>
            <td><c:out value="${user.sex}"></c:out></td>

            <td>
                <a href='<c:url value="/home/update3?id=${user.id}"/>'>修改</a>
            </td>
            <td>
                <a href='<c:url value="/home/delete3?id=${user.id}"/>'>删除</a>
            </td>
        </tr>
    </c:forEach>

    <!--分页-->
    <tr>
        <td colspan="5">
            <c:forEach begin="1" end="${endPage}" var="pageNo">
                <a href='<c:url value="/home/selectAll3?pageNo=${pageNo}"/>'>第${pageNo}页</a>&nbsp;&nbsp;
                </a>
            </c:forEach>
        </td>
    </tr>
</table>

</body>
</html>
//addForm.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
  <head>
    <title>add</title>
    <style>引用以上css配置</style>
  </head>
  <body>

  <form action="/home/doAdd3">
      <table >

          <tr >
              <td>name</td>
              <td><input type="text" name="name" value="${user.name}"/></td>
          </tr>

          <tr >
              <td>sex</td>
              <td><input type="text" name="sex" value="${user.sex}"/></td>
          </tr>
          <tr >
              <td colspan="2"><input type="submit" value="提交"/></td>
          </tr>
      </table>
  </form>
  </body>
</html>

 

//updateForm.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
  <head>
    <title>userList</title>          
    <style>引用以上配置</style>
  </head>
  <body>

  <form action="/home/doUpdate3">
      <table >
          <tr style="border: 1px solid ; background: lightblue">

              <td>id</td><td>${user.id}</td>
              <input type="hidden" name="id" value="${user.id}">
          </tr>

          <tr >
              <td>name</td>
              <td><input type="text" name="name" value="${user.name}"/></td>
          </tr>

          <tr >
              <td>sex</td>
              <td><input type="text" name="sex" value="${user.sex}"/></td>
          </tr>
          <tr >
              <td colspan="2"><input type="submit" value="提交"/></td>
          </tr>
      </table>
  </form>
  </body>
</html>

 

 

©️2020 CSDN 皮肤主题: 撸撸猫 设计师: 设计师小姐姐 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值