ssm框架搭建过程[通俗易懂]

ssm框架搭建过程[通俗易懂]ssm框架搭建过程

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

1.新建一个maven web项目(新建过程请参考:https://blog.csdn.net/AinUser/article/details/78185128),项目结构如下:
这里写图片描述
2.项目中需要引入的jar包:

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.6</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

  </dependencies>

其实可以在需要的时候引入相关的jar包即可,这样会避免引入一些没有用的。
3.mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <!--之后用于测试-->
        <typeAlias type="com.tgb.entity.User" alias="User" />
    </typeAliases>
</configuration>

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

    <!-- 数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:mapping/UserMapper.xml"/>
    </bean>

    <!-- DAO接口所在包名,Spring会自动查找之中的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.tgb.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

    <!--事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--开启事务注解扫描-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

5.applicationContext-mvc.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">

    <mvc:annotation-driven/>

    <mvc:default-servlet-handler/>

    <context:component-scan base-package="com.tgb"/>

   <!-- <mvc:resources mapping="/static/**" location="WEB-INF/static/"/>-->

    <!--配置springMVC的视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

6.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
    <!--加载spring容器配置-->
    <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

  <!--Spring容器加载所有的配置文件的路径-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:spring/applicationContext.xml</param-value>
  </context-param>

  <servlet>
    <servlet-name>springMvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:spring/applicationContext-mvc.xml</param-value>
    </init-param>
    <!--用来标记是否在项目启动时就加在此Servlet,0或正数表示容器在应用启动时就加载这个Servlet, 当是一个负数时或者没有指定时,则指示容器在该servlet被选择时才加载.正数值越小启动优先值越高 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>encodingFilter</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>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

到此为止,配置文件基本上就配好了,我们需要写一个功能来测试一下。
7.生成实体,mapper等文件。(逆向工程参考:https://blog.csdn.net/zhshulin/article/details/23912615
建表Sql:

CREATE TABLE `tb_user` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `NAME` varchar(18) NOT NULL, `SEX` varchar(18) NOT NULL, `AGE` int(11) DEFAULT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

User实体:

package com.tgb.entity;

public class User {
    private Integer id;

    private String name;

    private String sex;

    private Integer age;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

UserMapper:

package com.tgb.dao;

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

import java.util.List;

@Repository
public interface UserMapper { 
   
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

    List<User> selectAllUser();
}

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.tgb.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="com.tgb.entity.User" >
    <id column="ID" property="id" jdbcType="INTEGER" />
    <result column="NAME" property="name" jdbcType="VARCHAR" />
    <result column="SEX" property="sex" jdbcType="VARCHAR" />
    <result column="AGE" property="age" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Base_Column_List" >
    ID, NAME, SEX, AGE
  </sql>

  <select id="selectAllUser" resultType="User">
    select * from tb_user;
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from tb_user
    where ID = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from tb_user
    where ID = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="User" >
    insert into tb_user (ID, NAME, SEX, 
      AGE)
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, 
      #{age,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="User" >
    insert into tb_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        ID,
      </if>
      <if test="name != null" >
        NAME,
      </if>
      <if test="sex != null" >
        SEX,
      </if>
      <if test="age != null" >
        AGE,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null" >
        #{sex,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="User" >
    update tb_user
    <set >
      <if test="name != null" >
        NAME = #{name,jdbcType=VARCHAR},
      </if>
      <if test="sex != null" >
        SEX = #{sex,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        AGE = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where ID = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="User" >
    update tb_user
    set NAME = #{name,jdbcType=VARCHAR},
      SEX = #{sex,jdbcType=VARCHAR},
      AGE = #{age,jdbcType=INTEGER}
    where ID = #{id,jdbcType=INTEGER}
  </update>
</mapper>

Service接口和实现类:

package com.tgb.service;

import com.tgb.entity.User;
import java.util.List;

/** * Created by xiaojie on 2018/7/8. */
public interface UserService { 
   
    public List<User> getUser();

}

package com.tgb.service.impl;

import com.tgb.dao.UserMapper;
import com.tgb.entity.User;
import com.tgb.service.UserService;
import org.springframework.stereotype.Service;

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

/** * Created by xiaojie on 2018/7/8. */
@Service("userService")
public class UserServiceImpl implements UserService { 
   

    @Resource(name="userMapper")
    private UserMapper userMapper;
    @Override
    public List<User> getUser() {
        return userMapper.selectAllUser();
    }
}

Controller

package com.tgb.controller;

import com.tgb.entity.User;
import com.tgb.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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

/** * Created by xiaojie on 2018/7/8. */
@Controller
@RequestMapping(value = "/user")
public class UserController { 
   

    @Resource(name="userService")
    UserService userService;

    @RequestMapping(value = "/list")
    public ModelAndView list(){
        ModelAndView mv = new ModelAndView();
        List<User> userList = userService.getUser();
        mv.addObject("userList",userList);
        mv.setViewName("/show");
        return mv;
    }
}

创建一个show.jsp文件:

<%-- Created by IntelliJ IDEA. User: xiaojie Date: 2018/7/8 Time: 15:25 To change this template use File | Settings | File Templates. --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <table border="1">
        <tr>
            <td>序号</td>
            <td>姓名</td>
            <td>年龄</td>
            <td>性别</td>
        </tr>
        <c:choose>
            <c:when test="${not empty userList}">
                <c:forEach items="${userList}" var="user" varStatus="vs">
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.name}</td>
                        <td>${user.age}</td>
                        <td>${user.sex}</td>
                    </tr>
                </c:forEach>
            </c:when>
            <c:otherwise>
                <tr>
                    <td colspan="2">无数据!</td>
                </tr>
            </c:otherwise>
        </c:choose>
    </table>
</body>
</html>

启动项目,在浏览器里输入http://localhost:8080/user/list 如果出现如下列表,则说明ssm的一条线已经通了。
这里写图片描述
跟着这个步骤做下来,一般不会顺利地显示出来,可能会遇到一些问题,百度一下,都会解决的。

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

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

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

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

(0)


相关推荐

  • 牛x!一款比传统数据库快 100-1000 倍的数据库,来认识一下?

    点击上方“全栈程序员社区”,星标公众号 重磅干货,第一时间送达 一、ClickHouse 是什么? 二、业务问题 三、ClickHouse实践 四、遇到的坑 五、总结 一、Clic…

  • vue 富文本编辑框_基于vue的富文本编辑器

    vue 富文本编辑框_基于vue的富文本编辑器1、下载插件npmiwangeditor–save插件官网地址:https://www.wangeditor.com/2、封装富文本组件<templatelang=”html”><divclass=”editor”><!–<divref=”toolbar”class=”toolbar”></div>–><divref=”editor”class=”text”></div

  • HashMap底层数据结构原理解析[通俗易懂]

    HashMap底层数据结构原理解析[通俗易懂]老师:JDK中我们最常用的一个数据类是HashMap。那么,谁可以回答一下HashMap的底层数据结构原理是什么呢?小明:老师,我知道。众所周知,HashMap是一个用于存储Key-Value键值对的集合,每一个键值对也叫做Entry。这些个键值对(Entry)分散存储在一个数组当中,这个数组就是HashMap的主干。HashMap数组每一个元素的初始值都是Null。…

  • unity3d教学视频_unity3d激活成功教程版

    unity3d教学视频_unity3d激活成功教程版2018年什么游戏最火?不用问,肯定是人人都在撸的“王者荣耀”和吃鸡游戏了。 只会打游戏,不去研究可不行。一直在想,像王者荣耀这样火的游戏是用什么引擎和语言开发的?这里就不得不说到现在最主流的游戏开发引擎——Unity3D了。Unity3D是由UnityTechnologies开发的一个让玩家轻松创建诸如三维视频游戏、建筑可视化、实时三维动画等类型互动内容的多平台的综…

  • 操作系统中 heap 和 stack 的区别

    操作系统中 heap 和 stack 的区别 操作系统中 heap 和 stack 的区别(2016年腾讯校招笔试)概念:   堆栈是两种数据结构,是一种数据项按序排列的数据结构,只能在一端进行插入和删除操作。堆为队列优先,先进先出(FIFO)。栈为先进后出(FILO)。区别:一、空间区别:    1.堆(操作系统):一般由程序员分配释放,若程序员不释放,程序结束时可能由OS回收,分配方式类似于链表。PS:java中都是…

  • ■ 直接调用阿里云视频点播API实现视频播放

    ■ 直接调用阿里云视频点播API实现视频播放

发表回复

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

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