IDEA搭建SpringMVC+Mybatis+Mysql+Maven框架

时间:2022-10-11 22:50:17

相关环境

搭建步骤

创建项目工程

1、创建工程,选择Maven

IDEA搭建SpringMVC+Mybatis+Mysql+Maven框架

2、填写项目信息

IDEA搭建SpringMVC+Mybatis+Mysql+Maven框架

IDEA搭建SpringMVC+Mybatis+Mysql+Maven框架

IDEA搭建SpringMVC+Mybatis+Mysql+Maven框架

初始化配置

1、Maven配置

先说Maven的项目依赖配置文件pom.xml,我们进入mvn repository 查找需要搜索的包结果如图:

IDEA搭建SpringMVC+Mybatis+Mysql+Maven框架

点击进入第一个搜索结果,然后各种版本

IDEA搭建SpringMVC+Mybatis+Mysql+Maven框架

点击所需版本。如图:

IDEA搭建SpringMVC+Mybatis+Mysql+Maven框架

里面的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>

Java类

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

IDEA搭建SpringMVC+Mybatis+Mysql+Maven框架

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

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>

工程整体结构

IDEA搭建SpringMVC+Mybatis+Mysql+Maven框架

数据库脚本

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