1. 程式人生 > >springboot+mybatis+springmvc整合實例

springboot+mybatis+springmvc整合實例

1.4 prim stat html each 登陸 過程 manage embed

以往的ssm框架整合通常有兩種形式,一種是xml形式,一種是註解形式,不管是xml還是註解,基本都會有一大堆xml標簽配置,其中有很多重復性的。springboot帶給我們的恰恰是“零配置”,"零配置"不等於什麽也不配置,只是說相對於傳統的ssm框架的xml配置或是註解配置,要少的多。作為常規的來說,一個ssm框架整合,拿maven來說,首先在src/main/resource下加入jdbc.properties,spring-mvc.xml,spring-mybatis.xml等,還有要再web.xml配置監聽類和前端控制器,同時還要配置對應的加載spring-mvc和spring-mybatis的路徑。

而springboot的話,則不需要,只需在一個叫application.properties或者是叫application.yml配置數據源和解析jsp的即可。

參考網址:https://www.ggdoc.com

上述網址有許多參考文檔可參考

參考網址:https://projects.spring.io/spring-boot/ 該網址為springboot官網,官網雖然是英文的,但是可以通過第三方翻譯過來,不過最好的話還是懂點英文。建議學習一門新技術,最好還是參考其官方網址和文檔,那裏是最詳細的,其他什麽博客之類的,可以作為參考學習過程中解決問題的利器。學習過程中是不可能不遇到問題的。

最好還是那句話,在不懂該技術之前,可以通過百度百科了解,或者其他博客寫個入門實例,不過最好在此以後參考官網

就我個人的看法,必須和最好掌握spring+mybatis+springmvc等相關知識,同時也接觸過ssm框架的xml配置和ssm框架的註解配置。這樣方便比較學習,同時也有利於深入學習等。

不多說了,下面開始整合實例教程

一、準備環境

window10 jdk8 eclipe maven

二、pom文件

<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.0</modelVersion>
  <groupId>cn.springboot</groupId>
  <artifactId>springboot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
 	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.2.5.RELEASE</version>
	</parent>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<!--Spring Boot -->
		<!--支持 Web 應用開發,包含 Tomcat 和 spring-mvc。 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	
		<!--支持使用 JDBC 訪問數據庫 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<!--添加適用於生產環境的功能,如性能指標和監測等功能。 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<!--Mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.8</version>
		</dependency>
		<!--Mysql / DataSource -->
		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!--Json Support -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.1.43</version>
		</dependency>
		<!--Swagger support -->
		<dependency>
			<groupId>com.mangofactory</groupId>
			<artifactId>swagger-springmvc</artifactId>
			<version>0.9.5</version>
		</dependency>
		
		<!-- 支持jsp start -->
		<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
		<dependency>

			<groupId>org.springframework.boot</groupId>

			<artifactId>spring-boot-starter-tomcat</artifactId>

			<scope>provided</scope>

		</dependency>

		<dependency>

			<groupId>org.apache.tomcat.embed</groupId>

			<artifactId>tomcat-embed-jasper</artifactId>

			<scope>provided</scope>

		</dependency>
		<!-- end -->
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
	
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>

		</plugins>
	</build>
	<repositories>
		<repository>
			<id>spring-milestone</id>
			<url>https://repo.spring.io/libs-release</url>
		</repository>
	</repositories>
	<pluginRepositories>
		<pluginRepository>
			<id>spring-milestone</id>
			<url>https://repo.spring.io/libs-release</url>
		</pluginRepository>
</pluginRepositories>
 
 
 </project>

三、準備數據庫和表

庫名為 springboot

    CREATE TABLE `t_user` (  
      `id` INT(11) NOT NULL,  
      `username` VARCHAR(255) DEFAULT NULL,  
      `password` VARCHAR(255) DEFAULT NULL,  
      `email` VARCHAR(255) DEFAULT NULL,  
      `useable` INT(20) DEFAULT NULL,  
      `addtime` DATETIME DEFAULT NULL,  
      `logintime` DATETIME DEFAULT NULL,  
      `loginip` VARCHAR(255) DEFAULT NULL,  
      PRIMARY KEY  (`id`)  
    ) ENGINE=INNODB DEFAULT CHARSET=utf8;  

四、在src/main/resource下新建application.properties文件

spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.view.prefix=/WEB-INF/templates/
spring.view.suffix=.jsp

五、建立實體類和對應的mapper接口相關

1.建立實體

    package com.sam.project.mvc.model;  
      
    /**  
     * @ClassName: User  
     * @Description: 實體模型  
     */  
    public class User {  
        private Integer id;  
      
        private String username;  
      
        private String password;  
      
        private String email;  
      
        /**  
         * 是否可用(0禁用,1可用)  
         */  
        private Integer useable;  
      
        /**  
         * 創建時間  
         */  
        private String addtime;  
      
        /**  
         * 登陸時間  
         */  
        private String logintime;  
      
        /**  
         * 登陸IP  
         */  
        private String loginip;  
      
        /**  
         * @return id  
         */  
        public Integer getId() {  
            return id;  
        }  
      
        /**  
         * @param id  
         */  
        public void setId(Integer id) {  
            this.id = id;  
        }  
      
        /**  
         * @return username  
         */  
        public String getUsername() {  
            return username;  
        }  
      
        /**  
         * @param username  
         */  
        public void setUsername(String username) {  
            this.username = username;  
        }  
      
        /**  
         * @return password  
         */  
        public String getPassword() {  
            return password;  
        }  
      
        /**  
         * @param password  
         */  
        public void setPassword(String password) {  
            this.password = password;  
        }  
      
        /**  
         * @return email  
         */  
        public String getEmail() {  
            return email;  
        }  
      
        /**  
         * @param email  
         */  
        public void setEmail(String email) {  
            this.email = email;  
        }  
      
        /**  
         * 獲取是否可用(0禁用,1可用)  
         *  
         * @return useable - 是否可用(0禁用,1可用)  
         */  
        public Integer getUseable() {  
            return useable;  
        }  
      
        /**  
         * 設置是否可用(0禁用,1可用)  
         *  
         * @param useable  
         *            是否可用(0禁用,1可用)  
         */  
        public void setUseable(Integer useable) {  
            this.useable = useable;  
        }  
      
        /**  
         * 獲取創建時間  
         *  
         * @return addtime - 創建時間  
         */  
        public String getAddtime() {  
            return addtime;  
        }  
      
        /**  
         * 設置創建時間  
         *  
         * @param addtime  
         *            創建時間  
         */  
        public void setAddtime(String addtime) {  
            this.addtime = addtime;  
        }  
      
        /**  
         * 獲取登陸時間  
         *  
         * @return logintime - 登陸時間  
         */  
        public String getLogintime() {  
            return logintime;  
        }  
      
        /**  
         * 設置登陸時間  
         *  
         * @param logintime  
         *            登陸時間  
         */  
        public void setLogintime(String logintime) {  
            this.logintime = logintime;  
        }  
      
        /**  
         * 獲取登陸IP  
         *  
         * @return loginip - 登陸IP  
         */  
        public String getLoginip() {  
            return loginip;  
        }  
      
        /**  
         * 設置登陸IP  
         *  
         * @param loginip  
         *            登陸IP  
         */  
        public void setLoginip(String loginip) {  
            this.loginip = loginip;  
        }  
    }  

2.建立對應的mapper接口

package com.sam.project.mvc.mapper;  
  
import java.util.List;  
  
import com.sam.project.mvc.model.User;  
  
/**  
 * @ClassName: UserMapper   
 * @Description: mybites數據查詢接口  
 */  
public interface UserMapper {  
  
    List<User> queryList();  
  
    void save(User user);  
  
    void batchDelete(Integer[] ids);  
  
    void update(User user);  
  
} 

3.建立mapper對應的xml文件

在src/main/resource下新建mapper文件夾

在該文件下下新建UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"   
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
    <mapper namespace="com.sam.project.mvc.mapper.UserMapper">  
        <select id="queryList" resultType="com.sam.project.mvc.model.User">  
            SELECT u.id, u.username, u.password, u.email, u.useable, u.addtime, u.logintime, u.loginip FROM t_user u  
        </select>  
          
        <select id="queryById" resultType="com.sam.project.mvc.model.User">  
            SELECT u.id, u.username, u.password, u.email, u.useable, u.addtime, u.logintime, u.loginip FROM t_user u where u.id = #{id}  
        </select>  
          
        <insert id="save">  
            insert into t_user(username, password, email, useable, addtime)  
            values(#{username}, #{password}, #{email}, #{useable}, now())  
        </insert>  
          
        <update id="update">  
            update t_user set password = #{password}, email = #{email}, useable = #{useable} where id = #{id}  
        </update>  
          
        <delete id="batchDelete">  
            delete from t_user where id in  
            <foreach collection="array" item="item" open="(" separator="," close=")">  
                #{item}  
            </foreach>  
        </delete>  
          
        <!-- <delete id="delUsers">  
            delete from t_user where id in  
            <foreach collection="list" item="item" open="(" separator="," close=")">  
                #{item}  
            </foreach>  
        </delete> -->  
    </mapper>  

六、建立業務接口和對應的Controller及其相關返回json數據工具類

1.UserService業務接口

package com.sam.project.mvc.service;  
      
    import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sam.project.mvc.common.AjaxResult;
import com.sam.project.mvc.mapper.UserMapper;
import com.sam.project.mvc.model.User;  
      
    @Service  
    public class UserService {  
      
        @Autowired  
        private UserMapper userMapper;  
          
        public AjaxResult queryList() {  
            List<User> list = userMapper.queryList();  
            return new AjaxResult(list);  
        }  
      
        public AjaxResult save(User user) {  
            user.setUsername("user" + System.currentTimeMillis());  
            user.setPassword("123456");  
            user.setEmail("user" + System.currentTimeMillis());  
            user.setUseable(1);  
            userMapper.save(user);  
            return new AjaxResult();  
        }  
      
        public AjaxResult batchDelete(Integer[] ids) {  
            userMapper.batchDelete(ids);  
            return new AjaxResult();  
        }  
      
        public AjaxResult update(User user) {  
            userMapper.update(user);  
            return new AjaxResult();  
        }  
      
    }  

2.controller

    package com.sam.project.mvc.controller;  
      
    import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sam.project.mvc.common.AjaxResult;
import com.sam.project.mvc.model.User;
import com.sam.project.mvc.service.UserService;  
      
    /**  
     * @ClassName: UserController   
     * @Description: 用戶Controller  
     */  
    @Controller  
    public class UserController {  
      
        @Autowired  
        private UserService userService;  
          
        @ResponseBody  
        @RequestMapping("/queryList")  
        public AjaxResult queryList(){  
            return userService.queryList();  
        }  
      
        @ResponseBody  
        @RequestMapping("/addUser")  
        public AjaxResult addUser(User user){  
            return userService.save(user);  
        }  
          
        @ResponseBody  
        @RequestMapping("/delUser")   
        public AjaxResult delUser(Integer[] ids){  
            return userService.batchDelete(ids);  
        }  
          
        @ResponseBody  
        @RequestMapping("/updateUser")  
        public AjaxResult updateUser(User user){  
            return userService.update(user);  
        }  
        
        @RequestMapping("/hello")
        public String hello(ModelMap map) {
            map.put("title", "你好");
            return "index";
        }
      
    }  

3.工具類

    package com.sam.project.mvc.common;  
      
    /**  
     * @ClassName: AjaxResult   
     * @Description: 封裝返回數據  
     */  
    public class AjaxResult {  
      
        private int retcode = 1;  
        private String retmsg = "操作成功";  
        private Object data;  
          
        public AjaxResult(int retcode, String retmsg, Object data){  
            this.retcode = retcode;  
            this.retmsg = retmsg;  
            this.data = data;  
        }  
          
        public AjaxResult(int retcode, String retmsg){  
            this.retcode = retcode;  
            this.retmsg = retmsg;  
        }  
          
        public AjaxResult(Object data){  
            this.retmsg = "查詢成功";  
            this.data = data;  
        }  
          
        public AjaxResult(int retcode){  
            this.retcode = retcode;  
            this.retmsg = "操作失敗";  
        }  
          
        public AjaxResult(String retmsg){  
            this.retcode = 0;  
            this.retmsg = retmsg;  
        }  
          
        public AjaxResult(){  
              
        }  
      
        public int getRetcode() {  
            return retcode;  
        }  
        public void setRetcode(int retcode) {  
            this.retcode = retcode;  
        }  
        public String getRetmsg() {  
            return retmsg;  
        }  
        public void setRetmsg(String retmsg) {  
            this.retmsg = retmsg;  
        }  
        public Object getData() {  
            return data;  
        }  
        public void setData(Object data) {  
            this.data = data;  
        }  
      
        @Override  
        public String toString() {  
            return "AjaxResult [retcode=" + retcode + ", retmsg=" + retmsg + ", data=" + data + "]";  
        }  
          
    }  

七、springboot啟動類

package com.sam.project.mvc;
 
import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
 
@EnableAutoConfiguration
@SpringBootApplication
@ComponentScan
@MapperScan("com.sam.project.mvc.mapper")
public class Application extends SpringBootServletInitializer {
    private static Logger logger = Logger.getLogger(Application.class);
 
    //DataSource配置
    @Bean
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource dataSource() {
        return new org.apache.tomcat.jdbc.pool.DataSource();
    }
 
    //提供SqlSeesion
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
 
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
 
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
 
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"));
 
        return sqlSessionFactoryBean.getObject();
    }
 
    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
 
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
    /**
     * Main Start
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        logger.info("============= SpringBoot Start Success =============");
    }
 
}

八、在WEB-INF下新建templates文件夾並在該文件夾下新建index.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>你好</title>
</head>
<body>
${title }
</body>
</html>

九、啟動Application類

啟動成功,控制臺會顯示如下內容

技術分享圖片

十、在瀏覽器輸入localhost:8080/hello

技術分享圖片

上述就是springboot+springmvc+mybatis整合實例

springboot+mybatis+springmvc整合實例