实例代码,Mybatis入门搭建例子

英特尔liJ IDEA下Maven SpringMVC+Mybatis入门搭建例子,intellijmaven

 

非常久在此以前写了一篇SSH搭建例子,由于专门的学问缘故现已转到SpringMVC+Mybatis,就以在此以前SSH完毕轻易登录的事例,计算看看SpringMVC+Mybatis怎么落实。

Spring一起始是轻量级的框架,在SSH中,处于中游粘合剂的功用,大旨作用是IoC(调节反转)、DI(依赖注入),IoC和DI是同壹个定义,只是以差别角度举行分解。简单的讲,便是Spring支持你处理Bean,只要写好了安排文件也许Spring注脚,那么Spring能够自动帮你创造Bean,没有要求手动new。经过后来的上进出现的SpringMVC框架,与Struts一样,同属于MVC框架的一种,SpringMVC能够说和Spring是两遍事了,已是二个相当的重的框架了,笔者的接头是SpringMVC=Struts+Spring了。

Spring还恐怕有别的二个最首要组成都部队分是AOP(Aspect-Oriented Programming
面向切面编制程序),目前任重先生而道远行使在拦截器方面。实际上Struts也会有拦截器,概念是看似的。

Hibernate、Mybatis、ibatis都以常用的悠久层框架,能够回顾的感觉Hibernate相当的重,Mybatis、ibatis相当的轻量,Mybatis又是由ibatis发展来的,所以Mybatis与ibatis非常相似,Ali用的就是ibatis(毕竟那时候还从未Mybatis),三者之间的界别网络能够搜一下,就不开展说了。

IDE集成开拓工具作者也从MyEclipse转到速龙liJ
IDEA了(版本是2017.1.3),工具上接纳一定有点组别,不过写代码上是从未有过区分的。

一、建立Maven SpringMVC项目

率先依然要下载安装好JDK,如今JDK版本现已到9,也不用非常去下载J2EE的版本,就下载二个J2SE版本的就足以,笔者下载的是JDK8的,开垦情形是Windows,所以下载了三个Windows
x64的jdk-8u161-windows-x64.exe(下载地址

-version有版本消息体现就足以了。

其余为了更好的军管jar,小编利用了maven(下载地址

Tools->Maven里设置Maven home directory、User setting file、Local
repository。

选拔IDEA创造maven
SpringMVC项目标详细进程请参见博文

展开IDEA之后,File->new->Project,选拔如下maven-archetype-webapp

图片 1

next,输入GroupId和ArtifactId,next,next,输入Project name

点击finish,就创设好项目了,那时maven会首先去下载maven骨架,也正是体系集体结构布局文件,还应该有点供给的jar包。

等maven下载达成未来,就赢得了着力项目框架,参照上面博文,创建java目录并标识source,建设构造相关pakage,项目框架就基本到位了,笔者的品类布局如下图所示:

图片 2

那会儿,我们要使用maven参加springmvc、mybatis相关jar包,张开pom.xml,仿照如下增添properties和dependencies

<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.test</groupId>
  <artifactId>springmvctest</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>springmvctest Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <!-- spring版本号 -->
    <spring.version>4.1.6.RELEASE</spring.version>
    <!-- mybatis版本号 -->
    <mybatis.version>3.2.6</mybatis.version>
    <!-- log4j日志文件管理包版本 -->
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
    <!-- jackson包版本 -->
    <jackson.version>2.5.0</jackson.version>

  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!--spring单元测试依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
      <scope>test</scope>
    </dependency>

    <!-- springMVC核心包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- spring核心包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</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-context</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-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.0.9.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</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-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- AOP begin -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.7.4</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.7.4</version>
    </dependency>
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib</artifactId>
      <version>3.1</version>
    </dependency>
    <!-- AOP end -->

    <!-- mybatis核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>

    <!--mybatis spring 插件 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>

    <!-- Mysql数据库驱动包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.34</version>
    </dependency>

    <!--servlet-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

  </dependencies>
  <build>
    <finalName>springmvctest</finalName>
  </build>
</project>

要是前面还大概有供给下载的jar包,例如log4j等,能够去这么些网址

二、使用Spring

WEB-INF下的web.xml可以精晓为全部项目标进口,无论是Struts依然Spring都以先从这几个web.xml找到相关布置,再步入struts或是spring的框架中的。打开web.xml,修改为如下内容:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
  <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>
</web-app>

如上就加多了Spring框架技巧,DispatcherServlet从名称想到所包含的意义,正是转载的意趣,mapping的url-pattern写的是/,表达具有央浼都施用那些DispatcherServlet实行中转。大家能够对照一下struts的布署文件,struts是使用filter的,而spring使用的是servlet。有了Dispatcher转载,就须要再增多三个写什么转发的布置文件dispatcher-servlet.xml,同样在WEB-INF底下增添这一个文件即可,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">
    <description>Spring Configuration</description>
    <!-- 静态资源(js、image等)的访问 -->
    <mvc:default-servlet-handler/>
    <!-- 配置注解驱动 可以将request参数与绑定到controller参数上 -->
    <mvc:annotation-driven />
    <!-- 开启组件自动扫描;使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。  -->
    <!-- base-package 如果多个,用“,”分隔 -->
    <context:component-scan base-package="com.test.dao,com.test.service,com.test.controller" />
    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀(如果最后一个还是表示文件夹,则最后的斜杠不要漏了) 使用JSP-->
    <!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- -->
    <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/view/"/><!--设置JSP文件的目录位置-->
        <property name="suffix" value=".jsp"/>
    </bean>
 </beans>

<mvc:annotation-driven
/>这一句表明启用自动扫描Spring表明,<context:component-scan
base-package=”com.test.dao,com.test.service,com.test.controller”
/>那句表明扫描的岗位。defaultViewResolver这么些bean主若是用来平价controller再次来到搜索jsp视图,定义了jsp目录地点是/WEB-INF/view/上面。

那么,今年,大家来先写贰个controller,名字就叫IndexController吧,用来拍卖Index主页,其实就是登入页面。

package com.test.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Created by jeff on 2018/2/13.
 */
@Controller
@RequestMapping("/")
public class IndexController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String loginview(){
        return "loginview";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(@ModelAttribute("username") String username, @ModelAttribute("password") String password){
        if(username.equals("jeff") && password.equals("123"))
            return "index";
        return "loginview";
    }
}

能够看见,Class
IndexController下面有三个注明,贰个是@Controller,表达这么些Class是贰个Controller,另二个是@RequestMapping,约等于访谈路径。

在IndexController定义了七个措施,loginview和login,方法方面同样有@RequestMapping声明,细分访谈路径,还定义了它是GET照旧POST方法。

在login方法的参数username和password前边还也可以有@ModelAttribute评释,那是对应页面成分的name的,用于获取页面成分的值。这里其实便是借助注入了,大家从没开端化username和passowrd,就直接使用了,其实就是Spring帮大家获得并伊始化设置了页面对应的值进username和password里了。

那么,return “loginview”和return
“index”又是怎么着看头呢?那四个法子的重回值都以String类型,再次回到给什么人啊?刚刚上边dispatcher-servlet.xml文件中,我们定义了defaultViewResolver这一个bean,正是用来拍卖那么些String的,重返一个index,那么Spring就能够去你定义好的/WEB-INF/view/下边,找对应的jsp文件。所以,应该能够猜到,大家必要在/WEB-INF/view/上面新建多个jsp文件,二个叫loginview.jsp,一个叫index.jsp。

loginview.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="zh-CN">
<body>
    <form method="get" action="/login">
        登录名:<input name='username' type="text" /><br/>
        密码:<input name ='password' type="password" /><br/>
        <button type="submit" style="width: 70px; height: 20px;">确定</button>
    </form>
</body>
</html>

index.jsp

<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

完了了那个,还不可能运作起来,我们还也许有一个珍视的事物还未有,那便是tomcat恐怕jboss那些器皿。初学者学习了多少个月,说不定其实还不曾询问怎么着是容器,容器是用来做什么样的。首先,容器是指servlet容器,就是放一批大家刚刚写的servlet的。至于怎么样效果,其实大家从C写面向过程过来的话,能够想一想,C里面必得有八个main函数,不然程序从哪儿起始吧?学C++使用MFC框架时,小编就意识并未有了main函数,以为很想获得,程序怎么理解从哪个地方进去吧?我们地点写的代码,配置文件,也从不点名别的的main函数。其实main函数正是容器里的,能够想像成那些main函数一向在循环等待触发事件,一旦接受点击张开有些网页之类的下令,那么容器就能去找相应的servlet进行拍卖。领会了这一个,就去下载一个tomcat恐怕jboss容器,在idea里陈设好就行了,笔者这里运用常用的tomcat,网络搜一下idea配置tomcat就能够了。

run之后,张开浏览器,输入

图片 3

输入jeff登陆名和123密码,就可以跳转到index首页,其余登录名密码则不会跳转

图片 4

三、使用Mybits

既然Mybatis是贰个漫长层框架,使用Mybatis在此以前,大家供给有两个数据库,那么下载三个常用的开源无需付费的MySQL安装配置好就能够(

设置好之后,使用MySQLWorkbench连进去,实行创办数据库、建表等操作。

create database springtest;
use springtest;

create table users
(
id int PRIMARY KEY AUTO_INCREMENT,
username varchar(20),
password varchar(50)
) auto_increment = 1;

insert into users(username,password) values('jeff','123');

相应的,大家得以在entity包下新建多少个Users类

package com.test.entity;

import org.springframework.stereotype.Repository;

/**
 * Created by jeff on 2018/2/22.
 */public class Users {

    private Integer id;
    private String username;
    private String password;

    public  Integer getId() { return id; }

    public void setId(Integer id) { this.id = id; }

    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;}

}

那时在品种中必要连接MySQL数据库,在resources下增加jdbc.properties文件,内容如下:

jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/springtest
jdbc_username=root
jdbc_password=888888

在dispatcher-servlet.xml扩张以下内容:

    ...
    <!-- 配置数据源 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
                <!--要是有多个配置文件,只需在这里继续添加即可 -->
            </list>
        </property>
    </bean>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>${jdbc_driverClassName}</value>
        </property>
        <property name="url">
            <value>${jdbc_url}</value>
        </property>
        <property name="username">
            <value>${jdbc_username}</value>
        </property>
        <property name="password">
            <value>${jdbc_password}</value>
        </property>
    </bean>
    <!-- 配置Mybatis的文件 ,mapperLocations配置**Mapper.xml文件位置,configLocation配置mybatis-config文件位置-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
   ...

propertyConfigurer这么些bean定义了配置文件路线,dataSource这么些bean找到配置文件就机关心入property。

在jdbc.properties中安顿了jdbc_driverClassName=com.mysql.jdbc.Driver,那就是大家连接MySQL的jar手拿包含的数据库驱动,大家在前头pom.xml已经写了三个MySQL的dependency,已经将该jar包下载下来了,今后就足以平素动用了,倘使使用其余数据库,那么就换到其他驱动包就可以,相应的jdbc_driverClassName就需求修改。

sqlSessionFactory这几个工厂类bean是mybatis推荐的使用形式,mapperLocations定义了mybatis的mapper
xml文件的地方,能够观看本人那是概念在resources下mapper目录下的。

由此,我们需求在mapper目录下新建四个UsersMapper.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.test.mapper.UsersMapper">
    <!--设置domain类和数据库中表的字段一一对应,注意数据库字段和domain类中的字段名称不致,此处一定要!-->
    <resultMap id="BaseUsers" type="com.test.entity.Users">
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="username" property="username" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
    </resultMap>
    <!-- 查询所有记录 -->
    <select id="selectAllUsers" resultMap="BaseUsers">
        SELECT * FROM users
    </select>
    <!-- 查询单个记录 -->
    <select id="selectUsersByUsername" parameterType="java.lang.String"  resultMap="BaseUsers">
        SELECT * FROM users WHERE username=#{username}
    </select>
</mapper>

实例代码,Mybatis入门搭建例子。那般就定义了数额库表与entity类的照射关系。实现了那几个,咱们就必要写dao、service接口类和落实类了

dao接口类

package com.test.dao;

import com.test.entity.Users;

/**
 * Created by jeff on 2018/2/22.
 */
public interface UsersDao {
    Users getUsersByUsername(String username);
}

dao实现类

package com.test.dao.impl;

import com.test.dao.UsersDao;
import com.test.entity.Users;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * Created by jeff on 2018/2/22.
 */
@Repository
public class UsersDaoImpl extends SqlSessionDaoSupport implements UsersDao {
    @Resource
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        // TODO Auto-generated method stub
        super.setSqlSessionFactory(sqlSessionFactory);
    }
    @Override
    public Users getUsersByUsername(String username){
        return this.getSqlSession().selectOne("com.test.mapper.UsersMapper.selectUsersByUsername", username);
    }
}

service接口类

package com.test.service;

import com.test.entity.Users;

/**
 * Created by jeff on 2018/2/22.
 */
public interface UsersService {
    Users getUsersByUsername(String username);
}

service实现类

package com.test.service.impl;

import com.test.dao.UsersDao;
import com.test.entity.Users;
import com.test.service.UsersService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by jeff on 2018/2/22.
 */
@Service
public class UsersServiceImpl implements UsersService {
    @Resource
    private UsersDao usersDao;
    @Override
    public Users getUsersByUsername(String username){
        return usersDao.getUsersByUsername(username);
    }
}

这儿候IndexController要求修改为如下:

package com.test.controller;

import com.test.entity.Users;
import com.test.service.UsersService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;

/**
 * Created by jeff on 2018/2/13.
 */
@Controller
@RequestMapping("/")
public class IndexController {
    @Resource
    private UsersService usersService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String loginview(){
        return "loginview";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(@ModelAttribute("username") String username, @ModelAttribute("password") String password){
        Users user = usersService.getUsersByUsername(username);
        if(user != null && user.getPassword().equals(password))
            return "index";
        return "loginview";
    }
}

这么就完了了利用MyBatis连接数据库查询客商消息跳转index主页的作用。

那边遵照上边运用的Spring申明解释一下,@Repository意思是货仓、储藏,这里就是悠久层的意味,专门用来讲授那是长久层bean,@Service意思就是服务层,特意用来讲明服务层,还会有一种阐明是@Component,意思是组件,用来疏解不或许定义是服务层依旧长久层的别的bean。那多少个注明效果是一样的,随意换哪三个都是足以的,但为了便利阅读和职业,请精确使用在对应的bean上。

@Controller的讲授类似于struts的@Action申明,平常定义web层,间接与页面交互。

谈到底,附上项目集体层级结构树

图片 5

图片 6

由于文凭有限,如有遗漏错误之处,请指正,非常谢谢。

 

IDEA下Maven
SpringMVC+Mybatis入门搭建例子,intellijmaven
相当久在此以前写了一篇SSH搭建例子,由于工作原因已经转到SpringMVC+Mybatis,就以以前SS…

三大框架搭建整合英特网资料相当多,但对于新手来讲多而杂,再增添有个别坑令人很难筛选,于是本身调整写那篇小说并附着github代码,而且代码会不停的换代扩大直到饱含一些宽广常用的效果与利益截至。

连锁条件

  • Intellij IDEA Ultimate
  • Tomcat
  • JDK
  • MySql
    5.6(win32/win64)
  • Maven (可使用Intellij IDEA自带的)

有关条件

  • Intellij IDEA Ultimate
  • Tomcat
  • JDK
  • MySql
    5.6(win32/win64)
  • Maven (可使用Intellij IDEA自带的)

github代码地址:

搭建步骤

搭建步骤

先是看下笔者创设好的整个项目目录结构

创办项目工程

1、成立工程,选取Maven
图片 7

2、填写项目音讯
图片 8

图片 9

图片 10

创造项目工程

1、创立工程,采用Maven
图片 11

2、填写项目消息
图片 12

图片 13

图片 14

图片 15

开首化配置

1、Maven配置
先说Maven的门类看重配置文件pom.xml,大家进去mvn
repository 查找需要寻觅的包结果如图:
图片 16

点击步向第三个找出结果,然后各样版本
图片 17

点击所需版本。如图:
图片 18
中间的dependency即为所需标签。

总的配置文件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>SSMTestProject</groupId>
  <artifactId>SSMTestProject</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SSMTestProject Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.7.2</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>1.9.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate.javax.persistence</groupId>
      <artifactId>hibernate-jpa-2.0-api</artifactId>
      <version>1.0.1.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>5.1.0.Final</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>
    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20160212</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.7.2</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.7.2</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.1</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.4</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>SSMTestProject</finalName>
  </build>
</project>

2、web配置

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>
  <display-name>SSMTestProject</display-name>
  <servlet>
    <servlet-name>myspring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>myspring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>encodingFilter</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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

采纳spring框架的暗许DispatcherSerlet。load-on-starup标签表示servlet的启用时间,servlet-name点名了serevlet配置文件myspring。url
-pattern
是指具备路径均会被该servlet拦截。而filter一句是防范中文乱码,启用uft-8。

配置Servlet myspring-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">

    <!--指明 controller 所在包,并扫描其中的注解-->
    <context:component-scan base-package="com.ssm.controller"/>

    <!-- 静态资源(js、image等)的访问 -->
    <mvc:default-servlet-handler/>

    <!-- 开启注解 -->
    <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>

log4j.xml 配置文件如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  <!--
    - This is a sample configuration for log4j.
    - It simply just logs everything into a single log file.
    - Note, that you can use properties for value substitution.
    -->
  <appender name="CORE" class="org.apache.log4j.FileAppender">
    <param name="File"   value="${org.apache.cocoon.work.directory}/cocoon-logs/log4j.log" />
    <param name="Append" value="false" />
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d %-5p %t %c - %m%n"/>
    </layout>
  </appender>

  <root>
    <priority value="${org.apache.cocoon.log4j.loglevel}"/>
    <appender-ref ref="CORE"/>
  </root>
</log4j:configuration>

3、mybatis配置
能够应用申明大概xml的艺术布置sql操作,这里运用注脚格局:

// 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>
    <!-- development:开发模式     work:工作模式 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/ssm" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>

    <!--<mappers>
        <mapper resource="userMapper.xml" />
    </mappers>-->
    <mappers>
        <mapper class="com.ssm.Mapper.UserMapper"/>
    </mappers>

</configuration>

使用xml方式:

// 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="userMapper">
    <!--根据ID获取对应的值  -->
    <select id="findUserById" parameterType="int" resultType="com.ssm.model.User">
        select * from user where id = #{id}
    </select>
    <insert id="addUser" parameterType="com.ssm.model.User">
        insert into user(username,password) values(#{username},#{password})
    </insert>
</mapper>

开首化配置

1、Maven配置
先说Maven的品种信赖配置文件pom.xml,大家步向mvn
repository 查找要求探寻的包结果如图:
图片 19

点击步入第三个寻找结果,然后各样本子
图片 20

点击所需版本。如图:
图片 21
里头的dependency即为所需标签。

总的配置文件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>SSMTestProject</groupId>
  <artifactId>SSMTestProject</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SSMTestProject Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.7.2</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>1.9.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate.javax.persistence</groupId>
      <artifactId>hibernate-jpa-2.0-api</artifactId>
      <version>1.0.1.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>5.1.0.Final</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>
    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20160212</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.7.2</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.7.2</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.1</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.4</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>SSMTestProject</finalName>
  </build>
</project>

2、web配置

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>
  <display-name>SSMTestProject</display-name>
  <servlet>
    <servlet-name>myspring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>myspring</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>encodingFilter</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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

应用spring框架的暗中同意DispatcherSerlet。load-on-starup标签表示servlet的启用时间,servlet-name钦赐了serevlet配置文件myspring。url
-pattern
是指具有路子均会被该servlet拦截。而filter一句是严防中文乱码,启用uft-8。

配置Servlet myspring-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">

    <!--指明 controller 所在包,并扫描其中的注解-->
    <context:component-scan base-package="com.ssm.controller"/>

    <!-- 静态资源(js、image等)的访问 -->
    <mvc:default-servlet-handler/>

    <!-- 开启注解 -->
    <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>

log4j.xml 配置文件如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  <!--
    - This is a sample configuration for log4j.
    - It simply just logs everything into a single log file.
    - Note, that you can use properties for value substitution.
    -->
  <appender name="CORE" class="org.apache.log4j.FileAppender">
    <param name="File"   value="${org.apache.cocoon.work.directory}/cocoon-logs/log4j.log" />
    <param name="Append" value="false" />
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d %-5p %t %c - %m%n"/>
    </layout>
  </appender>

  <root>
    <priority value="${org.apache.cocoon.log4j.loglevel}"/>
    <appender-ref ref="CORE"/>
  </root>
</log4j:configuration>

3、mybatis配置
可以选用申明只怕xml的办法安顿sql操作,这里运用申明情势:

// 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>
    <!-- development:开发模式     work:工作模式 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/ssm" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>

    <!--<mappers>
        <mapper resource="userMapper.xml" />
    </mappers>-->
    <mappers>
        <mapper class="com.ssm.Mapper.UserMapper"/>
    </mappers>

</configuration>

使用xml方式:

// 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="userMapper">
    <!--根据ID获取对应的值  -->
    <select id="findUserById" parameterType="int" resultType="com.ssm.model.User">
        select * from user where id = #{id}
    </select>
    <insert id="addUser" parameterType="com.ssm.model.User">
        insert into user(username,password) values(#{username},#{password})
    </insert>
</mapper>

1.
一建立一个maven项目:这一步不懂的参见小编的前一篇博文:

Java类

在main文件夹下创建文件夹java,点击右键将java作为source文件夹:
图片 22

Controller

// MainController.java
package com.ssm.controller;

import com.ssm.model.User;
import com.ssm.service.IUserService;
import com.ssm.service.UserServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class MainController {

    private IUserService service = new UserServiceImpl();

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String index(User user) {
        return "index";
    }
    @RequestMapping(value="/nice",method = RequestMethod.GET)
    @ResponseBody
    public List<User> nice(Model model){
        return service.getAllUsers();
    }

    @RequestMapping(value ="/toJson",method=RequestMethod.POST)
    @ResponseBody
    public User toJson(User user){
        service.addUser(user); //一起测试了
        return service.findUserById(2);
    }
}

DAO

// IUserDao.java
package com.ssm.Dao;

import com.ssm.model.User;

import java.util.List;

public interface IUserDao {
    public User findUserById(int id); //查询
    public void addUser(User user); //添加
    public List<User> getAllUsers();
}

// UserDaoImpl.java
package com.ssm.Dao;

import com.ssm.Mapper.UserMapper;
import com.ssm.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class UserDaoImpl implements IUserDao{
    private SqlSessionFactory sessionFactory;
    private SqlSession session;
    private UserMapper mapper;
    public UserDaoImpl() {
        String resource = "config.xml";
//        try {
//            Reader reader = Resources.getResourceAsReader(resource);
//            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//            session = sessionFactory.openSession();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        try {
            Reader reader = Resources.getResourceAsReader(resource);
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            session = sessionFactory.openSession();
            mapper = session.getMapper(UserMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public User findUserById(int id) {
//        String statement = "userMapper.findUserById";
//        User user = (User)session.selectOne(statement, 1);
//        return user;
        return mapper.findUserById(id);
    }
    public void addUser(User user) {
//        String statement = "userMapper.addUser";
//        session.insert(statement, user);
//        session.commit();  //一定要记得commit
        mapper.addUser(user);
        session.commit();
    }

    public List<User> getAllUsers() {
        return mapper.getAllUsers();
    }
}

Mapper

// UserMapper.java
package com.ssm.Mapper;

import com.ssm.model.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper {
    @Select("select * from user where id = #{id}")
    User findUserById(int id);

    @Insert("insert into user(username,password) values(#{username},#{password})")
    void addUser(User user);

    @Select("select * from user")
    List<User> getAllUsers();

}

Model

// User.java
package com.ssm.model;

public class User {
    private String username;
    private String password;
    private int id;


    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;
    }

    public User(String username, String password, int id) {
        this.username = username;
        this.password = password;
        this.id = id;
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public User() {
    }
}

service

// IUserService.java
package com.ssm.service;

import com.ssm.model.User;

import java.util.List;

public interface IUserService {
    public User findUserById(int id);
    public void addUser(User user);
    public List<User> getAllUsers();
}

// UserServiceImpl.java
package com.ssm.service;

import com.ssm.Dao.IUserDao;
import com.ssm.Dao.UserDaoImpl;
import com.ssm.model.User;

import java.util.List;

public class UserServiceImpl implements IUserService {
    private IUserDao userDao;

    public UserServiceImpl() {
        userDao = new UserDaoImpl();
    }

    public User findUserById(int id) {
        return userDao.findUserById(id);
    }
    public void addUser(User user){
        userDao.addUser(user);
    }

    public List<User> getAllUsers() {
        return userDao.getAllUsers();
    }
}

Java类

在main文件夹下创制文件夹java,点击右键将java作为source文件夹:
图片 23

Controller

// MainController.java
package com.ssm.controller;

import com.ssm.model.User;
import com.ssm.service.IUserService;
import com.ssm.service.UserServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class MainController {

    private IUserService service = new UserServiceImpl();

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String index(User user) {
        return "index";
    }
    @RequestMapping(value="/nice",method = RequestMethod.GET)
    @ResponseBody
    public List<User> nice(Model model){
        return service.getAllUsers();
    }

    @RequestMapping(value ="/toJson",method=RequestMethod.POST)
    @ResponseBody
    public User toJson(User user){
        service.addUser(user); //一起测试了
        return service.findUserById(2);
    }
}

DAO

// IUserDao.java
package com.ssm.Dao;

import com.ssm.model.User;

import java.util.List;

public interface IUserDao {
    public User findUserById(int id); //查询
    public void addUser(User user); //添加
    public List<User> getAllUsers();
}

// UserDaoImpl.java
package com.ssm.Dao;

import com.ssm.Mapper.UserMapper;
import com.ssm.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class UserDaoImpl implements IUserDao{
    private SqlSessionFactory sessionFactory;
    private SqlSession session;
    private UserMapper mapper;
    public UserDaoImpl() {
        String resource = "config.xml";
//        try {
//            Reader reader = Resources.getResourceAsReader(resource);
//            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//            session = sessionFactory.openSession();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        try {
            Reader reader = Resources.getResourceAsReader(resource);
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            session = sessionFactory.openSession();
            mapper = session.getMapper(UserMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public User findUserById(int id) {
//        String statement = "userMapper.findUserById";
//        User user = (User)session.selectOne(statement, 1);
//        return user;
        return mapper.findUserById(id);
    }
    public void addUser(User user) {
//        String statement = "userMapper.addUser";
//        session.insert(statement, user);
//        session.commit();  //一定要记得commit
        mapper.addUser(user);
        session.commit();
    }

    public List<User> getAllUsers() {
        return mapper.getAllUsers();
    }
}

Mapper

// UserMapper.java
package com.ssm.Mapper;

import com.ssm.model.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper {
    @Select("select * from user where id = #{id}")
    User findUserById(int id);

    @Insert("insert into user(username,password) values(#{username},#{password})")
    void addUser(User user);

    @Select("select * from user")
    List<User> getAllUsers();

}

Model

// User.java
package com.ssm.model;

public class User {
    private String username;
    private String password;
    private int id;


    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;
    }

    public User(String username, String password, int id) {
        this.username = username;
        this.password = password;
        this.id = id;
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public User() {
    }
}

service

// IUserService.java
package com.ssm.service;

import com.ssm.model.User;

import java.util.List;

public interface IUserService {
    public User findUserById(int id);
    public void addUser(User user);
    public List<User> getAllUsers();
}

// UserServiceImpl.java
package com.ssm.service;

import com.ssm.Dao.IUserDao;
import com.ssm.Dao.UserDaoImpl;
import com.ssm.model.User;

import java.util.List;

public class UserServiceImpl implements IUserService {
    private IUserDao userDao;

    public UserServiceImpl() {
        userDao = new UserDaoImpl();
    }

    public User findUserById(int id) {
        return userDao.findUserById(id);
    }
    public void addUser(User user){
        userDao.addUser(user);
    }

    public List<User> getAllUsers() {
        return userDao.getAllUsers();
    }
}

把上边包车型地铁pom文件拷贝到新建筑工程程的pom.xml里,让maven下载所需的重视包

JSP

// index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
<h2>Hello World!</h2>
<sf:form method="post" modelAttribute="user" action="/toJson">
  用户名:<sf:input path="username"/>
  密码:<sf:password path="password"/>
  <input type="submit" value="提交">
</sf:form>
</body>
</html>

// nice.jsp
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/10/9
  Time: 8:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>nice to meet you!</title>
</head>
<body>
<br/>
<div>
  ${result}
</div>

</body>
</html>

JSP

// index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
<h2>Hello World!</h2>
<sf:form method="post" modelAttribute="user" action="/toJson">
  用户名:<sf:input path="username"/>
  密码:<sf:password path="password"/>
  <input type="submit" value="提交">
</sf:form>
</body>
</html>

// nice.jsp
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/10/9
  Time: 8:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>nice to meet you!</title>
</head>
<body>
<br/>
<div>
  ${result}
</div>

</body>
</html>

介意上边的groupid 和 artifactId要跟你成立工程时填写的同等

工程全体布局

图片 24

工程一体化布局

图片 25

4.0.0lemonlemon-ssmwar1.0-SNAPSHOTlemon-ssm Maven
Webapp

数据库脚本

// ssm.sql
/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50554
Source Host           : localhost:3306
Source Database       : ssm

Target Server Type    : MYSQL
Target Server Version : 50554
File Encoding         : 65001

Date: 2017-10-22 18:19:30
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'guo', '111');
INSERT INTO `user` VALUES ('2', 'root', 'aaa');
INSERT INTO `user` VALUES ('3', '11111', '22222');

数据库脚本

// ssm.sql
/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50554
Source Host           : localhost:3306
Source Database       : ssm

Target Server Type    : MYSQL
Target Server Version : 50554
File Encoding         : 65001

Date: 2017-10-22 18:19:30
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'guo', '111');
INSERT INTO `user` VALUES ('2', 'root', 'aaa');
INSERT INTO `user` VALUES ('3', '11111', '22222');
  1. 运用mybatis的逆向变化学工业具生成mapper接口和model实体

首先在resource下添加generatorConfig.xml

PUBLIC “-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN”

“;

NUME奔驰M级IC 类型剖判为java.math.BigDecimal –>

–>

第一比较最上端的体系目录结构把尚未的公文夹创制好,然后在编辑器的侧面贰遍按序号点击

图片 26

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图