首页  »   VC/MFC

SpringMVC+Spring+mybatis+maven+tomcat+restful项目创设详细

网友分享于:2018-04-03  浏览:2次
SpringMVC+Spring+mybatis+maven+tomcat+restful项目创建详细


 Idea SpringMVC+Spring+mybatis+maven+tomcat+restful
项目创建详细

[参考:Idea SpringMVC+Spring+MyBatis+Maven+Tomcat调整

http://blog.csdn.net/qq_35116967/article/details/51504558]

1.     创建项目

File-New Project

选中左侧的Maven,选中右侧上方的Create from archetype,然后选中下方列表中的webapp,然后点击Next

 

 

 

 

GroupIdArtifactId中填入指定内容,点击Next



 

直接点Next



 

 

输入项目名称,Finish

 

Idea会自动开始下载所依赖的包,等待其完成。(如果下载慢,请给maven添加mirror,见帖子https://www.cnblogs.com/xiongxx/p/6057558.html)

 

 

2.     项目结构

 



 

 

项目刚建好的时候是没有这些文件的,所以自己手动创建缺少的文件夹(包)

创建完后的项目框架:




 
 

 

3.修改pom.xml导入依赖包插件

依赖包需要如下:

spring framework
aspectj
事务
c3p0
数据源
servlet/jsp api
junit4
mybatis
mybatis spring
整合
postgresql driver

jstl

 

完整的pom.xml代码清单:

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

  <name>ssm Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <build>
    <finalName>ssm</finalName>
    <plugins>
      <!--mybatis 逆向工程插件-->
      <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>
  <properties>
    <spring.version>4.1.1.RELEASE</spring.version>
  </properties>
  <dependencies>
    <!-- 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-oxm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- springframe end -->
    <!--aspectj start-->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.6</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.8.6</version>
    </dependency>
    <!--aspectj end-->
    <!--c3p0-->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.1</version>
    </dependency>
    <!--servlet/jsp api start-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
      <scope>provided</scope>
    </dependency>
    <!--servlet/jsp api end-->
    <!--junit4-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>
    <!--mybatis spring整合-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
    <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <version>42.2.1</version>
    </dependency>
    <!--jstl-->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
  </dependencies>
</project>

 

 

4.     使用mybatis逆向工程创建mapper接口和xml文件

students表结构(首先在postgresql库中创建名字叫ssmdatabase库,可以生成.sql文件将下面的代码复制进去,通过在这个库下导入sql文件建students表,或者直接在ssm库下的窗口里粘贴创建students)

 

CREATE TABLE "public"."students" (
"sid" int4 NOT NULL,
"sname" varchar(255) COLLATE "default",
"gender" varchar(255) COLLATE "default",
"birthday" date,
"address" varchar(255) COLLATE "default",
CONSTRAINT "students_pkey" PRIMARY KEY ("sid")
)
WITH (OIDS=FALSE)
;
ALTER TABLE "public"."students" OWNER TO "postgres";
 

 

 

建成的表如下所示:



 

 

 

5.     main/resources中创建generatorConfig.xml文件



 

generatorConfig.xml代码清单

 

<?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>
    <!--此处需要在本地有mysql连接所需jar包,写自己的jar包路径-->
    <classPathEntry location="D:\softwares\数据库工具\postgresql\jar\postgresql-9.1-901-1.jdbc4.jar"/>
    <context id="testTables" targetRuntime="MyBatis3" >
    <commentGenerator>
        <!-- 是否去除自动生成的注释 true:是 : false:否 -->
        <property name="suppressAllComments" value="true" />
    </commentGenerator>
    <!--</jdbcConnection> 修改成自己的用户密码-->
        <jdbcConnection driverClass="org.postgresql.Driver"
                        connectionURL="jdbc:postgresql://127.0.0.1:5432/cz?characterEncoding=UTF-8"
                        userId="postgres"
                        password="******">
        </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.elin4it.ssm.pojo"
                            targetProject="src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.elin4it.ssm.mapper"
                         targetProject="src\main\resources">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.elin4it.ssm.mapper"
                             targetProject="src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- 指定数据库表 -->
        <table tableName="students"></table>
        <!-- 有些表的字段需要指定java类型
         <table schema="" tableName="">
            <columnOverride column="" javaType="" />
        </table> -->
    </context>
</generatorConfiguration>

 

 

点击idea右侧的maven选项卡,选择其中的mybatis-generator,点击顶部的绿色按钮运行



 

 

如果没有出错的话,应该会自动生成mapper接口文件、xml文件、pojo文件。

      

 

 

resources/config中创建jdbc.properties,该文件用来描述mysql连接信息

jdbc.driver = org.postgresql.Driver
jdbc.url = jdbc:postgresql://127.0.0.1:5432/cz?characterEncoding=UTF-8
jdbc.username = postgres
jdbc.password = ******

6.     Mybatis-config文件

resources/config/mybatis中创建mybatis-config.xml文件,该文件为Mybatis的配置文件,由于跟spring整合,所以一些基础配置文件都在spring中,在这里该文件中值需要写文件的框架,此处是系统自动生成的代码(mybatis文件夹右键->new->mybatis-config):

<?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>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="true"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="3000"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>
    </settings>
    <!-- Continue going here -->
</configuration>

 

 

7.     SpringMVC配置文件

resources/config/spring中创建springmvc.xml文件    

 

<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.elin4it.ssm"/>
    <!--视图渲染-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--控制器映射器和控制器适配器-->
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>
 

 

8.     Spring IOC注入和事件控制

resources/config/spring中创建applicationContext-dao.xmlapplication-service.xmlapplicationContext-transaction.xml文件

 

applicationContext-dao.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"
       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">

    <!--获取数据库配置文件-->
    <context:property-placeholder location="classpath:config/jdbc.properties"/>
    <!--设置数据源c3p0-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxPoolSize" value="50"/>
        <property name="minPoolSize" value="2"/>
        <property name="maxIdleTime" value="60"/>
    </bean>
    <!--sqlsessionFactory bean-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:config/mybatis/mybatis-config.xml"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--自动扫描mapper接口,并注入sqlsession-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.elin4it.ssm.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSession"/>
    </bean>

</beans> 

application-service.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"
       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">

    <!--扫描service-->
    <context:component-scan base-package="com.elin4it.ssm.service"/>
</beans>  
applicationContext-transaction.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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">


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

    <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
        <tx:attributes>
            <tx:method name="find*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="add*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.elinzhou.ixxs.service.*.*(..))"/>
    </aop:config>
</beans>

 


9.     web.xml文件

修改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>
  <!--设置spring 配置文件的位置-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:config/spring/applicationContext-*.xml</param-value>
  </context-param>
  <!--解决POST乱码问题-->
  <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>
  <!--配置spring listener-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--springmvc前端控制器配置-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:config/spring/springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

10.     Service接口与实现

创建一个简单的service,只有一个查看所有用户列表的功能

UserService.java

 

package com.elin4it.ssm.service;

import com.elin4it.ssm.pojo.Students;
/**
 * Created by lgs on 2015/7/11.
 */
public interface UserService {
    /**
     * 查找所有用户
     * @return
     * @throws Exception
     */
    Students findUser()throws Exception;
}  

实现类UserServiceImpl.java

 

 

package com.elin4it.ssm.service;

import com.elin4it.ssm.mapper.StudentsMapper;
import com.elin4it.ssm.pojo.Students;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * Created by lgs on 2015/7/11. 
 */
@Service
public class UserServiceImpl implements UserService {
    //User接口 此处注入UserMapper时需要在UserMapper接口上添加<span style="font-family: Arial, Helvetica, sans-serif;">@Component进行依赖注入</span>  
    @Autowired
    private StudentsMapper userMapper;
    public Students findUser() throws Exception {
        //调用mapper类中的selectByExample方法,如果传入类型为null,则表示无条件查找  
        Students users = userMapper.selectByPrimaryKey(2);
        return users;
    }
}  

11.     Controller

UserController.java代码:
package com.elin4it.ssm.controller;

import com.elin4it.ssm.pojo.Students;
import com.elin4it.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Administrator on 2018/3/13.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    //service类
    @Autowired
    private UserService userService;

    /**
     * 查找所用用户控制器方法
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/findUser")
    public Students getStudents()throws Exception{
        Students students = userService.findUser();
        return students;
    }
}

12.     配置tomcat

打开面板 Run -- Edit Configurations,点+号,选择 Tomcat server --> Local -->输入tomcat名称和配置信息后,点击“Deployment”标签页,点击下面的+号,在弹出的列表中选择“Artifact”, 弹出提示框选择要deploymentproject  

编辑 Application context的名称,点击OK就可完成Tomcat配置。

点击下面的绿色箭头或右上角的tomcat启动箭头,即可启动tomcat部署的project  

启动后会自动跳转到浏览器可以通过http://localhost:8080//user/findUser访问跑起来!

 

启动后出现错误:

 

 


13.     解决方法:配置json转换器

pom.xml添加依赖:


 

<!--json-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.8.5</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.5</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.8.5</version>
</dependency>

输出结果如下:

 

14.     日期格式需要修正

解决:在springmvc.xml中添加

<mvc:annotation-driven>  
    <!-- 处理responseBody 里面日期类型 -->  
        <mvc:message-converters>  
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
                <property name="objectMapper">  
                    <bean class="com.fasterxml.jackson.databind.ObjectMapper">  
                        <property name="dateFormat">  
                            <bean class="java.text.SimpleDateFormat">  
                                <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />  
                            </bean>  
                        </property>  
                    </bean>  
                </property>  
            </bean>  
        </mvc:message-converters>  
    </mvc:annotation-driven>

 


输出结果如下:




 
15.     mybatis 打印sql

 

mybatis.cfg.xml中增加如下配置

 

 

<settings>中增加

 

<setting name="logImpl" value="STDOUT_LOGGING" />

 

可在控制台查看效果:

 

 

【完】

相关解决方案

最新解决方案