使用IDEA搭建SSM框架(Spring+SpringMVC+Mybatis+Maven)

(菜鸟教程!!!)

本文详细记录了一次SSM框架搭建的过程,过程中遇到了各种坎坷,终于成功的搭建成功!

准备工作:

本人的操作系统为CentOS7.4,项目搭建过程中的路径做相应改动

1.IDEA (我的版本为2018.3)

2.JDK (1.8)

3.Maven (3.6)

4.MySQL (5.6)

5.TomCat (8.5)

其中,使用Maven进行软件包管理,Apache-tomcat用作服务器,数据库使用的是Mysql,项目中的Dao层、Model层以及Mapper是通过Mybatis-generator自动生成的。

SSM框架搭建步骤:

一、创建项目:

1.使用Maven做软件包管理,打开IDEA,选择Create New Project

2.选择或添加JDK的路径,勾选Create from archetype后,选择创建一个webapp 

3.输入GroupID(习惯和自己的包名相同),ArtifactID(习惯直接定义为项目名)

4.选择或添加Maven的路径

5.输入项目名称后点击Finish完成项目的创建。(第一次创建的时候时间会比较长,耐心等待创建完毕,又下角会有进度条,这里先不用急着点击Import Changes,等一会创建完目录后可以省事!!!)

6.Maven创建完的项目路径涨的酱紫~~~

7.首先要完善项目的目录结构,如下图~

8.创建好各种各样的文件夹之后,刚刚又下角的Import Changes要发挥大作用了,点击Import Changes,会发现java、resources等文件夹的图表变了!(这里如果没有又下角的Import Changes,看步骤9)

9.(完成第8步,这里忽略)这里如果没有又下角的Import Changes可以点击File —— Project Structure —— Moudules 进行设置(点击路径下的目录,然后点击上面的分类,让idea识别目录作用)

10.好了~~~项目的准备工作完成!!!

 

二、添加Maven中的软件包(配置pom.xml)

打开pom.xml进行配置。pom.xml主要描述了项目的maven坐标,依赖关系,开发者需要遵循的规则,缺陷管理系统,组织和licenses,以及其他所有的项目相关因素,是项目级别的配置文件。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yueluo</groupId>
    <artifactId>Testssm</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>testssm Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.yueluo.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>

        <!--  spring版本号  -->
        <spring.version>4.3.5.RELEASE</spring.version>
        <!--  mybatis版本号  -->
        <mybatis.version>3.4.1</mybatis.version>
        <!--  log4j日志文件管理包版本  -->
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
    </properties>

    <dependencies>
        <!--  junit测试包  -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!--  jstl  -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2.1-b03</version>
            <scope>provided</scope>
        </dependency>

        <!--  servlet  -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

        <!--  json数据  -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.7.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.7.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.7.1</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </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.3.1</version>
        </dependency>

        <!--  mysql驱动包  -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
            <scope>runtime</scope>
        </dependency>

        <!--  spring核心包  -->
        <!--  springframe start  -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</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-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-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</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-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--  springframe end  -->

        <!--  日志文件管理包  -->
        <!--  log start  -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</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>
        <!-- 上传 -->
        <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>
        <!--  log end  -->
        <!--   commons   -->
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.5.6</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.8.3</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>jsr250-api</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>net.sf.ezmorph</groupId>
            <artifactId>ezmorph</artifactId>
            <version>1.0.6</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>


    </dependencies>
    <build>
        <finalName>testssm</finalName>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <!-- 允许移动生成的文件 -->
                    <verbose>true</verbose>
                    <!-- 允许覆盖生成的文件 -->
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

在编辑完pom.xml之后,点击有下角的Import Changes,会自动下载Maven中的jar包,耐心等待jar包的下载完成,完成后,pom.xml文件中没有红色的名字,若有红色的,请检查相关配置。(等待的过程是漫长的,我们可以先进行下一步的配置~~~)

 

三、配置Mybatis(配置持久层相关文件)

1.在resources路径下右键,New —— Resource Bundel,新建三个配置文件:jdbc,log4j,generator

 

其中 文件内容如下

jdbc.properties(这里面的url中testssm为mysql数据库中的database数据库名,username和password为数据库的用户名密码,根据自己配置做相应的修改)

#配置本地的数据库
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/testssm?useUnicode=true&characterEncoding=utf-8
username=root
password=123456

generator.properties(这里面的url,username和password 也要做相应的修改,最下面table=user中的user为数据库中的表名,在使用mybatis gentrator创建Dao层和Model层的时候使用

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/testssm?useUnicode=true&characterEncoding=utf-8
username=root
password=123456

#model 包名和 java目录
modelPackage=com.yueluo.model
modelProject=src/main/java
#sqlmap包名 和resources目录
sqlPackage=sqlmap
sqlProject=src/main/resources
#mapper包名和 java目录
mapperPackage=com.yueluo.dao
mapperProject=src/main/java

table=user

log4j.properties(这个为输出日志文件的配置,其中日志的路径:log4j.appender.D.File 一定要设置成自己的日志路径,并创建好文件夹,不然会报错)

#定义log输出级别
log4j.rootLogger = INFO,D
#log4j.rootLogger=INFO,Console,File

###输出到控制台###
log4j.logger.toConsole=debug,stdout

#定义日志输出到控制台
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out

#可以灵活地指定日志输出格式
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout

#定义日志输出的具体格式
log4j.appender.stdout.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %c -%F(%L) -%m%n

log4j.logger.daily=INFO,D
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = /run/media/ry03/wuyunfeng/workspace/log4j/testssm.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %c -%F(%L) -%m%n

2.1.在resources路径下右键,New —— Resource Bundel,新建一个xml文件:generatorCongif.xml  (记得点上Use XML---的小勾勾哦)

 

内容如下

generatorCongif.xml(这里面的classPathEntry location="  "  需要修改!!!)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>

    <!--导入属性配置 -->
    <properties resource="generator.properties"/>

    <classPathEntry location="/home/ry03/.m2/repository/mysql/mysql-connector-java/5.1.41/mysql-connector-java-5.1.41.jar"/>
    <context id="context1">
        <!-- 注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
            <property name="suppressDate" value="true"/> <!-- 是否取消生成注释代时间戳 -->
        </commentGenerator>

        <jdbcConnection driverClass="${driver}"
                        connectionURL="${url}"
                        userId="${username}"
                        password="${password}"/>

        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <javaModelGenerator targetPackage="${modelPackage}" targetProject="${modelProject}"/>
        <sqlMapGenerator targetPackage="${sqlPackage}" targetProject="${sqlProject}"/>
        <javaClientGenerator targetPackage="${mapperPackage}" targetProject="${mapperProject}" type="XMLMAPPER"/>

        <!-- 配置需要生成的Map方法 -->
        <table schema=""
               tableName="${table}"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false">
            
        </table>
    </context>
</generatorConfiguration>

展开左侧软件包,找到mysql的驱动包,然后右键,Copy Path,拷贝mysql驱动包的路径到generatorCongif.xml配置中的classPathEntry location中。

修改好路径后,需要创建mysql数据表,

先创建一个名字为testssm的数据库,然后新建表user

create database testssm;


use testssm


CREATE TABLE user(
id int(8) unsigned NOT NULL AUTO_INCREMENT,
username varchar(30) NOT NULL,
password varchar(30) NOT NULL,
PRIMARY KEY (id)
)ENGINE=InnoDB AUTO_INCREMENT=20180001 DEFAULT CHARSET=utf8;

数据库创建好后,点击右侧的Maven,展开mybatis-generator, 双击  mybatis-generator:generate

(如果右侧没有这一栏,可以点击 View —— Tool Buttons 打开)

执行完成之后,控制台会出现 BUILD SUCCESS的结果

展开左侧的目录,发现生成了三个新的文件~~~

此时,Mybatis配置成功!!!!!是不是很激动~~~接下来一起来测试以下生成的这些文件吧~~~~

 

四、配置Spring(配置逻辑层相关文件)

1.在spring文件夹下新建applicationContext.xml

配置applicationContext.xml

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:context="http://www.springframework.org/schema/context"
       xmlns:beans="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-4.3.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

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

    <!--数据库配置 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
        <property name="initialSize" value="1"/>
        <property name="maxActive" value="100"/>
        <property name="maxIdle" value="5"/>
        <property name="maxWait" value="80000"/>
    </bean>

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

    <!-- 配置会话工厂SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:sqlmap/*Mapper.xml"/>
        <property name="typeAliasesPackage" value="com.yueluo.model" />
    </bean>

    <!-- 在spring容器中配置mapper的扫描器产生的动态代理对象在spring的容器中自动注册,bean的id就是mapper类名(首字母小写)-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定扫描包的路径,就是mapper接口的路径,多个包中间以 半角逗号隔开   -->
        <property name="basePackage" value="com.yueluo.dao"/>
        <!-- 配置sqlSessionFactoryBeanName -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
</beans>

2.打开UserMapper  ,因为spring的标签,先在UserMapper类上加一个@Repository标签,表明它是数据访问组件,即DAO组件

鼠标点在UserMapper后面,Alt + Enter 然后选择Create Test

点击OK,创建测试类

3. 编辑测试类

UserMapperTest

package com.yueluo.dao;

import com.yueluo.model.User;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.junit.Assert.*;

public class UserMapperTest {

    private ApplicationContext applicationContext;

    @Autowired
    private UserMapper userMapper;

    @Before
    public void setUp() throws Exception {
        // 加载spring配置文件
        applicationContext = new ClassPathXmlApplicationContext("classpath:/spring/applicationContext.xml");
        // 导入测试的Mapper
        userMapper = applicationContext.getBean(UserMapper.class);
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testinsert() throws Exception {
        User user = new User();
        user.setUsername("yueluo");
        user.setPassword("12345678");
        int result = userMapper.insert(user);
        System.out.println(result);
        assert (result == 1);
    }
}

点击testinsert()类左侧的小绿三角,run一下这个测试类,输出结果为1 则测试成功!!

打开数据库,查看user表~~~

 

五、配置SpringMVC(配置显示层相关文件)

1.在spring文件夹下新建spring-mvc.xml

spring-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:beans="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-4.3.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">


    <!-- ①:top.xiaofeng包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
    <context:component-scan base-package="com.yueluo.controller"/>
    <!-- 开启SpringMVC注解模式 -->
    <mvc:annotation-driven/>
    <!-- 静态资源默认servlet配置 -->
    <mvc:default-servlet-handler/>

    <!-- 静态资源访问 -->
    <!--如果webapp下你新建了文件夹,想访问里面的静态资源,那么就要在这配置一下-->
    <mvc:resources location="/img/" mapping="/img/**"/>
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>

    <!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter"/>
            </list>
        </property>
    </bean>

    <bean id="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!-- 配置视图解析器,把控制器的逻辑视频映射为真正的视图 -->
    <!-- /WEB-INF/views/second.jsp -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 拦截器 -->
    <mvc:interceptors>
        <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
    </mvc:interceptors>

    <!-- 定义无Controller的path<->view直接映射 -->
    <!-- <mvc:view-controller path="/" view-name="redirect:/" /> -->
</beans>

2.点击File —— Project Struture 选择Moudules —— Spring 点击上面的加号,然后勾选刚配置的xml文件,点击OK

3.编辑webapp/WEB-INF/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">
  <display-name>helloworld</display-name>
  <!-- 配置编码方式-->
  <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>


  <!-- 配置springmvc的前端控制器 指向spring-mvc.xml 程序在启动的时候就加载springmvc 可以接受所有请求
  load-on-startup:表示启动容器时初始化该Servlet; -->
  <servlet>
    <servlet-name>springServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 可以自定义servlet.xml配置文件的位置和名称,
    默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!-- 将前端URL请求和后台处理方法controller建立对应关系-->
  <servlet-mapping>
    <servlet-name>springServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- 取消对某一类文件的拦截-->
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/static/*</url-pattern>
  </servlet-mapping>

  <!-- Spring配置 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext.xml</param-value>
  </context-param>

  <!-- 欢迎页面-->
  <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
  </welcome-file-list>

  <!--设置session失效时间为30分钟 -->
  <session-config>
    <session-timeout>600</session-timeout>
  </session-config>
</web-app>

4.点击上面工具栏中的Edit Configrations...   (可能在界面右上角,如果没有工具栏  可以点击View —— Toolbar 调出  )

点击左上角的加号,找到Tomcat Server 选择Local(如果没有,可以点击下面的items more找到)

Server页配置没问题的话点击 Deployement,点击右侧加号,选择Artigact...  

选择Testssm:war exploded (这个貌似是以源文件形式上传tomcat,选择上面的则是打包)然后OK~~~OK~~~

配置好之后点击旁边的小三角  Run Tomcat

会自动弹出index.jsp页面!!!!哇喔~~~好激动~~~

到这里项目已经部署到服务器上了,接下来就是前端页面(views)以及后端的逻辑控制(controller)之间的编写喽~~~

六、测试SSM框架

1.编写首页index.jsp

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: ry03
  Date: 11/29/18
  Time: 4:35 PM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
</head>
<body>
<form id="report" action="user/pwd" method="post">
    用户ID<input type="text" id=“userid” name="userid"/>
    <input type="submit" value="查询密码"/>
</form>
</body>
</html>

2.编写跳转后的页面second.jsp

second.jsp

<%--
  Created by IntelliJ IDEA.
  User: ry03
  Date: 11/29/18
  Time: 6:58 PM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>跳转成功</title>
</head>
<body>
用户名:${username}
密码:${password}
</body>
</html>

3.编写UserController

package com.yueluo.controller;

import com.yueluo.dao.UserMapper;
import com.yueluo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value = "/pwd", method = RequestMethod.POST)
    public String pwdTest(@RequestParam("userid") int userid , Model model){
        User user = userMapper.selectByPrimaryKey(userid);
        model.addAttribute("username" , user.getUsername());
        model.addAttribute("password" , user.getPassword());
        return "second";
    }
}

写好的目录结构如下:

4.重新部署一下项目:

5.输入用户ID,点击查询

6.跳转到结果页面~~~

至此,SSM框架搭建完毕!!!

 

原文纯手打,肯定会有很多不足之处,欢迎补充纠错~~~

最后,再次感谢头头哥以及hacyo提供的技术文档!!!

参考博客:

https://www.cnblogs.com/hackyo/p/6646051.html

https://blog.csdn.net/dwhdome/article/details/83380149

https://www.cnblogs.com/toutou/p/ssm_spring.html

https://www.cnblogs.com/toutou/p/ssm_springmvc.html

 

 

 

 

 

 

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值