使用Intellij IEDA搭建ssm+mysql框架

ssm框架即spring+springMVC +mybatis,今天主要介绍如何将其整合。

准备工作:请确保你的jdk、idea、mysql、maven已经安装好,并且相关环境变量设置成功。


1.创建maven项目
打开idea,新建项目。
使用Intellij IEDA搭建ssm+mysql框架_第1张图片
使用Intellij IEDA搭建ssm+mysql框架_第2张图片
使用Intellij IEDA搭建ssm+mysql框架_第3张图片
使用Intellij IEDA搭建ssm+mysql框架_第4张图片

此时工程创建成功,等待maven将工程生成。

以下是生成的工程目录,及其pom中的数据,pom中的数据还需要调整下。

使用Intellij IEDA搭建ssm+mysql框架_第5张图片
使用Intellij IEDA搭建ssm+mysql框架_第6张图片

2. 修改下工程的目录结构
成功后的目录结构应该是如下的样子:
使用Intellij IEDA搭建ssm+mysql框架_第7张图片

  • 打开project structure
    这里写图片描述
    使用Intellij IEDA搭建ssm+mysql框架_第8张图片
    在src上新建目录。
    使用Intellij IEDA搭建ssm+mysql框架_第9张图片
    使用Intellij IEDA搭建ssm+mysql框架_第10张图片
    这样就创建了测试的目录。
    按照此方法在main和test上创建resources、java目录,如图:
    使用Intellij IEDA搭建ssm+mysql框架_第11张图片
    下面修改目录的源,鼠标移动到main目录下的java目录上,右键选择sources即可,
    使用Intellij IEDA搭建ssm+mysql框架_第12张图片
    按照上面的方法,分别
    修改main目录下resources,右键选择resources;
    修改test目录下的java,右键选择tests;
    修改test目录下的resources,右键test resources。
    修改完成如图:
    使用Intellij IEDA搭建ssm+mysql框架_第13张图片
    然后点击APPLY,再点击ok,则目录结构修改完成。

3. 配置pom
向pom中添加依赖,及其pom的相关配置,如下代码:



<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.0modelVersion>

  <groupId>com.itlaobinggroupId>
  <artifactId>ssmartifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging>

  <name>ssm Maven Webappname>
  
  <url>http://www.example.comurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.8maven.compiler.source>
    <maven.compiler.target>1.8maven.compiler.target>
    <maven.compiler.compilerVersion>1.8maven.compiler.compilerVersion>

    <spring.version>4.3.13.RELEASEspring.version>
    <jackson.version>2.9.3jackson.version>
  properties>

  <dependencies>

    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.12version>
      <scope>testscope>
    dependency>

    
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>3.1.0version>
      <scope>providedscope>
    dependency>

    
    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>javax.servlet.jsp-apiartifactId>
      <version>2.3.1version>
      <scope>providedscope>
    dependency>

    
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>

    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>1.7.25version>
    dependency>

    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
      <version>1.7.25version>
      <scope>testscope>
    dependency>

    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>1.2.17version>
    dependency>

    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.45version>
    dependency>

    
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>druidartifactId>
      <version>1.1.6version>
    dependency>

    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.4.5version>
    dependency>

    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.1version>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>4.3.13.RELEASEversion>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>4.3.13.RELEASEversion>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>4.3.13.RELEASEversion>
    dependency>

    
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-coreartifactId>
      <version>${jackson.version}version>
    dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-annotationsartifactId>
      <version>${jackson.version}version>
    dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>${jackson.version}version>
    dependency>

    
    <dependency>
      <groupId>org.hibernategroupId>
      <artifactId>hibernate-validatorartifactId>
      <version>5.0.2.Finalversion>
    dependency>

  dependencies>

  <build>
    
    <finalName>ssmfinalName>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.mavengroupId>
        <artifactId>tomcat7-maven-pluginartifactId>
        <version>2.2version>
        <configuration>
          <port>80port>
          <path>/path>
          <uriEncoding>UTF-8uriEncoding>
        configuration>
      plugin>
    plugins>
  build>

project>

添加依赖后,更新maven,下载jar
使用Intellij IEDA搭建ssm+mysql框架_第14张图片
更新完成后如下:
使用Intellij IEDA搭建ssm+mysql框架_第15张图片

4.创建spring、springMVC配置文件

  • 创建 IoC 配置文件 (beans.xml)

在main下的resources上创建beans.xml文件,并贴上如下代码。

 

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:p="http://www.springframework.org/schema/p"
           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">

    beans>
  • 创建springMVC配置文件( mvc.xml ),并贴上如下代码


   <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:p="http://www.springframework.org/schema/p"
          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">


   beans>

5. 编辑 web.xml ,添加监听器、过滤器、Servlet等组件



<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         id="WebApp_ID" version="3.1">

    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:beans.xmlparam-value>
    context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>

    

    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
    filter>

    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
        <dispatcher>REQUESTdispatcher>
        <dispatcher>INCLUDEdispatcher>
        <dispatcher>FORWARDdispatcher>
    filter-mapping>

    

    <servlet>
        <servlet-name>mvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:mvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>

    <servlet-mapping>
        <servlet-name>mvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

web-app>

6.分包
在main下java上创建包(package),目录结构如下图:
使用Intellij IEDA搭建ssm+mysql框架_第16张图片

7.创建控制器
在包controller上创建java类,命名为UserController。

package com.itlaobing.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

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

    @RequestMapping( path = "/sign-up" , method = RequestMethod.GET)
    public String signUpPage() {
        return "sign-up" ;
    }

}

8.创建jsp页面 sign-up.jsp
在WEB-INF下新建目录,命名为views,在views下新建sign-up.jsp文件。
使用Intellij IEDA搭建ssm+mysql框架_第17张图片

在sign-up.jsp文件中添加如下代码:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <meta charset="UTF-8">
    <title>注册title>

head>
<body>

<h2>注册h2>

<div>
    <form action="${ pageContext.request.contextPath }/user/sign-up" method="post">
        <input type="text" name="username" >
        <input type="text" name="password" >
        <input type="submit" value="注册">
    form>
div>

body>
html> 

9.编辑mvc.xml
在mvc.xml中添加视图解析器,启动扫描,代码如下:



<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       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">

        
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/" />
            <property name="suffix" value=".jsp" />
        bean>

        
        <context:component-scan base-package="com.itlaobing.web.controller" />
        <mvc:annotation-driven  />
beans>

10.测试
启动 tomcat
使用Intellij IEDA搭建ssm+mysql框架_第18张图片
点击tomcat7:run即启动。
然后在浏览器地址栏输入: http://localhost:80/user/sign-up 即可。
使用Intellij IEDA搭建ssm+mysql框架_第19张图片

11.创建 UserMapper 接口
在mapper上创建UserMapper接口,代码如下:

package com.itlaobing.mapper;

import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper {

}

12.创建UserService接口及其实现类,并注入UserMapper
在service包上创建UserService接口,代码如下:

package com.itlaobing.service;

public interface UserService {

}

在service包上创建包impl,然后在impl包上创建接口的实现类UserServiceImpl,并自动注入UserMapper ,代码如下:

package com.itlaobing.service.impl;

import com.itlaobing.mapper.UserMapper;
import com.itlaobing.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

}

13.为UserController 注入 UserService
将UserService自动注入到UserController里面,代码如下:

package com.itlaobing.web.controller;

import com.itlaobing.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

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

    @Autowired
    private UserService userService;

    @RequestMapping( path = "/sign-up" , method = RequestMethod.GET)
    public String signUpPage(HttpServletRequest request) {


        return "sign-up" ;
    }

}

14.在 beans.xml 中扫描组件
在resources下的 beans.xml里面添加扫描组件设置,代码如下:



<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       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.xsd
                              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    
    <context:component-scan base-package="com.itlaobing.mapper" />
    <context:component-scan base-package="com.itlaobing.service" />
    <context:component-scan base-package="com.itlaobing.web.controller" />


beans>

15.创建实体类和数据库及其数据表
实体类:在entity上创建User实体类,代码如下:

package com.itlaobing.entity;

import java.io.Serializable;

public class User implements Serializable {

    private Integer id ;
    private String username ;
    private String password ;

    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;
    }
}

创建数据库及其数据表:
在mysql中执行以下sql语句,创建数据库及其数据表:

DROP DATABASE IF EXISTS ssm ;
CREATE DATABASE ssm CHARACTER SET utf8;
USE ssm;
DROP TABLE IF EXISTS t_users ;
 CREATE TABLE t_users (
    id INT AUTO_INCREMENT ,
    username VARCHAR(50) ,
    PASSWORD VARCHAR(32) ,
    PRIMARY KEY ( id )
 );

16.在UserMapper接口中添加方法

代码如下:

package com.itlaobing.mapper;

import com.itlaobing.entity.User;
import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper {

    /**
     * 保存用户对象到数据库中并返回受SQL影响的纪录数目
     * @param user 需要被保存的对象
     * @return
     */
    int save( User user );

}

17.创建UserMapper.xml
在main下的 resources 目录中创建一个com,在com下创建文件夹itlaobing,在itlaobing下创建文件夹mapper,在mapper下创建UserMapper.xml,UserMapper.xml 的存放路径必须跟 UserMapper 接口的全限定名称一致
在UserMapper.xml 中添加以下内容:





<mapper namespace="com.itlaobing.mapper.UserMapper">

    
    
    
    
    <insert id="save" parameterType="com.itlaobing.entity.User" useGeneratedKeys="true" keyProperty="id">
         INSERT INTO t_users ( username , password ) VALUES ( #{username} ,#{password} )
     insert>

mapper>

18.在UserService接口和实现类中添加方法
UserService接口代码:

package com.itlaobing.service;

import com.itlaobing.entity.User;

public interface UserService {

    int save(User user);

}

UserServiceImpl实现类代码:

package com.itlaobing.service.impl;

import com.itlaobing.entity.User;
import com.itlaobing.mapper.UserMapper;
import com.itlaobing.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * @param user
     * @return i
     */
    @Override
    public int save(User user) {
        //调用mapper中的方法
        int i = userMapper.save(user);
        return i;
    }
}

19.在UserController中添加方法
代码如下:

package com.itlaobing.web.controller;

import com.itlaobing.entity.User;
import com.itlaobing.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

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

    @Autowired
    private UserService userService;

    @RequestMapping( path = "/sign-up" , method = RequestMethod.GET)
    public String signUpPage(HttpServletRequest request) {


        return "sign-up" ;
    }

    @RequestMapping(path = "/sign-up",method = RequestMethod.POST)
    public String signUp(User user){

        int i = userService.save(user);
        //对结果判断,i>0去登陆,i<0去注册
        if (i>0){
            return "sign-in";
        }else{
            return "sign-up";
        }
    }

}

20.添加登录页面
在 /WEB-INF/views/ 中创建 sign-in.jsp,代码如下:

<%@ page language="java"  pageEncoding="UTF-8"%>
<%@ page  contentType="text/html; charset=UTF-8"%>


    <html>
    <head>
        <meta charset="UTF-8">
        <title>登录title>

    head>
    <body>

        <h2>登录h2>

        <div>
            
            <form action="${ pageContext.request.contextPath }/user/sign-in" method="post">
                <input type="text" name="username" >
                <input type="text" name="password" >
                <input type="submit" value="登录">
            form>
        div>

    body>
html>

21.在 beans.xml 中添加数据源支持
在main下resources下新建db.properties文件,文件的内容如下:
注意修改 数据库名称、数据库用户名、数据库密码这三项

jdbc.url = jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF8&useSSL=true
jdbc.driver = com.mysql.jdbc.Driver
jdbc.user = root
jdbc.password =
druid.filters = stat
druid.maxActive =20
druid.initialSize = 1
druid.maxWait = 60000
druid.minIdle = 10
druid.maxIdle = 15
druid.timeBetweenEvictionRunsMillis = 60000
druid.minEvictableIdleTimeMillis = 300000
druid.validationQuery = SELECT 'x'
druid.testWhileIdle = true
druid.testOnBorrow = false
druid.testOnReturn = false
druid.maxOpenPreparedStatements = 20
druid.removeAbandoned = true  
druid.removeAbandonedTimeout = 1800
druid.logAbandoned = true

在bean.xml中添加数据源,内容如下:



<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       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.xsd
                              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    
    <context:component-scan base-package="com.itlaobing.mapper" />
    <context:component-scan base-package="com.itlaobing.service" />
    <context:component-scan base-package="com.itlaobing.web.controller" />


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

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="filters" value="${druid.filters}" />
        
        <property name="maxActive" value="${druid.maxActive}" />
        
        <property name="initialSize" value="${druid.initialSize}" />
        
        <property name="maxWait" value="${druid.maxWait}" />
        
        <property name="minIdle" value="${druid.minIdle}" />
        
        <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" />
        
        <property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" />
        <property name="validationQuery" value="${druid.validationQuery}" />
        <property name="testWhileIdle" value="${druid.testWhileIdle}" />
        <property name="testOnBorrow" value="${druid.testOnBorrow}" />
        <property name="testOnReturn" value="${druid.testOnReturn}" />
        <property name="maxOpenPreparedStatements" value="${druid.maxOpenPreparedStatements}" />
        
        <property name="removeAbandonedTimeout" value="${druid.removeAbandonedTimeout}" />
        
        <property name="logAbandoned" value="${druid.logAbandoned}" />
    bean>


beans>

22.在 beans.xml 中添加 MyBatis 支持
内容如下:



<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       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.xsd
                              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    
    <context:component-scan base-package="com.itlaobing.mapper" />
    <context:component-scan base-package="com.itlaobing.service" />
    <context:component-scan base-package="com.itlaobing.web.controller" />


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

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="filters" value="${druid.filters}" />
        
        <property name="maxActive" value="${druid.maxActive}" />
        
        <property name="initialSize" value="${druid.initialSize}" />
        
        <property name="maxWait" value="${druid.maxWait}" />
        
        <property name="minIdle" value="${druid.minIdle}" />
        
        <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" />
        
        <property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" />
        <property name="validationQuery" value="${druid.validationQuery}" />
        <property name="testWhileIdle" value="${druid.testWhileIdle}" />
        <property name="testOnBorrow" value="${druid.testOnBorrow}" />
        <property name="testOnReturn" value="${druid.testOnReturn}" />
        <property name="maxOpenPreparedStatements" value="${druid.maxOpenPreparedStatements}" />
        
        <property name="removeAbandonedTimeout" value="${druid.removeAbandonedTimeout}" />
        
        <property name="logAbandoned" value="${druid.logAbandoned}" />
    bean>

    
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:com/itlaobing/mapper/*.xml" />
    bean>

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


beans>

23、测试

启动tomcat,在浏览器中输入 http://localhost:80/user/sign-up 打开注册页面

输入用户名,密码,确认密码后点击注册

注册成功后,去往 登录页面。( 因为没有处理登录操作,所以别点登录 )

去数据库中查询,查看新添加的数据;

24.静态资源配置
在webapp下新建文件夹assets
在 mvc.xml 中添加静态资源配置,内容如下:

   

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       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">

        
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/" />
            <property name="suffix" value=".jsp" />
        bean>

        
        <context:component-scan base-package="com.itlaobing.web.controller" />
        <mvc:annotation-driven  />

        
        
        <mvc:resources mapping="/assets/**" location="/assets/" />


beans>

25.添加事务支持
在bean.xml中添加事务配置,内容如下:



<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       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.xsd
                              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    
    <context:component-scan base-package="com.itlaobing.mapper" />
    <context:component-scan base-package="com.itlaobing.service" />
    <context:component-scan base-package="com.itlaobing.web.controller" />


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

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="filters" value="${druid.filters}" />
        
        <property name="maxActive" value="${druid.maxActive}" />
        
        <property name="initialSize" value="${druid.initialSize}" />
        
        <property name="maxWait" value="${druid.maxWait}" />
        
        <property name="minIdle" value="${druid.minIdle}" />
        
        <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" />
        
        <property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" />
        <property name="validationQuery" value="${druid.validationQuery}" />
        <property name="testWhileIdle" value="${druid.testWhileIdle}" />
        <property name="testOnBorrow" value="${druid.testOnBorrow}" />
        <property name="testOnReturn" value="${druid.testOnReturn}" />
        <property name="maxOpenPreparedStatements" value="${druid.maxOpenPreparedStatements}" />
        
        <property name="removeAbandonedTimeout" value="${druid.removeAbandonedTimeout}" />
        
        <property name="logAbandoned" value="${druid.logAbandoned}" />
    bean>

    
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:com/itlaobing/mapper/*.xml" />
    bean>

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

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    bean>

    
    <tx:annotation-driven transaction-manager="transactionManager"/>


beans>

在UserService的实现类UserServiceImpl中添加事务的注解@Transactional,代码如下:

package com.itlaobing.service.impl;

import com.itlaobing.entity.User;
import com.itlaobing.mapper.UserMapper;
import com.itlaobing.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * @param user
     * @return i
  **重点内容**   */
    @Transactional
    @Override
    public int save(User user) {
        //调用mapper中的方法
        int i = userMapper.save(user);

        return i;
    }
}

**至此,ssm框架完全搭建完成,赶紧体验框架开发的快感吧!如有问题,请详细的描述问题信息发送邮件到[email protected]
资源文件下载地址 https://download.csdn.net/download/safdghj456/10555732**

你可能感兴趣的:(技术博客)