给萌新的SSM入门说明书(有详细源码)

使用 Spring + Spring MVC +MyBatis 搭建一个服务端

想直接看项目源码的,请移步https://gitee.com/spencercjh/shouers

欢迎大家关注我的微信公众号 spencerlife,这篇文章原本不会在这出现而仅仅是一次公众号推送,全因图文消息不能超过50000字。

第一次在微信公众号给大家写技术文章,就写最傻瓜最萌新的SSM使用教程吧。

这里只有使用方法,你可以直接复制黏贴地开始搭建自己的SSM环境,具体的实现理论我不再赘述,自己看书研究吧。但我会介绍每个文件是干什么的。


环境准备(我自己的环境)

Intelij IDEA 2018.1.1 (IDE)

Java8 1.8.0_152 (JDK)

Apache Maven 3.5.0 (Maven)

MySQL 5.7.17 (DataBase)

Tomcat 8.5 (Local Sever)

开始

1 Create New Project

New Project左侧栏中有许许多多的选择,选择绿叶图标的Spring Initializr,SDK默认JDK,Initializr Server URL默认不变start.spring.io。

单击Next。

Group是团队名称,一般命名规则都是com.公司/团队名;Artifact是项目名称。举个例子比如我最近做了一个网站后端是给上海海洋大学用的,项目名字叫shouers,所以我的Group+Artifact就是com.shou.shouers,我不建议在这里有大小写,因为当你发现包名、项目名、XX名、XX名都不一样的时候,你会疯掉的。这是我一点人生的经验。

Type里你可以选择是Maven Project还是Gradle Projcet,Maven和Gradle简单说都是管理dependency(没有这些东西我们需要下载jar包并导入)。

Language选择Java。(但你也可以了解了解Kotlin呢【安利】)

Packaging选择War包,本人才疏学浅还只会部署war包到服务器上,还并不了解jar包怎么使用。

Java Version选择8。

Version一般不改。

Name可以改成Artifact名

单击Next。

Description可以简单写写,我从来没试过在这里写中文,我建议你也别尝试

Package 就是包名,会根据Group+Artifact自动生成,你当然可以自己改,所以我所有的建议都是针对萌新,当你不知道会发生什么事情的时候,就要谨慎行事。

接下来选择Dependencies,制作一个我们是给网站/App/小程序/公众号做服务端,你要根据需要去勾选:我的项目非常简单,所以只勾了:Web、MySQL,JDBC,MyBatis。你仔细看上面会发现还要选择Spring Boot的版本,这个不用管它,我们不用Spring Boot,我们会在后面的Maven Pom文件中把项目改回我们要的样子,对熟悉自己在做什么事情的人来说,怎么创建SSM项目都行。(在New Project中选择Spring而不选择Spring Initializr,或者只创建Maven/Gradle项目自己手动添加Spring有关的配置,或者自己手写一个Spring框架【笑】)

单击Next。

Project Name,我建议你用Artifact名,到现在你应该一直都是小写它的。

Project Location,项目的物理位置。我建议你不要在C盘的User目录下,或者program files目录里放工程项目。(经常会因为C盘的写入权限或者文件系统让你头皮发麻的)

别的都不用你操心了。

单击Finish。

2 开始复制黏贴我的代码吧

我会介绍每个文件是干嘛的。

2.1 pom.xml

你会发现你刚刚的设置其实都体现在pom.xml里了,你可以在这里修改以颠覆刚刚的设置,改完了以后要import changes。


<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.shougroupId>
    <artifactId>shouersartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>warpackaging>

    <name>shouersname>
    <description>shouersdescription>

    <properties>
        
        <spring.version>4.3.3.RELEASEspring.version>
        
        <mybatis.version>3.1.1mybatis.version>
        
        <slf4j.version>1.7.7slf4j.version>
        <log4j.version>2.5log4j.version>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>
    <dependencies>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>3.8.1version>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-oxmartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aopartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>${spring.version}version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>${mybatis.version}version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.1.0version>
        dependency>
        
        <dependency>
            <groupId>javaxgroupId>
            <artifactId>javaee-apiartifactId>
            <version>7.0version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.30version>
        dependency>
        
        <dependency>
            <groupId>commons-dbcpgroupId>
            <artifactId>commons-dbcpartifactId>
            <version>1.2.2version>
        dependency>
        
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        
        
        <dependency>
            <groupId>org.apache.logging.log4jgroupId>
            <artifactId>log4j-coreartifactId>
            <version>${log4j.version}version>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.1.41version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>${slf4j.version}version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>${slf4j.version}version>
        dependency>
        
        
        <dependency>
            <groupId>org.codehaus.jacksongroupId>
            <artifactId>jackson-mapper-aslartifactId>
            <version>1.9.13version>
        dependency>
        
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.3.1version>
        dependency>
        <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.4version>
        dependency>
        <dependency>
            <groupId>commons-codecgroupId>
            <artifactId>commons-codecartifactId>
            <version>1.9version>
        dependency>

        
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-emailartifactId>
            <version>1.4version>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-messagingartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-websocketartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-expressionartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-annotationsartifactId>
            <version>2.8.1version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-coreartifactId>
            <version>2.8.1version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.8.1version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.1.0version>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>com.google.code.gsongroupId>
            <artifactId>gsonartifactId>
            <version>2.6.2version>
        dependency>
        <dependency>
            <groupId>net.sf.json-libgroupId>
            <artifactId>json-libartifactId>
            <version>2.4version>
            <classifier>jdk15classifier>
            <scope>compilescope>
        dependency>

        <dependency>
            <groupId>org.apache.httpcomponentsgroupId>
            <artifactId>httpcoreartifactId>
            <version>4.4version>
        dependency>

        
        <dependency>
            <groupId>org.apache.httpcomponentsgroupId>
            <artifactId>httpclientartifactId>
            <version>4.5.3version>
        dependency>


        <dependency>
            <groupId>org.jsoupgroupId>
            <artifactId>jsoupartifactId>
            <version>1.8.3version>
        dependency>

        
        <dependency>
            <groupId>org.jsongroupId>
            <artifactId>jsonartifactId>
            <version>20171018version>
        dependency>

        

        <dependency>
            <groupId>io.jsonwebtokengroupId>
            <artifactId>jjwtartifactId>
            <version>0.9.0version>
        dependency>

        
        
        <dependency>
            <groupId>com.google.zxinggroupId>
            <artifactId>coreartifactId>
            <version>3.3.0version>
        dependency>
        
        <dependency>
            <groupId>com.google.zxinggroupId>
            <artifactId>javaseartifactId>
            <version>3.3.0version>
        dependency>
        <dependency>
            <groupId>dom4jgroupId>
            <artifactId>dom4jartifactId>
            <version>1.6.1version>
        dependency>
        <dependency>
            <groupId>com.thoughtworks.xstreamgroupId>
            <artifactId>xstreamartifactId>
            <version>1.3.1version>
        dependency>
    dependencies>
    <build>
        
        <resources>
            <resource>
                <directory>${basedir}/src/main/javadirectory>
                <includes>
                    <include>**/*.xmlinclude>
                includes>
            resource>
        resources>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-pluginartifactId>
                <version>2.9version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnatureprojectnature>
                    additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilderbuildcommand>
                    additionalBuildcommands>
                    <downloadSources>truedownloadSources>
                    <downloadJavadocs>truedownloadJavadocs>
                configuration>
            plugin>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>2.5.1version>
                <configuration>
                    <source>1.6source>
                    <target>1.6target>
                    <compilerArgument>-Xlint:allcompilerArgument>
                    <showWarnings>trueshowWarnings>
                    <showDeprecation>trueshowDeprecation>
                configuration>
            plugin>
            <plugin>
                <groupId>org.codehaus.mojogroupId>
                <artifactId>exec-maven-pluginartifactId>
                <version>1.2.1version>
                <configuration>
                    <mainClass>org.test.int1.MainmainClass>
                configuration>
            plugin>
            
            <plugin>
                <groupId>org.mybatis.generatorgroupId>
                <artifactId>mybatis-generator-maven-pluginartifactId>
                <version>1.3.2version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generatorConfig.xmlconfigurationFile>
                    <overwrite>trueoverwrite>
                    <verbose>trueverbose>
                configuration>
            plugin>
        plugins>
    build>
project>

2.2 webapp/*(eclipse里默认叫这个名,idea都不会默认创建)

在src中New->Directory,取名webapp。

打开Project Structure,在左边Modules中看有没有Web,没有就添加。

在Web Resources Directories中添加webapp这个路径。

在webapp中添加文件夹(根据你的开发习惯),我添加了resources,static,WEB-INF;在static中再添加css,js,images;在WEB-INF中添加jsp,和web.xml

2.2.1 webapp/WEB-INF/web.xml

做过JSP+Servlet+JavaBean等其他Java Web的人都知道这个web.xml是干嘛的。


<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Archetype Created Web Applicationdisplay-name>
    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:spring-mybatis.xmlparam-value>
    context-param>
    
    <filter>
        <filter-name>encodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <async-supported>trueasync-supported>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
    listener>

    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>/static/*url-pattern>
    servlet-mapping>


    

    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.txturl-pattern>
    servlet-mapping>

    <error-page>
        <error-code>404error-code>
        <location>/index.jsplocation>
    error-page>
    
    <servlet>
        <servlet-name>SpringMVCservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring-mvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
        <async-supported>trueasync-supported>
    servlet>
    <servlet>
        <description>
        description>
        <display-name>FileUploadServletdisplay-name>
        <servlet-name>FileUploadServletservlet-name>
        <servlet-class>ttaiweb.controller.FileUploadServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>SpringMVCservlet-name>
        
        <url-pattern>/url-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>FileUploadServletservlet-name>
        <url-pattern>/FileUploadServleturl-pattern>
    servlet-mapping>
    <welcome-file-list>
        <welcome-file>/index.jspwelcome-file>
    welcome-file-list>
    
    <session-config>
        <session-timeout>15session-timeout>
    session-config>
web-app>

你会发现这里面有些代码指向的类,文件,目录都不存在,但我想告诉你做服务端的时候Error并不会影响什么(除非不让你run了)

2.3 src/resouces/*

你可以把里面原来的东西全部删掉。

2.3.1 eneratorConfig.xml

SSM中dao,model,mapping都是靠这个生成出来的,具体怎么操作去生成后面会介绍。




<generatorConfiguration>
    
    <classPathEntry
            location="D:\spencercjh\programe\JAR\mysql-connector-java-5.1.44\mysql-connector-java-5.1.44-bin.jar"/>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            
            <property name="suppressAllComments" value="true"/>
        commentGenerator>
        
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://{远程/本地服务器IP}:3306/shouers"
                        userId="用户名"
                        password="密码">
        jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        javaTypeResolver>
        
        <javaModelGenerator targetPackage="com.shou.shouers.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        javaModelGenerator>
        
        <sqlMapGenerator targetPackage="com.shou.shouers.mapping" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        sqlMapGenerator>
        
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.shou.shouers.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        javaClientGenerator>
        
        <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">table>
        <table tableName="admin" domainObjectName="Admin" enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">table>
        <table tableName="activityinfo" domainObjectName="Activityinfo" enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">table>
        <table tableName="enroll" domainObjectName="Enroll" enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">table>
    context>
generatorConfiguration>

2.3.2 jdbc.properties

这个文件是给mybatis的配置文件看的

driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://{本地/远程服务器IP}:3306/shouers?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=用户名
password=密码
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000

2.3.3 log4j.properties

这个文件是维护日志的,对大规模的服务端来说,日志是很重要的。

#定义LOG输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n

#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/shouers.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n




log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.com.pro.mapper = DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

2.3.4 spring-mvc.xml

这是Spring MVC的配置文件,你需要修改里面的包名,我建议你用ctrl-F,ctrl-R来做这些事情。


<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-3.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    
    <context:component-scan base-package="com.shou.shouers.controller" />
    
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8value>
            list>
        property>
    bean>

    <mvc:annotation-driven/>
    
    
    <mvc:resources mapping="/static/**" location="/static/" />
    <mvc:resources mapping="/doc/**" location="/static/doc/"/>

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

    
    <bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="utf-8" />  
        
        <property name="maxUploadSize" value="10485760000" />  
        
        <property name="maxInMemorySize" value="40960" />  
    bean> 

beans>

2.3.5 spring-mybatis.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:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    
    <context:component-scan
        base-package="com.shou.shouers.*" />
    
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    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="${initialSize}">property>
        
        <property name="maxActive" value="${maxActive}">property>
        
        <property name="maxIdle" value="${maxIdle}">property>
        
        <property name="minIdle" value="${minIdle}">property>
        
        <property name="maxWait" value="${maxWait}">property>
    bean>

    
    <bean id="sqlSessionFactory"
        class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        
        <property name="mapperLocations"
            value="classpath:com/shou/shouers/mapping/*.xml">property>
    bean>

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

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

beans>

2.4 java

你应该知道SSM有以下文件结构:controller,dao,model,mapping,model,service,serviceimpl,一般的工程还会有util(工具包),common等等。建好文件目录后你还要把默认存在的Spring Boot的启动类删掉

2.4.1 使用mybatis-generator:generate

在IDEA中你不new一种运行项目的方式的话默认是不能运行的。

在这之前你应该先建好数据库了!

添加Maven运行方式。

Name随便取。

Command line里填写如下指令mybatis-generator:generate -e

具体怎么生成,都写在generatorConfig.xml中了。

运行。

你会发现dao、mapping、model中有东西了。

如果数据库被修改了,这些文件应该都会跟着变动,这个时候你要先把它们都删了,再生成一次,而不是直接运行生成插件!

2.4.2 编写service和serviceimpl

这里就举一个完整的例子:(这个例子中我已经扩充过一些SQL操作,并不是刚生成后的)

2.4.2.1 UserMapper .java
package com.shou.shouers.dao;

import com.shou.shouers.model.User;
import com.shou.shouers.model.UserKey;

import java.util.List;

/**
 * @author spencercjh
 * @version V2.0
 * @date 2018年8月2日08:47:38
 */
public interface UserMapper {
    /**
     * 查找所有的用户对象
     *
     * @return 含有所有用户对象的列表
     */
    List selectAll();

    /**
     * 通过主键删除用户信息
     *
     * @param key 用户主键对象
     * @return 删除数量
     */
    int deleteByPrimaryKey(UserKey key);

    /**
     * 插入管理员记录
     *
     * @param record 用户对象
     * @return 插入数量
     */
    int insert(User record);

    /**
     * 插入管理员记录
     *
     * @param record 用户对象
     * @return 插入数量
     */
    int insertSelective(User record);

    /**
     * 根据主键查找用户
     *
     * @param key 用户主键对象
     * @return 用户对象
     */
    User selectByPrimaryKey(UserKey key);

    /**
     * 根据主键选择性地修改用户记录(只修改不为空的属性)
     *
     * @param record 用户对象
     * @return 更新数量
     */
    int updateByPrimaryKeySelective(User record);

    /**
     * 根据主键更新用户记录(直接覆盖)
     *
     * @param record 用户对象
     * @return 更新数量
     */
    int updateByPrimaryKey(User record);
}
2.4.2.2 UserMapper.xml



<mapper namespace="com.shou.shouers.dao.UserMapper">
    <resultMap id="BaseResultMap" type="com.shou.shouers.model.User">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <id column="userid" property="userid" jdbcType="VARCHAR"/>
        <result column="password" property="password" jdbcType="VARCHAR"/>
        <result column="username" property="username" jdbcType="VARCHAR"/>
        <result column="sex" property="sex" jdbcType="INTEGER"/>
        <result column="volunteer" property="volunteer" jdbcType="INTEGER"/>
        <result column="telephone" property="telephone" jdbcType="VARCHAR"/>
        <result column="openid" property="openid" jdbcType="VARCHAR"/>
        <result column="idcard" property="idcard" jdbcType="VARCHAR"/>
        <result column="shvolunteer" property="shvolunteer" jdbcType="VARCHAR"/>
        <result column="createtime" property="createtime" jdbcType="TIMESTAMP"/>
        <result column="createuser" property="createuser" jdbcType="VARCHAR"/>
        <result column="updatetime" property="updatetime" jdbcType="TIMESTAMP"/>
        <result column="updateuser" property="updateuser" jdbcType="VARCHAR"/>
    resultMap>
    <sql id="Base_Column_List">
    id, userid, password, username, sex, volunteer, telephone, openid, idcard, shvolunteer, 
    createtime, createuser, updatetime, updateuser
  sql>
    <select id="selectAll" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from `user`
    select>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="com.shou.shouers.model.UserKey">
        select
        <include refid="Base_Column_List"/>
        from `user`
        where id = #{id,jdbcType=INTEGER}
        and userid = #{userid,jdbcType=VARCHAR}
    select>
    <delete id="deleteByPrimaryKey" parameterType="com.shou.shouers.model.UserKey">
    delete from `user`
    where id = #{id,jdbcType=INTEGER}
      and userid = #{userid,jdbcType=VARCHAR}
  delete>
    <insert id="insert" parameterType="com.shou.shouers.model.User">
    insert into `user` (id, userid, password,
      username, sex, volunteer, 
      telephone, openid, idcard, 
      shvolunteer, createtime, createuser, 
      updatetime, updateuser)
    values (#{id,jdbcType=INTEGER}, #{userid,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{username,jdbcType=VARCHAR}, #{sex,jdbcType=INTEGER}, #{volunteer,jdbcType=INTEGER}, 
      #{telephone,jdbcType=VARCHAR}, #{openid,jdbcType=VARCHAR}, #{idcard,jdbcType=VARCHAR}, 
      #{shvolunteer,jdbcType=VARCHAR}, #{createtime,jdbcType=TIMESTAMP}, #{createuser,jdbcType=VARCHAR}, 
      #{updatetime,jdbcType=TIMESTAMP}, #{updateuser,jdbcType=VARCHAR})
  insert>
    <insert id="insertSelective" parameterType="com.shou.shouers.model.User">
        insert into `user`
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            if>
            <if test="userid != null">
                userid,
            if>
            <if test="password != null">
                password,
            if>
            <if test="username != null">
                username,
            if>
            <if test="sex != null">
                sex,
            if>
            <if test="volunteer != null">
                volunteer,
            if>
            <if test="telephone != null">
                telephone,
            if>
            <if test="openid != null">
                openid,
            if>
            <if test="idcard != null">
                idcard,
            if>
            <if test="shvolunteer != null">
                shvolunteer,
            if>
            <if test="createtime != null">
                createtime,
            if>
            <if test="createuser != null">
                createuser,
            if>
            <if test="updatetime != null">
                updatetime,
            if>
            <if test="updateuser != null">
                updateuser,
            if>
        trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=INTEGER},
            if>
            <if test="userid != null">
                #{userid,jdbcType=VARCHAR},
            if>
            <if test="password != null">
                #{password,jdbcType=VARCHAR},
            if>
            <if test="username != null">
                #{username,jdbcType=VARCHAR},
            if>
            <if test="sex != null">
                #{sex,jdbcType=INTEGER},
            if>
            <if test="volunteer != null">
                #{volunteer,jdbcType=INTEGER},
            if>
            <if test="telephone != null">
                #{telephone,jdbcType=VARCHAR},
            if>
            <if test="openid != null">
                #{openid,jdbcType=VARCHAR},
            if>
            <if test="idcard != null">
                #{idcard,jdbcType=VARCHAR},
            if>
            <if test="shvolunteer != null">
                #{shvolunteer,jdbcType=VARCHAR},
            if>
            <if test="createtime != null">
                #{createtime,jdbcType=TIMESTAMP},
            if>
            <if test="createuser != null">
                #{createuser,jdbcType=VARCHAR},
            if>
            <if test="updatetime != null">
                #{updatetime,jdbcType=TIMESTAMP},
            if>
            <if test="updateuser != null">
                #{updateuser,jdbcType=VARCHAR},
            if>
        trim>
    insert>
    <update id="updateByPrimaryKeySelective" parameterType="com.shou.shouers.model.User">
        update `user`
        <set>
            <if test="password != null">
                password = #{password,jdbcType=VARCHAR},
            if>
            <if test="username != null">
                username = #{username,jdbcType=VARCHAR},
            if>
            <if test="sex != null">
                sex = #{sex,jdbcType=INTEGER},
            if>
            <if test="volunteer != null">
                volunteer = #{volunteer,jdbcType=INTEGER},
            if>
            <if test="telephone != null">
                telephone = #{telephone,jdbcType=VARCHAR},
            if>
            <if test="openid != null">
                openid = #{openid,jdbcType=VARCHAR},
            if>
            <if test="idcard != null">
                idcard = #{idcard,jdbcType=VARCHAR},
            if>
            <if test="shvolunteer != null">
                shvolunteer = #{shvolunteer,jdbcType=VARCHAR},
            if>
            <if test="createtime != null">
                createtime = #{createtime,jdbcType=TIMESTAMP},
            if>
            <if test="createuser != null">
                createuser = #{createuser,jdbcType=VARCHAR},
            if>
            <if test="updatetime != null">
                updatetime = #{updatetime,jdbcType=TIMESTAMP},
            if>
            <if test="updateuser != null">
                updateuser = #{updateuser,jdbcType=VARCHAR},
            if>
        set>
        where id = #{id,jdbcType=INTEGER}
        and userid = #{userid,jdbcType=VARCHAR}
    update>
    <update id="updateByPrimaryKey" parameterType="com.shou.shouers.model.User">
    update `user`
    set password = #{password,jdbcType=VARCHAR},
      username = #{username,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=INTEGER},
      volunteer = #{volunteer,jdbcType=INTEGER},
      telephone = #{telephone,jdbcType=VARCHAR},
      openid = #{openid,jdbcType=VARCHAR},
      idcard = #{idcard,jdbcType=VARCHAR},
      shvolunteer = #{shvolunteer,jdbcType=VARCHAR},
      createtime = #{createtime,jdbcType=TIMESTAMP},
      createuser = #{createuser,jdbcType=VARCHAR},
      updatetime = #{updatetime,jdbcType=TIMESTAMP},
      updateuser = #{updateuser,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
      and userid = #{userid,jdbcType=VARCHAR}
  update>
mapper>
2.4.2.3 User.java
package com.shou.shouers.model;

import java.util.Date;

/**
 * @author spencercjh
 * @version V1.0
 * @date 2018年8月1日23:50:19
 */
public class User extends UserKey {
    private String password;

    private String username;

    private Integer sex;

    private Integer volunteer;

    private String telephone;

    private String openid;

    private String idcard;

    private String shvolunteer;

    private Date createtime;

    private String createuser;

    private Date updatetime;

    private String updateuser;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public Integer getVolunteer() {
        return volunteer;
    }

    public void setVolunteer(Integer volunteer) {
        this.volunteer = volunteer;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone == null ? null : telephone.trim();
    }

    public String getOpenid() {
        return openid;
    }

    public void setOpenid(String openid) {
        this.openid = openid == null ? null : openid.trim();
    }

    public String getIdcard() {
        return idcard;
    }

    public void setIdcard(String idcard) {
        this.idcard = idcard == null ? null : idcard.trim();
    }

    public String getShvolunteer() {
        return shvolunteer;
    }

    public void setShvolunteer(String shvolunteer) {
        this.shvolunteer = shvolunteer == null ? null : shvolunteer.trim();
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }

    public String getCreateuser() {
        return createuser;
    }

    public void setCreateuser(String createuser) {
        this.createuser = createuser == null ? null : createuser.trim();
    }

    public Date getUpdatetime() {
        return updatetime;
    }

    public void setUpdatetime(Date updatetime) {
        this.updatetime = updatetime;
    }

    public String getUpdateuser() {
        return updateuser;
    }

    public void setUpdateuser(String updateuser) {
        this.updateuser = updateuser == null ? null : updateuser.trim();
    }
}
2.4.2.4 UserKey.java
package com.shou.shouers.model;

/**
 * @author spencercjh
 * @version V1.0
 * @date 2018年8月1日23:50:32
 */
public class UserKey {
    private Integer id;

    private String userid;

    public UserKey(String userid) {
        this.userid = userid;
    }

    public UserKey() {
    }

    public Integer getId() {
        return id;
    }

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

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid == null ? null : userid.trim();
    }
}
2.4.2.5 UserService.java
package com.shou.shouers.service;


import com.shou.shouers.model.User;
import com.shou.shouers.model.UserKey;

import java.util.List;

/**
 * @author spencercjh
 * @version V2.0
 * @date 2018年8月2日08:47:29
 */
public interface UserService {
    /**
     * 查找所有的用户对象
     *
     * @return 含有所有用户对象的列表
     */
    List selectAll();

    /**
     * 通过主键删除用户信息
     *
     * @param key 用户主键对象
     * @return 删除数量
     */
    int deleteByPrimaryKey(UserKey key);

    /**
     * 插入管理员记录
     *
     * @param record 用户对象
     * @return 插入数量
     */
    int insert(User record);

    /**
     * 插入管理员记录
     *
     * @param record 用户对象
     * @return 插入数量
     */
    int insertSelective(User record);

    /**
     * 根据主键查找用户
     *
     * @param key 用户主键对象
     * @return 用户对象
     */
    User selectByPrimaryKey(UserKey key);

    /**
     * 根据主键选择性地修改用户记录(只修改不为空的属性)
     *
     * @param record 用户对象
     * @return 更新数量
     */
    int updateByPrimaryKeySelective(User record);

    /**
     * 根据主键更新用户记录(直接覆盖)
     *
     * @param record 用户对象
     * @return 更新数量
     */
    int updateByPrimaryKey(User record);
}
2.4.2.6 UserServiceImpl.java
package com.shou.shouers.serviceimpl;


import com.shou.shouers.dao.UserMapper;
import com.shou.shouers.model.User;
import com.shou.shouers.model.UserKey;
import com.shou.shouers.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author spencercjh
 * @version V2.0
 * @date 2018年8月2日08:47:22
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }


    @Override
    public List selectAll() {
        return userMapper.selectAll();
    }

    @Override
    public int deleteByPrimaryKey(UserKey key) {
        return userMapper.deleteByPrimaryKey(key);
    }

    @Override
    public int insert(User record) {
        return userMapper.insert(record);
    }

    @Override
    public int insertSelective(User record) {
        return userMapper.insert(record);
    }

    @Override
    public User selectByPrimaryKey(UserKey key) {
        return userMapper.selectByPrimaryKey(key);
    }

    @Override
    public int updateByPrimaryKeySelective(User record) {
        return userMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(User record) {
        return userMapper.updateByPrimaryKey(record);
    }
}
2.4.2.7 user表
/*
Navicat MySQL Data Transfer

Source Server         : 我
Source Server Version : 50722
Source Host           : {本地/远程数据库IP}:3306
Source Database       : shouers

Target Server Type    : MYSQL
Target Server Version : 50722
File Encoding         : 65001

Date: 2018-08-03 11:41:07
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增编号',
  `userid` varchar(32) NOT NULL COMMENT '用户名,唯一',
  `password` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL COMMENT '用户的姓名',
  `sex` int(1) unsigned NOT NULL DEFAULT '0' COMMENT '1为女性0位男性',
  `volunteer` int(1) unsigned NOT NULL DEFAULT '0' COMMENT '1表示是志愿者0表示不是',
  `telephone` varchar(32) NOT NULL COMMENT '手机号,必填',
  `openid` varchar(64) DEFAULT NULL COMMENT '微信公众号给每一个关注用户的openid',
  `idcard` varchar(32) NOT NULL COMMENT '身份证号,必填',
  `shvolunteer` varchar(32) DEFAULT NULL COMMENT '上海志愿者平台编号,可填可不填',
  `createtime` datetime DEFAULT NULL,
  `createuser` varchar(32) DEFAULT NULL,
  `updatetime` datetime DEFAULT NULL,
  `updateuser` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`,`userid`),
  KEY `userid` (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';

-- ----------------------------
-- Records of user
-- ----------------------------

2.4.3 编写controller

controller里会负责网页的路由和接收请求接口,这里也举一个例子:(据说这里面也有争议,有些人不喜欢把大量的业务逻辑写在这里)

2.4.3.1 LoginController.java

package com.shou.shouers.controller;

import com.alibaba.fastjson.JSON;
import com.shou.shouers.model.Admin;
import com.shou.shouers.model.AdminKey;
import com.shou.shouers.model.User;
import com.shou.shouers.model.UserKey;
import com.shou.shouers.service.AdminService;
import com.shou.shouers.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 登录页面及相关API
 *
 * @author spencercjh
 * @version v3.0
 * @date 2018年8月2日15:26:55
 */
@Controller
public class LoginController {
    private final Logger logger = LoggerFactory.getLogger(LoginController.class);

    private final UserService userService;
    private final AdminService adminService;

    @Autowired
    public LoginController(UserService userService, AdminService adminService) {
        this.userService = userService;
        this.adminService = adminService;
    }

    /**
     * 登陆页面
     *
     * @return login.jsp
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        logger.info("进入登陆界面");
        return "login";
    }

    /**
     * 登陆接口
* code:200 message:登陆成功
* code:501 message:登陆signin API 参数为空
* code:502 message:登陆signin API 数字转换失败/用户用户组参数有误
* code:503 message:密码不正确
* * @param request HttpServletRequest
userid用户名 password密码 role用户组(1为管理员,0为普通用户 * @return JSON串
{{message:"错误信息/登陆成功"},
{code:200/501/502/503}} */
@RequestMapping(value = "/signin", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8") @ResponseBody public String signin(HttpServletRequest request) { ConcurrentHashMap result = new ConcurrentHashMap(); String userid; String password; String roleString; int role; try { userid = request.getParameter("userid"); password = request.getParameter("password"); roleString = request.getParameter("role"); //noinspection AlibabaUndefineMagicConstant,AlibabaUndefineMagicConstant,AlibabaUndefineMagicConstant if ("".equals(userid) || "".equals(password) || "null".equals(userid) || "null".equals(password) || "".equals(roleString) || "null".equals(roleString)) { throw new NullPointerException(); } else { logger.info("用户" + userid + "尝试登陆signin"); } } catch (NullPointerException e) { e.printStackTrace(); logger.info("登陆signin API 参数为空"); result.put("message", "登陆signin API 参数为空"); result.put("code", "501"); return JSON.toJSON(result).toString(); } try { role = Integer.parseInt(roleString); } catch (NumberFormatException e) { e.printStackTrace(); logger.info("登陆signin API 数字转换失败"); result.put("message", "登陆signin API 数字转换失败"); result.put("code", "502"); return JSON.toJSON(request).toString(); } if (role == 1) { result = adminSignin(result, userid, password); } else if (role == 0) { result = userSignin(result, userid, password); } else { logger.info("用户" + userid + "用户组参数有误"); result.put("message", "用户" + userid + "用户组参数有误"); result.put("code", "502"); } return JSON.toJSON(result).toString(); } @SuppressWarnings("Duplicates") private ConcurrentHashMap userSignin(ConcurrentHashMap result, String userid, String password) { User user = this.userService.selectByPrimaryKey(new UserKey(userid)); if (!user.getPassword().equals(password)) { result.put("message", "密码不正确"); result.put("code", "503"); } else { result.put("message", "登陆成功"); result.put("code", "200"); } return result; } @SuppressWarnings("Duplicates") private ConcurrentHashMap adminSignin(ConcurrentHashMap result, String userid, String password) { Admin admin = this.adminService.selectByPrimaryKey(new AdminKey(userid)); if (!admin.getPassword().equals(password)) { result.put("message", "密码不正确"); result.put("code", "503"); } else { result.put("message", "登陆成功"); result.put("code", "200"); } return result; } }

3 尝试运行

3.1 准备一个index.jsp

按照我的配置,被路由的网页jsp都放在webapp/WEB-INF/jsp中

3.2 写一个默认路由

3.2.1 HomeController.java

package com.shou.shouers.controller;

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

/**
 * 网站第一个页面
 *
 * @author spencercjh
 * @version V2.0
 * @date 2018年8月1日23:56:51
 */
@Controller
public class HomeController {

    private final Logger logger = LoggerFactory.getLogger(HomeController.class);

    /**
     * 网站首页
     *
     * @return index.jsp
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home() {
        logger.info("进入首页界面");
        return "index";
    }

}

3.3 添加运行方法

Run/Debug Configuration中添加Tomcat。

Name随便取。

Application Sever配置一下。

Deployment中把项目添加进来,应该是demo:war。Application context默认是“/”,也就是访问localhost:8080/就能进入,但在eclipse中默认是localhost:8080/demo。我也没研究过怎么在eclipse中改动这个。

单击OK。

Run。

3.4 可能出现的问题

我简单列举几个。

3.4.1 服务器并没有在跑项目,而是空跑

[2018-08-03 12:17:03,403] Artifact shouers:war: Artifact is being deployed, please wait...

你一定要看到这句话,否则你的服务器运行配置就没有配置好。

3.4.2 mapping,sql等字样的错误信息

你的mapping文件系统被没有找到,观察target/classes/包名/中是否有mapping文件夹和对应的xml文件,我在pom中已经加入相关插件解决了IDEA不会在编译过程中自动把mapping文件放入taget的问题。

3.4.3 not mapping found for HTTP…………

[org.springframework.web.servlet.PageNotFound] - No mapping found for HTTP request with URI [/sad] in DispatcherServlet with name 'SpringMVC'

路由写好,写对了吗?

4 总结

按照我这样配置一般不会出什么岔子的。希望你能在使用SSM的过程中理解Spring IOC容器的DI(依赖注入),Spring MVC的MVC架构,MyBatis的实现过程与原理以及和Hibernate的区别。

你可能感兴趣的:(Java,实习,SSM,Spring,Java)