IDEA Builds Spring MVC+Mybatis+Mysql+Maven Framework

Keywords: Java Apache xml log4j

Related environment

Steps to build

Creating Project Engineering

1. Create a project and choose Maven

2. Fill in project information

Initialization configuration

1. Maven configuration
Let's start with Maven's project dependency configuration file pom.xml. Let's enter mvn repository Find the package results that need to be searched as follows:

Click to enter the first search result, then various versions

Click on the version you want. As shown in the picture:

The dependency inside is the required label.

The general configuration file pom.xml adds dependency package information as follows:

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

The web.xml configuration adds the following information:

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

Use the default Dispatcher Serlet of the spring framework. The load-on-starup tag indicates the start-up time of the servlet, and servlet-name specifies the serevlet configuration file myspring. Url-pattern means that all paths will be intercepted by the servlet. The filter sentence is to prevent Chinese scrambling, uft-8 is enabled.

Configure 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">

    <!--To specify controller The package in question, and scan the annotations-->
    <context:component-scan base-package="com.ssm.controller"/>

    <!-- Static resources(js,image etc.)Visit -->
    <mvc:default-servlet-handler/>

    <!-- Open notes -->
    <mvc:annotation-driven/>

    <!--ViewResolver view resolver-->
    <!--For support Servlet,JSP View parsing-->
    <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>

The log4j.xml configuration file is as follows:

<?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 configuration
You can configure sql operations using annotations or xml, where annotations are used:

// 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:Development mode     work:Working mode -->
    <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>

Using 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">
    <!--according to ID Get the corresponding value  -->
    <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>

Java class

Create the folder java under the main folder and right-click java as the source folder:

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); //Tested together
        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); //query
    public void addUser(User user); //Add to
    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(); // Be sure to remember 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();
    }
}

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">
  User name:<sf:input path="username"/>
  Password:<sf:password path="password"/>
  <input type="submit" value="Submission">
</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>

Engineering Integral Structure

Database script

// 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');

Posted by priya_amb on Thu, 07 Feb 2019 19:03:17 -0800