首页 > 代码库 > idea+springmvc+spring+mybatis+maven整合返回json数据webapi
idea+springmvc+spring+mybatis+maven整合返回json数据webapi
首先看一张目录结构图:
:
创建步骤:
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="http://www.mamicode.com/true"/>
<property name="suppressAllComments" value="http://www.mamicode.com/true"/>
</commentGenerator>
<!-- 数据库链接URL、用户名、密码 -->
<jdbcConnection
driverClass="${jdbc.driver}"
connectionURL="${jdbc.url}"
userId="${jdbc.username}"
password="${jdbc.password}">
</jdbcConnection>
<!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
<javaTypeResolver>
<property name="forceBigDecimals" value="http://www.mamicode.com/false"/>
</javaTypeResolver>
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径
-->
<javaModelGenerator targetPackage="com.ch.model"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="http://www.mamicode.com/true"/>
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="http://www.mamicode.com/true"/>
<!-- 是否对类CHAR类型的列的数据进行trim操作 -->
<property name="trimStrings" value="http://www.mamicode.com/true"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="http://www.mamicode.com/false"/>
</javaModelGenerator>
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<sqlMapGenerator targetPackage="com.ch.mapping"
targetProject="src/main/java">
<property name="enableSubPackages" value="http://www.mamicode.com/true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.ch.dao"
targetProject="src/main/java">
<property name="enableSubPackages" value="http://www.mamicode.com/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中用到的数据库配置。内容如下:
接下来,点击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="http://www.mamicode.com/${jdbc.driver}"/>
<property name="url" value="http://www.mamicode.com/${jdbc.url}"/>
<property name="username" value="http://www.mamicode.com/${jdbc.username}"/>
<property name="password" value="http://www.mamicode.com/${jdbc.password}"/>
<property name="testWhileIdle" value="http://www.mamicode.com/true"/>
<property name="testOnBorrow" value="http://www.mamicode.com/true"/>
<property name="testOnReturn" value="http://www.mamicode.com/false"/>
<property name="timeBetweenEvictionRunsMillis" value="http://www.mamicode.com/30000"/>
<property name="maxActive" value="http://www.mamicode.com/30"/>
<property name="minIdle" value="http://www.mamicode.com/5"/>
<property name="initialSize" value="http://www.mamicode.com/5"/>
</bean>
<!--mybatis 核心类-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="http://www.mamicode.com/classpath:spring-mybatis.xml"/>
<!--配置mybatis映射文件mapper的位置,如果配置文件在src/main/java目录下,maven默认不会编译,参考我pom.xml的,build,
当然也可以放在resources目录下,那样就可以访问到-->
<property name="mapperLocations" value="http://www.mamicode.com/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="http://www.mamicode.com/org.springframework.web.servlet.view.JstlView"/>-->
<property name="prefix" value="http://www.mamicode.com/WEB-INF/"/>
<property name="suffix" value="http://www.mamicode.com/.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="http://www.mamicode.com/10485760"/>
<property name="defaultEncoding" value="http://www.mamicode.com/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的内容:
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 = "http://www.mamicode.com/user")
public class UserinfoController {
@Autowired
UserinfoService userinfoService;
@ResponseBody
@RequestMapping(value = "http://www.mamicode.com/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(谷歌的软件,要FQ去谷歌商店下载)测试API成功。发布。
idea+springmvc+spring+mybatis+maven整合返回json数据webapi