程序员

IntelliJ IDEA spring mvc +mybati

2016-03-20  本文已影响5675人  nothingwxq

这里使用的是xml配置mybatis,如喜欢注解,请待下一篇。

1 修改配置,引入json、mybatis

在pom.xml中添加mybatis-spring、mybatis、mysql-connector-java(用于mysql连接)、jackson-core、jackson-databind(用于返回对象直接映射成json),整体工程现在配置如下:

<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.nothing</groupId>
  <artifactId>hellospringmvc</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>hellospringmvc 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>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</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>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.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>

    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20160212</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>hellospringmvc</finalName>
  </build>
</project>

2 上篇的myspring-servlet.xml 和web.xml 不用修改。

3 配置mybatis conf.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/mysql" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="userMapper.xml" />
    </mappers>

</configuration>

需要注意的是,如下与jdbc连接的代码差不多的,这里使用xml配置,由于我使用的是mysql(如使用其他数据库请百度),url中为数据库的名称,我这里是mysql。后面两项是username 和password需自行配置。
这里需要注意路径:本文放在src/main/resources 目录下。我在这卡了很久。

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.nothing.Model.User">
        select * from user_nothing where id = #{id}
    </select>
    <insert id="addUser" parameterType="com.nothing.Model.User">
            insert into user_nothing(username,password) values(#{username},#{password})
    </insert>
</mapper>

这里使用xml配置sql语句。user_nothing 在mysql数据库中创建的表。三个字段,待会给出。parameterType为输入参数 id的类型int,esultType="com.nothing.Model.User"为返回值User对象。

4 User

package com.nothing.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() {
    }

}

5 UserDao

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

UserDaoImpl 才是正真的实现类,参与数据库curd,本文只有简单的单个查询。

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

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

UserService中间层,负责dao与controller交互,本文较简单,可省略。

public interface IUserService {
    public User findUserById(int id);
    public void addUser(User user);
}

UserServiceImpl真正实现

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

6 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>

这里使用jstl标签库。

7 最后看一眼MainController,实现是用户到/hello 页面就跳到index .jsp 页面,在该页面注册后,。然后action动作toJson,返回id为2的用户

@Controller
public class MainController {
    private IUserService service = new UserServiceImpl();
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String index( User user) {
        return "index";
    }
  
    @RequestMapping(value ="/toJson",method=RequestMethod.POST)
    @ResponseBody
    public User toJson(User user){
        service.addUser(user); //一起测试了
        return service.findUserById(2);
    }

}

整个工程的架构如图:

框架.png

另外我使用mysql的可视化管理工具navicat:

mysql.png

最后运行截图:

run1.png run2.png
上一篇下一篇

猜你喜欢

热点阅读