idea+springmvc+spring+mybatis+maven整合返回json數據web api-


本人大三,第一次寫博客,還有許多不懂得地方,如果有不當的地方 歡迎各位指教

項目地址:https://github.com/qq571831158/Springmvc-spring-mybatisDemo

首先看一張目錄結構圖:

創建步驟:

1.創建maven  webapp工程,

創建完后的目錄結構為:

2.添加項目依賴(添加jar包)

需要的jar包:

spring-webmvc,

spring-test,

spring-orm,

commons-dbcp,

mybatis,

mybatis-spring,

mysql-connector-java,

commons-fileupload,

jstl,jackson-core,

jackson-databind,

jackson-mapper-asl,

cors-fiflter,(這個包為跨域訪問的,不是必須的,前后端分離,為了方便測試,所以加上了。)

log4j,

slf4j-log4j12

添加這些依賴到pom.xml中,可以去這個網站搜索添加到maven:http://mvnrepository.com(PS:最后會發項目鏈接,大家也可以去我項目的pom.xml里面拷貝)

3、創建數據庫:

下面是我的建表語句:

CREATE TABLE USERINFO(

`id` int NOT NULL AUTO_INCREMENT,

`username` varchar(50) NOT NULL,

`password` varchar(50) NOT NULL,

`nickname` varchar(50),

`user_picture` varchar(100),

`islogin` int,

`isactive` int,

`last_modeify` timestamp NULL,

`create_date` timestamp NULL,

`create_ip` varchar(50), 

            KEY(id),

            PRIMARY KEY(username)

);

4.配置mybatis的generator插件:

這個插件可以自動生成mybatis的mapper,model,dao

在pom.xml的 build節點下添加如下:

 <!--mybatis 自動生成dao,model,mapper,generaotr插件-->
 <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>

 

如圖所示:

然后在目錄結構下的src/main/resources中創建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>
    <!--引入配置文件-->
    <properties resource="config.properties"></properties>
    <!-- 數據庫驅動包位置 -->
    <classPathEntry location="${jdbc.driverClassLocation}"/>
    <context id="default" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!-- 數據庫鏈接URL、用戶名、密碼 -->
        <jdbcConnection
                driverClass="${jdbc.driver}"
                connectionURL="${jdbc.url}"
                userId="${jdbc.username}"
                password="${jdbc.password}">
        </jdbcConnection>

        <!-- 非必需,類型處理器,在數據庫類型和java類型之間的轉換控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- Model模型生成器,用來生成含有主鍵key的類,記錄類 以及查詢Example類
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在該項目下所在的路徑
        -->
        <javaModelGenerator targetPackage="com.ch.model"
                            targetProject="src/main/java">
            <!-- 是否允許子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="true"/>
            <!-- 是否對model添加 構造函數 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否對類CHAR類型的列的數據進行trim操作 -->
            <property name="trimStrings" value="true"/>
            <!-- 建立的Model對象是否 不可改變  即生成的Model對象不會有 setter方法,只有構造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>


        <!--Mapper映射文件生成所在的目錄 為每一個數據庫的表生成對應的SqlMap文件 -->
        <sqlMapGenerator targetPackage="com.ch.mapping"
                         targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- 生成DAO的包名和位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.ch.dao"
                             targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
        <table tableName="USERINFO" domainObjectName="Userinfo"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false"/>
    </context>
</generatorConfiguration>

在resources目錄下繼續創建config.properties;
此文件是generator.xml中用到的數據庫配置。內容如下:
#jdbc 連接對象
#mysql jar文件位置
jdbc.driverClassLocation = /Users/apple/.m2/repository/mysql/mysql-connector-java/5.1.34/mysql-connector-java-5.1.34.jar

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/ssmtest
jdbc.username = root
jdbc.password = 689571

 


接下來,點擊idea右上角的

選擇Edit Configurations,進入后,點擊左上角的➕,選擇maven

選擇后,在Name出輸入名字,任意都可以

在command line 中輸入:

mybatis-generator:generate -e

然后點擊Apply,OK.

接着,到src/main目錄下,新建一個java目錄,然后在此目錄上點擊右鍵把此目錄作Sources Root,做完后,你會發現java目錄變成了藍色,如圖:

然后,點擊右上角的綠色小三角

在看看你的java目錄下,

發現,自動生成了,mapping,model,dao的interface,致此,mybatis的文件生成完成。

5.整合spring,mybatis:

在resources目錄下創建beans.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
         http://www.springframework.org/schema/mvc 
         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context-3.0.xsd 
         http://www.springframework.org/schema/aop 
         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
         http://www.springframework.org/schema/tx 
         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
    <!--載入配置文件-->
    <context:property-placeholder location="classpath:config.properties"/>

    <!--自動掃描service-->
    <context:component-scan base-package="com.ch.service,com.ch.dao"/>

    <!--mybatis數據源,這里用的是apache的dbcp-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="testWhileIdle" value="true"/>
        <property name="testOnBorrow" value="true"/>
        <property name="testOnReturn" value="false"/>
        <property name="timeBetweenEvictionRunsMillis" value="30000"/>
        <property name="maxActive" value="30"/>
        <property name="minIdle" value="5"/>
        <property name="initialSize" value="5"/>

    </bean>

    <!--mybatis 核心類-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:spring-mybatis.xml"/>
        <!--配置mybatis映射文件mapper的位置,如果配置文件在src/main/java目錄下,maven默認不會編譯,參考我pom.xml的,build,
             當然也可以放在resources目錄下,那樣就可以訪問到-->
        <property name="mapperLocations" value="classpath*:com/ch/mapping/*.xml"/>
    </bean>

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

    <!--事物通知-->
    <tx:advice id="txAdvice" transaction-manager = "txManager">
        <tx:attributes>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="save*" propagation="REQUIRED"/>

            <tx:method name="find*" read-only="true"/>
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
</beans>

 


在創建spring-mybatis.xml,mybatis的配置文件為空,此處創建是為了留作以后擴展:
<?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>
</configuration>

至此,spring,mybatis整合完畢。

6.在java目錄下創建controller包,service包,bean包

7.整合springmvc:
在resources目錄下創建dispatcher-servlet.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"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
       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
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    <!--可掃描注解的包-->
    <mvc:annotation-driven />
    <context:component-scan base-package="com.ch.controller"/>
    <!--視圖解析器-->
    <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/"/>
        <property name="suffix" value=".jsp"/>
    </bean>


    <!--消息轉換器-->
    <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>application/json;charset=UTF-8</value>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter"/>
            </list>
        </property>
    </bean>

    
    <!--文件上傳-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
</beans>

然后修改/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"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:beans.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>dispatcher-servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher-servlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  <!-- 3.編碼過濾器,解決中文亂碼 -->
  <filter>
    <filter-name>SpringEncoding</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>SpringEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


  <!--CORS跨域訪問,不是必須,此處為方便前斷測試,部署時最好刪去-->
  <filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    <async-supported>true</async-supported>
    <init-param>
      <param-name>cors.allowOrigin</param-name>
      <param-value>*</param-value>
    </init-param>
    <init-param>
      <param-name>cors.supportedMethods</param-name>
      <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
    </init-param>
    <init-param>
      <param-name>cors.supportedHeaders</param-name>
      <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
    </init-param>
    <init-param>
      <param-name>cors.exposedHeaders</param-name>
      <param-value>Set-Cookie</param-value>
    </init-param>
    <init-param>
      <param-name>cors.supportsCredentials</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

至此,springmvc,spring整合完畢。

8.在dao包下創建impl包。然后在impl包下創建UserinfoMapperImpl繼承SqlSessionDaoSupport實現UserinfoMapper
package com.ch.dao.impl;

import com.ch.dao.UserinfoMapper;
import com.ch.model.Userinfo;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * Created by apple on 2017/4/25.
 */
@Repository
public class UserinfoMapperImpl extends SqlSessionDaoSupport implements UserinfoMapper {
    @Autowired
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory){
        super.setSqlSessionFactory(sqlSessionFactory);
    }
    public int deleteByPrimaryKey(String username) {
        return 0;
    }

    public int insert(Userinfo record) {
        return 0;
    }

    public int insertSelective(Userinfo record) {
        return 0;
    }

    public Userinfo selectByPrimaryKey(String username) {
        return this.getSqlSession().selectOne("com.ch.dao.UserinfoMapper.selectByPrimaryKey",username);
    }

    public int updateByPrimaryKeySelective(Userinfo record) {
        return 0;
    }

    public int updateByPrimaryKey(Userinfo record) {
        return 0;
    }
}

 



千萬別忘了在類上加上@Repository注解



9.新建service:
在service包下新建UserinfoService,因為處理的業務簡單,這里直接拷貝UserinfoMapper的內容:
package com.ch.service;

import com.ch.model.Userinfo;

/**
 * Created by apple on 2017/4/25.
 */
public interface UserinfoService {
    int deleteByPrimaryKey(String username);

    int insert(Userinfo record);

    int insertSelective(Userinfo record);

    Userinfo selectByPrimaryKey(String username);

    int updateByPrimaryKeySelective(Userinfo record);

    int updateByPrimaryKey(Userinfo record);
}

繼續在service包下新建impl包,在impl包中新建UserinfoServiceImpl實現UserinfoSerice:
package com.ch.service.impl;

import com.ch.dao.UserinfoMapper;
import com.ch.model.Userinfo;
import com.ch.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by apple on 2017/4/25.
 */
@Service
public class UserinfoServiceImpl implements UserinfoService {
    @Autowired
    UserinfoMapper userinfoMapper;
    public int deleteByPrimaryKey(String username) {
        return 0;
    }

    public int insert(Userinfo record) {
        return 0;
    }

    public int insertSelective(Userinfo record) {
        return 0;
    }

    public Userinfo selectByPrimaryKey(String username) {
        return userinfoMapper.selectByPrimaryKey(username);
    }

    public int updateByPrimaryKeySelective(Userinfo record) {
        return 0;
    }

    public int updateByPrimaryKey(Userinfo record) {
        return 0;
    }
}

 

千萬別忘了在類上加上@Service注解


10.創建bean:
在bean包下新建類OBeanBase,此類為返回json數據的載體:
package com.ch.bean;

/**
 * Created by apple on 2017/4/25.
 */
public class OBeanBase {
    private String code;
    private String message;
    private Object contents;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getContents() {
        return contents;
    }

    public void setContents(Object contents) {
        this.contents = contents;
    }

    public void setInfo(String code,String message){
        this.message = message;
        this.code = code;
    }

    public OBeanBase(){}
}

 


繼續在該包下創建類UserLoginIBean,此類為請求json數據自動轉換的類
package com.ch.bean;

/**
 * Created by apple on 2017/4/25.
 */
public class UserLoginIBean {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

 


11.創建controller:
package com.ch.controller;

import com.ch.bean.OBeanBase;
import com.ch.bean.UserLoginIBean;
import com.ch.model.Userinfo;
import com.ch.service.UserinfoService;
import org.apache.log4j.Logger;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * Created by apple on 2017/4/25.
 */
@Controller
@RequestMapping(value = "/user")
public class UserinfoController {
    @Autowired
    UserinfoService userinfoService;

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public OBeanBase doLogin(@RequestBody UserLoginIBean userLoginIBean) {
        Logger logger = Logger.getLogger("DAO");
        OBeanBase carrier = new OBeanBase();
        Userinfo userinfo = userinfoService.selectByPrimaryKey(userLoginIBean.getUsername());
        if (userinfo != null) {
            if (userinfo.getPassword().equals(userLoginIBean.getPassword())) {
                System.out.println(userinfo.getNickname());
                carrier.setInfo("S01", "登錄成功");
                logger.debug("登錄成功");
                carrier.setContents(userinfo);
            } else {
                carrier.setInfo("E01", "密碼錯誤");
            }
        } else {
            carrier.setInfo("E03", "無此賬號");
        }
        return carrier;
    }
}

12.發布:
點擊右上角的

選擇Edit,添加tomcat:

填寫Name,在ApplicationServer中選擇自己的Tomcat,


接着點擊Deployment,點擊下角的➕,選擇Artifacts

選擇下面的war exploded

然后點擊OK,APPLY,OK

12.在pom.xml中的build節點下加入:
       <!--java目錄下xml文件默認不會打包,此處手動打包,否則報錯-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>

然后點擊啟動Tomcat。

13,打開postman(谷歌的軟件,要翻牆去谷歌商店下載)測試API成功。發布。


再次附上地址:https://github.com/qq571831158/Springmvc-spring-mybatisDemo





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM