一个简单的ssm项目

 

准备说明
jdk、tomcat、idea、mave配置请看我前两篇,这里说下mysql以及我的mysql图像化工具

 




数据库

 



项目概览

 

 

 

 

项目构建
--------搭建一个简单的mave的web项目,构建步骤如下--------
http://www.cnblogs.com/flyins/p/7617078.html

 

--------配置文件--------

该项目需要以来的jar和plugins如下,也就是pom.xml。maven下载完成后,你可以点击Maven Projects中看到

<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.dsh</groupId>
  <artifactId>Demo</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Demo Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <!-- 统一管理版本号 -->
  <properties>
    <junit.version>4.12</junit.version>
    <spring.version>4.1.3.RELEASE</spring.version>
    <mybatis.version>3.2.8</mybatis.version>
    <mybatis.spring.version>1.2.2</mybatis.spring.version>
    <mybatis.paginator.version>1.2.15</mybatis.paginator.version>
    <mysql.version>5.1.32</mysql.version>
    <slf4j.version>1.6.4</slf4j.version>
    <jackson.version>2.4.2</jackson.version>
    <druid.version>1.0.9</druid.version>
    <httpclient.version>4.3.5</httpclient.version>
    <jstl.version>1.2</jstl.version>
    <servlet-api.version>2.5</servlet-api.version>
    <jsp-api.version>2.0</jsp-api.version>
    <joda-time.version>2.5</joda-time.version>
    <commons-lang3.version>3.3.2</commons-lang3.version>
    <commons-io.version>1.3.2</commons-io.version>
    <commons-net.version>3.3</commons-net.version>
    <pagehelper.version>3.4.2-fix</pagehelper.version>
    <jsqlparser.version>0.9.1</jsqlparser.version>
    <commons-fileupload.version>1.3.1</commons-fileupload.version>
    <jedis.version>2.7.2</jedis.version>
    <solrj.version>4.10.3</solrj.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- Jackson Json处理工具包(springmvc的注解@ResponseBody需要此包) -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <!-- 单元测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <!-- 日志处理 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <!-- Mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis.spring.version}</version>
    </dependency>
    <dependency>
      <groupId>com.github.miemiedev</groupId>
      <artifactId>mybatis-paginator</artifactId>
      <version>${mybatis.paginator.version}</version>
    </dependency>
    <!-- MySql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!-- 连接池 -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <!-- Spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</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-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- JSP相关 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>${servlet-api.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>${jsp-api.version}</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>Demo</finalName>
    <!-- maven所需依赖。 -->
    <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>
    <!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>
</project>
View Code

resources下,粘贴下如下配置文件
spring配置文件applicationContext.xml。主要是用于ioc式创建对象和aop式管理事务。
这里主要是用到了提供数据源对象

<?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-4.0.xsd

        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- 1. 数据源 : DriverManagerDataSource -->
    <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/test" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <!--
        2. mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源

        MyBatis定义数据源,同意加载配置
    -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml" />
    </bean>

    <!--
        3. mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory

        basePackage:指定sql映射文件/接口所在的包(自动扫描)
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.isd.dao"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

    <!--
        4. 事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源
    -->
    <!-- <bean id="txManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean> -->
 <!--
    5. 使用声明式事务
         transaction-manager:引用上面定义的事务管理器-->
    
    <!-- <tx:annotation-driven transaction-manager="txManager" /> -->
</beans>
View Code

 

mybatis配置文件mybatis-config.xml
仅仅只有几行配置,因为项目中使用的 sping和mybatis 实现的,那么其他的配置是否就由spring完成了
仔细想一下就知道结果了,使用spring当然会用到的就是spring配置数据源datasource了。那么mybatis-config.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>
    <settings>
        <setting name="cacheEnabled" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="multipleResultSetsEnabled" value="true"/>
        <setting name="useColumnLabel" value="true"/>
        <setting name="useGeneratedKeys" value="true"/>
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <setting name="defaultStatementTimeout" value="25000"/>
        <setting name="logImpl" value="STDOUT_LOGGING" /> 
    </settings>

    <!-- 实体类,简称 -设置别名 -->
    <typeAliases>
        <typeAlias alias="Student" type="com.isd.model.Student" />
    </typeAliases>
    <!-- 实体接口映射资源 -->
    <!--
            说明:如果xxMapper.xml配置文件放在和xxMapper.java统一目录下,mappers也可以省略,因为org.mybatis.spring.mapper.MapperFactoryBean默认会去查找与xxMapper.java相同目录和名称的xxMapper.xml
    -->
    <mappers> </mappers>

</configuration>
View Code

 

Log4j,配置文件log4j.properties
通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件、甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等

# Direct log messages to console
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=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
 
# Root logger option
log4j.rootLogger=debug,console
View Code

 

配置web.xml,springmvc的配置文件dispatcher-servlet.xml
dispatcher-servlet.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">

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

    <!-- 静态资源的访问 -->
    <mvc:resources  mapping="/**/*.html" location="/"/>
    <mvc:resources mapping="/**/*.js" location="/"/>
    <!--<mvc:resources mapping="/css/**" location="/css/"/>-->
    <!--<mvc:resources mapping="/images/**" location="/images/"/>-->
    <!--<mvc:resources mapping="/static/**" location="/static/"/>-->

    <!-- 开启注解 -->
    <mvc:annotation-driven/>


    <!--ViewResolver 视图解析器-->
    <!--用于支持Servlet、JSP视图解析-->
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
View Code

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  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_2_5.xsd" version="2.5">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>CharacterEncodingFilter</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>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>
View Code

 

 


---------使用mybatis.generator逆向工程生成model和dao层--------
配置文件generatorConfig.xml
注意的是:先新建一个在src下java目录,然后转成sources类型,不然不会被编译,方法参考http://www.cnblogs.com/flyins/p/7617835.html

<?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>
    <classPathEntry
            location="C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\5.1.32\mysql-connector-java-5.1.32.jar" />
    <context id="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="false" />
        </commentGenerator>
        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test" userId="root"
                        password="root">
        </jdbcConnection>

        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成PO类的位置 -->
        <javaModelGenerator targetPackage="com.isd.model" targetProject="C:\Users\Administrator\IdeaProjects\Demo\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="false" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.isd.dao" targetProject="C:\Users\Administrator\IdeaProjects\Demo\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.isd.dao" targetProject="C:\Users\Administrator\IdeaProjects\Demo\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>


        <!-- 指定数据库表 -->
        <table tableName="student" ></table>
    </context>
</generatorConfiguration>
View Code

 

 



---------给项目配置服务器--------
idea要求若给项目添加tomcat,则必须先配置好默认的tomcat,然后点击+号才有tomcat选项,所以先配置全局default的tomcat



然后再给项目配置tomcat服务器

 

 



 

 

 

------------------------------------------------------------------------------以上,准备工作结束,项目搭建完毕,准备自己coding吧----------------------------------------------------------------------------------------------
我要点击按钮,获取所有的student。
Dao层
那么我需要在mapper的xml和java文件中新增此方法:
StudentMapper.xml

<select id="selectAllSudent" resultMap="BaseResultMap"  >
        select
        <include refid="Base_Column_List" />
        from student
</select>

StudentMapper.java

List<Student> selectAllSudent();

 

service层
接口StudentService

package com.isd.service;

import com.isd.model.Student;

import java.util.List;
public interface StudentService {
    List<Student> getAllStudent();
}

实现StudentServiceImp

package com.isd.service.imp;
import com.isd.dao.StudentMapper;
import com.isd.model.Student;
import com.isd.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImp implements StudentService {
    @Autowired
    private StudentMapper studentDao;
    public List<Student> getAllStudent() {
        return studentDao.selectAllSudent();
    }
}

 

 conttroller层
StudentController

package com.isd.controller;
import com.isd.model.Student;
import com.isd.service.StudentService;
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping("getAllStudent")
    @ResponseBody
    public Map<String,Object> getAllStudent(){
        List<Student> allStudent=studentService.getAllStudent();
        Map<String,Object> result=new HashMap<String,Object>();
        result.put("status","sucess");
        result.put("data",allStudent);
        return result;
    }
}

 

 

 web

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>测试系统已经启动!!!</h1>
    <button>获取所有学生</button>
    <script src="./js/jquery-3.2.1.min.js"></script>
    <script>
        var myhost='http://localhost:8080/Demo/';
        var getAllStudent=myhost+'student/getAllStudent';

        $('button').click(function () {
            $.post(getAllStudent,function (rep) {
                console.log(rep)
            })
        })
     </script>
</body>
</html>

 

效果



 

 

 



 


总的大概来说呢
spring就是用来提供对象的,利用其ioc/di与aop贯穿于整个项目。为各个层之间提供对象创建和注入,解耦合。
比如我的这个项目提供了dao层的对象。不过service、controller都有,只不过是用来注解,在默认配置文件applicationContext.xml中感觉不出来而已

springMVC是负责controller和jsp的,也就是视图层的,其默认配置文件是dispatcher-servlet.xml

mybatis是负责数据库的连接(不用jdbc了),与spring整合后,配合spring可提供dao层对象


 

项目地址
https://gitee.com/dingshao/Demo.git

posted @ 2018-09-14 13:19  甲乙丙丁少  阅读(4708)  评论(0编辑  收藏