IntelliJ IDEA 2017.1.4下的SSM

本文详细介绍了如何在IntelliJ IDEA 2017.1.4环境下搭建SSM(Spring + SpringMVC + MyBatis)框架。从创建Maven Web项目开始,逐步讲解了配置过程、数据库设计及具体的代码实现。
摘要由CSDN通过智能技术生成

IntelliJ IDEA 2017.1.4下的SSM

创建工程

  • Create New Project
  • 新建maven+web项目
  • 定义包名和项目名
  • 配置maven和相应的配置文件和本地工厂
  • 结束配置
  • 项目创建完成

工程创建完成,现在来整合Spring,SpringMVC,Mybatis

  • 工程框架
    • 注:先在main下建一个java目录,并设置为Sources Root

数据库设计

  • 数据库名
    • springmvc_db
  • 表名
    • user
  • 表结构

  • 具体代码

    • src

      • java

        • com

          • peng

            • controller

              • UserServlet

                package com.peng.controller;
                
                import java.util.List;
                
                import org.springframework.beans.factory.annotation.Autowired;
                import org.springframework.beans.factory.annotation.Qualifier;
                import org.springframework.stereotype.Controller;
                import org.springframework.ui.Model;
                import org.springframework.web.bind.annotation.RequestMapping;
                
                import com.peng.pojo.User;
                import com.peng.service.UserService;
                
                @Controller(value = "userServlet")
                public class UserServlet {
                    @Autowired
                    @Qualifier(value = "userService")
                    private UserService userService;
                
                    @RequestMapping("/selectUsers.action")
                    public String findAllAction(Model model) {
                        List<User> user_list = userService.selectUsers();
                        System.out.println(user_list);
                        model.addAttribute("user_list", user_list);
                        return "users";
                    }
                }
                
            • mapper

              • UserMapper

                package com.peng.mapper;
                
                import java.util.List;
                
                import org.springframework.stereotype.Repository;
                
                import com.peng.pojo.User;
                
                @Repository(value = "userMapper")
                public interface UserMapper {
                    public List<User> selectUsers();
                }
                
            • pojo

              • User package com.peng.pojo;

                import java.io.Serializable;

                @SuppressWarnings("serial") public class User implements Serializable { private String id; private String name; private String email; private String money;

                public User() {
                    super();
                }
                
                public User(String id, String name, String emial, String money) {
                    super();
                    this.id = id;
                    this.name = name;
                    this.email = emial;
                    this.money = money;
                }
                
                public String getId() {
                    return id;
                }
                
                public void setId(String id) {
                    this.id = id;
                }
                
                public String getName() {
                    return name;
                }
                
                public void setName(String name) {
                    this.name = name;
                }
                
                public String getEmial() {
                    return email;
                }
                
                public void setEmial(String emial) {
                    this.email = emial;
                }
                
                public String getMoney() {
                    return money;
                }
                
                public void setMoney(String money) {
                    this.money = money;
                }
                
                @Override
                public String toString() {
                    return "【编号:" + id + "姓名:" + name + ",邮箱:" + email + ",存款:" + money + "】";
                }
                

                }

                package com.peng.service;
                
                import java.util.List;
                
                import com.peng.pojo.User;
                
                public interface UserService {
                    /**
                     * 查询所有的用户
                     * 
                     * @return
                     */
                    List<User> selectUsers();
                
                }
                
            • service

              • UserService

              • UserServiceImpl

                package com.peng.service;
                
                import java.util.List;
                
                import org.springframework.beans.factory.annotation.Autowired;
                import org.springframework.beans.factory.annotation.Qualifier;
                import org.springframework.stereotype.Service;
                
                import com.peng.mapper.UserMapper;
                import com.peng.pojo.User;
                
                @Service(value = "userService")
                public class UserServiceImpl implements UserService {
                
                    // 注入dao层对象
                    @Autowired
                    @Qualifier(value = "userMapper")
                    private UserMapper userMapper;
                
                    public List<User> selectUsers() {
                        return userMapper.selectUsers();
                    }
                
                }
                
      • resources

        • mapper

          • UserMapper.xml

            <?xml version="1.0" encoding="UTF-8" ?>
            <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
            <mapper namespace="com.peng.mapper.UserMapper">
                <select id="selectUsers" resultType="com.peng.pojo.User">
                    select * from user
                </select>
            </mapper>
            
        • applicationContext.xml

          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="http://www.springframework.org/schema/beans"
                 xmlns:context="http://www.springframework.org/schema/context"
                 xmlns:aop="http://www.springframework.org/schema/aop" 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-3.2.xsd
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd 
              http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd ">
              <!-- 扫描包 -->
              <context:component-scan base-package="com.peng"></context:component-scan>
              <!-- 扫描注解 -->
              <context:annotation-config></context:annotation-config>
              <!-- sql的会话工厂 -->
              <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
                  <!-- 引入数据源 -->
                  <property name="dataSource" ref="c3p0dataSource"></property>
                  <!-- 引入核心配置文件 -->
                  <property name="configLocation" value="classpath:/sqlMapConfig.xml"></property>
                  <!-- 引入映射文件 -->
                  <property name="mapperLocations" value="classpath:/mapper/*Mapper.xml"></property>
              </bean>
              <!-- Mapper接口的扫描器 -->
              <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                  <property name="basePackage" value="com.peng.mapper"></property>
              </bean>
              <!-- 配置文件 -->
              <bean
                      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
                  <property name="location" value="classpath:/jdbc_config.properties"></property>
              </bean>
              <!--c3p0 -->
              <bean id="c3p0dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                  <property name="driverClass" value="${jdbc.driver}"></property>
                  <property name="jdbcUrl" value="${jdbc.url}"></property>
                  <property name="user" value="${jdbc.user}"></property>
                  <property name="password" value="${jdbc.password}"></property>
                  <property name="minPoolSize" value="3"></property>        <!--最小连接数 -->
                  <property name="initialPoolSize" value="5"></property>    <!-- 初始化连接数 -->
                  <property name="acquireIncrement" value="3"></property>    <!-- 每次增长的个数 -->
              </bean>
          </beans>
          
        • applicationContext-mvc.xml

          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="http://www.springframework.org/schema/beans"
              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-3.2.xsd
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd 
              http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd ">
              <!-- 扫描包 -->
              <context:component-scan base-package="com.peng"></context:component-scan>
              <!-- 扫描注解 -->
              <context:annotation-config></context:annotation-config>
              <!-- 资源解析器:前后缀 -->
              <bean
                  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                  <property name="prefix" value="/WEB-INF/">
                  </property>
                  <property name="suffix" value=".jsp"></property>
              </bean>
              <!-- 文件上传资源解析器 -->
              <bean id="multipartResolver"
                  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
                  <property name="defaultEncoding" value="utf-8"></property>
                  <property name="maxUploadSize" value="10485760000"></property>
                  <property name="maxInMemorySize" value="40960"></property>
              </bean>
          </beans>
          
        • jdbc_config.properties

          jdbc.user=root
          jdbc.password=root
          jdbc.url=jdbc\:mysql\://localhost\:3306/springmvc_db
          jdbc.driver=com.mysql.jdbc.Driver
          
        • log4j.properties

          log4j.rootLogger=DEBUG, Console
          #Console
          log4j.appender.Console=org.apache.log4j.ConsoleAppender
          log4j.appender.Console.layout=org.apache.log4j.PatternLayout
          log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
          log4j.logger.java.sql.ResultSet=INFO
          log4j.logger.org.apache=INFO
          log4j.logger.java.sql.Connection=DEBUG
          log4j.logger.java.sql.Statement=DEBUG
          log4j.logger.java.sql.PreparedStatement=DEBUG                
          
        • 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>
          </configuration>                
          
      • webapp

        • js

          (jquery的js文件,这块略)
          
        • users.jsp

          <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
          <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
          <%@ page isELIgnored="false"%>
          <!DOCTYPE HTML>
          <html>
          <head>
              <title>用户管理</title>
              <meta http-equiv="content-type" content="text/html; charset=UTF-8">
              <style type="text/css">
                  body {
                      font-family: "微软雅黑"
                  }
          
                  h2, h4 {
                      text-align: center;
                  }
          
                  div#box1, div#box2 {
                      text-align: center;
                  }
          
                  hr {
                      margin: 20px 0;
                  }
          
                  table {
                      margin: 0 auto;
                      width: 70%;
                      text-align: center;
                      border-collapse: collapse;
                  }
          
                  td, th {
                      padding: 7px;
                      width: 20%;
                  }
          
                  th {
                      background-color: #DCDCDC;
                  }
              </style>
          
              <!--引入jquery的js库-->
              <script src="js/jquery-1.4.2.js"></script>
              <script type="text/javascript">
                  $(function() {
                      $("#add").click(
                          function() {
                              //获取输入信息
                              var id = $("#box1 input[name='id']").val().trim();
                              var name = $("#box1 input[name='name']").val().trim();
                              var email = $("#box1 input[name='email']").val().trim();
                              var salary = $("#box1 input[name='salary']").val().trim();
                              //校验
                              if (id == "" || name == "" || email == "" || salary == "") {
                                  alert("员工信息不能为空");
                                  return;
                              }
                              //员工id不能重复
                              var flag = false;
                              $("table tr").each(function() {
                                  if ($(this).find("td:eq(1)").text() == id) {
                                      alert("ID已存在");
                                      flag = true;
                                      return false;
                                  }
                              });
                              if (flag) {
                                  return;
                              }
                              //将员工信息添加到列表中
                              var $tab = $("table");
                              var $tr = $("<tr></tr>");
                              var $td0 = $("<td><input type='checkbox'/></td>");
                              var $td1 = $("<td>" + id + "</td>");
                              var $td2 = $("<td>" + name + "</td>");
                              var $td3 = $("<td>" + email + "</td>");
                              var $td4 = $("<td>" + salary + "</td>");
                              $tr.append($td0).append($td1).append($td2).append($td3)
                                  .append($td4);
                              $tab.append($tr);
          
                          });
                      //全选按钮
                      $("#all").click(function() {
                          //获取全选状态
                          var check = $(this).attr("checked");
                          //将其他复选框状态与全选一致
                          $("table input").attr("checked", check);
                      });
                      //删除
                      $("#del").click(function() {
                          $("input:checked:not(input[id='all'])").parents("tr").remove();
                      });
                      //修改
                      $("#upd").click(function() {
                          //获取修改信息
                          var id = $("#box2 input[name='id']").val().trim();
                          var name = $("#box2 input[name='name']").val().trim();
                          var email = $("#box2 input[name='email']").val().trim();
                          var salary = $("#box2 input[name='salary']").val().trim();
          
                          //校验
                          if (id == "" || name == "" || email == "" || salary == "") {
                              alert("修改信息不能为空");
                              return;
                          }
                          //根据ID进行修改
                          var flag = true;
                          $("table tr").each(function() {
                              if ($(this).find("td:eq(1)").text() == id) {
                                  //进行修改
                                  flag = false;
                                  $(this).find("td:eq(2)").text(name);
                                  $(this).find("td:eq(3)").text(email);
                                  $(this).find("td:eq(4)").text(salary);
                                  return false;
          
                              }
                          });
                          if (flag) {
                              alert("员工id不存在!");
                          }
          
                      });
          
                  });
              </script>
          </head>
          
          <body>
          <h2>添加新员工</h2>
          <div id="box1">
              ID:<input type="text" name="id" /> 姓名:<input type="text" name="name" />
              邮箱:<input type="text" name="email" /> 工资:<input type="text"
                                                              name="salary" /> <input type="button" id="add" value="添加" />
          </div>
          <hr />
          <table border="1">
              <tr>
                  <th><input type="checkbox" id="all" /> <!--全选--></th>
                  <th>ID</th>
                  <th>姓名</th>
                  <th>邮箱</th>
                  <th>工资</th>
              </tr>
              <c:forEach items="${user_list}" var="item">
                  <tr>
                      <td><input type="checkbox" /></td>
                      <td>${item.id}</td>
                      <td>${item.name}</td>
                      <td>${item.emial}</td>
                      <td>${item.money}</td>
                  </tr>
              </c:forEach>
          
          </table>
          <p align="center">
              <a href="#" id="del">删除选中</a>
          </p>
          
          <hr />
          <div id="box2">
              ID:<input type="text" name="id" /> 姓名:<input type="text" name="name" />
              邮箱:<input type="text" name="email" /> 工资:<input type="text"
                                                              name="salary" /> <input type="button" id="upd" value="修改" />
          </div>
          </body>
          </html>                
          
        • web.xml

          <!DOCTYPE web-app PUBLIC
           "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
           "http://java.sun.com/dtd/web-app_2_3.dtd" >
          
          <web-app>
            <!-- 解决乱码过滤器(只能解决post的,get的需要手动解决) -->
            <!-- 乱码过滤器 -->
            <filter>
              <filter-name>characterFilter</filter-name>
              <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
              <init-param>
                <param-name>encoding</param-name>
                <param-value>utf-8</param-value>
              </init-param>
              <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
              </init-param>
            </filter>
            <filter-mapping>
              <filter-name>characterFilter</filter-name>
              <url-pattern>/*</url-pattern>
            </filter-mapping>
            <!-- 分发器 -->
            <servlet>
              <servlet-name>springmvc_dispatcher</servlet-name>
              <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
              <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:/applicationContext*.xml</param-value><!-- 注:这里的* -->
              </init-param>
            </servlet>
            <!-- 分发器的映射 -->
            <servlet-mapping>
              <servlet-name>springmvc_dispatcher</servlet-name>
              <url-pattern>*.action</url-pattern>
            </servlet-mapping>
            <!-- 欢迎界面 -->
            <welcome-file-list>
              <welcome-file>index.jsp</welcome-file>
            </welcome-file-list>
          </web-app>
          
      • index.jsp

        <%@ page contentType="text/html;charset=UTF-8" language="java" %>
        <html>
        <head>
            <title>Title</title>
        </head>
        <body>
        asdfghjkl
        </body>
        </html>
        
    • target(这个系统自动生成)

    • pom.xml

      <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/maven-v4_0_0.xsd">
          <modelVersion>4.0.0</modelVersion>
          <groupId>com.peng</groupId>
          <artifactId>ssm_test</artifactId>
          <packaging>war</packaging>
          <version>1.0-SNAPSHOT</version>
          <name>ssm_test Maven Webapp</name>
          <url>http://maven.apache.org</url>
          <properties>
              <!-- spring版本号 -->
              <spring.version>4.0.2.RELEASE</spring.version>
              <!-- mybatis版本号 -->
              <mybatis.version>3.2.6</mybatis.version>
              <!-- log4j日志文件管理包版本 -->
              <slf4j.version>1.7.7</slf4j.version>
              <log4j.version>1.2.17</log4j.version>
          </properties>
          <dependencies>
              <dependency>
                  <groupId>c3p0</groupId>
                  <artifactId>c3p0</artifactId>
                  <version>0.9.1.2</version>
              </dependency>
              <dependency>
                  <groupId>junit</groupId>
                  <artifactId>junit</artifactId>
                  <version>3.8.1</version>
                  <scope>test</scope>
              </dependency>
              <!-- spring核心包 -->
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-core</artifactId>
                  <version>${spring.version}</version>
              </dependency>
      
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-oxm</artifactId>
                  <version>${spring.version}</version>
              </dependency>
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-tx</artifactId>
                  <version>${spring.version}</version>
              </dependency>
      
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-jdbc</artifactId>
                  <version>${spring.version}</version>
              </dependency>
      
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-web</artifactId>
                  <version>${spring.version}</version>
              </dependency>
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-webmvc</artifactId>
                  <version>${spring.version}</version>
              </dependency>
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-aop</artifactId>
                  <version>${spring.version}</version>
              </dependency>
      
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-context-support</artifactId>
                  <version>${spring.version}</version>
              </dependency>
      
              <dependency>
                  <groupId>org.springframework</groupId>
                  <artifactId>spring-test</artifactId>
                  <version>${spring.version}</version>
              </dependency>
              <!-- mybatis核心包 -->
              <dependency>
                  <groupId>org.mybatis</groupId>
                  <artifactId>mybatis</artifactId>
                  <version>${mybatis.version}</version>
              </dependency>
              <!-- mybatis/spring包 -->
              <dependency>
                  <groupId>org.mybatis</groupId>
                  <artifactId>mybatis-spring</artifactId>
                  <version>1.2.2</version>
              </dependency>
      
              <!-- 导入Mysql数据库链接jar包 -->
              <dependency>
                  <groupId>mysql</groupId>
                  <artifactId>mysql-connector-java</artifactId>
                  <version>5.1.30</version>
              </dependency>
      
              <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
              <dependency>
                  <groupId>commons-dbcp</groupId>
                  <artifactId>commons-dbcp</artifactId>
                  <version>1.2.2</version>
              </dependency>
              <!-- JSTL标签类 -->
              <dependency>
                  <groupId>jstl</groupId>
                  <artifactId>jstl</artifactId>
                  <version>1.2</version>
              </dependency>
              <!-- 日志文件管理包 -->
              <!-- log start -->
              <dependency>
                  <groupId>log4j</groupId>
                  <artifactId>log4j</artifactId>
                  <version>${log4j.version}</version>
              </dependency>
      
      
              <!-- 格式化对象,方便输出日志 -->
              <dependency>
                  <groupId>com.alibaba</groupId>
                  <artifactId>fastjson</artifactId>
                  <version>1.1.41</version>
              </dependency>
      
      
              <dependency>
                  <groupId>org.slf4j</groupId>
                  <artifactId>slf4j-api</artifactId>
                  <version>${slf4j.version}</version>
              </dependency>
      
              <dependency>
                  <groupId>org.slf4j</groupId>
                  <artifactId>slf4j-log4j12</artifactId>
                  <version>${slf4j.version}</version>
              </dependency>
              <!-- log end -->
              <!-- 映入JSON -->
              <dependency>
                  <groupId>org.codehaus.jackson</groupId>
                  <artifactId>jackson-mapper-asl</artifactId>
                  <version>1.9.13</version>
              </dependency>
              <!-- 上传组件包 -->
              <dependency>
                  <groupId>commons-fileupload</groupId>
                  <artifactId>commons-fileupload</artifactId>
                  <version>1.3.1</version>
              </dependency>
              <dependency>
                  <groupId>commons-io</groupId>
                  <artifactId>commons-io</artifactId>
                  <version>2.4</version>
              </dependency>
              <dependency>
                  <groupId>commons-codec</groupId>
                  <artifactId>commons-codec</artifactId>
                  <version>1.9</version>
              </dependency>
          </dependencies>
          <build>
              <resources>
                  <!--编译之后包含xml-->
                  <resource>
                      <directory>src/resources</directory>
                      <includes>
                          <include>**/*.xml</include>
                      </includes>
                      <filtering>true</filtering>
                  </resource>
              </resources>
          </build>
      </project>
      

Tomcat的配置

执行

  • 成功界面
  • 测试网址:
    • http://localhost/selectUsers.action
    • 页面

坑 VS 对策

项目结构中的xml文件 VS 放置的位置与访问

  • 放置的位置
    1. 放在java下,当打包时,不会自动放到classes文件的目录下,访问时很容易失败
    2. 放在resources下,不一定会自动放到classes文件夹下,需要手动配置
    3. 神器(嘻嘻:根据自己的项目实际情况来用)
      1. 将mapper.xml放到resources下
      2. 在pom.xml中配置资源的访问器

        <build>
            <resources>
                <!--编译之后包含xml-->
                <resource>
                    <directory>src/resources</directory>
                    <includes>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
            </resources>
        </build>
        

其他小坑 VS 细心(萌萌哒。。。)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乘风御浪云帆之上

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值