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

相关环境

搭建步骤

创建项目工程

1、创建工程,选择Maven
创建工程

2、填写项目信息
项目名称填写

Maven选择

位置选择

初始化配置

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

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

点击所需版本。如图:
具体版本信息及pom.xml配置
里面的dependency即为所需标签。

总的配置文件pom.xml添加依赖包信息如下:


4.0.0
SSMTestProject
SSMTestProject
war
1.0-SNAPSHOT
SSMTestProject Maven Webapp
http://maven.apache.org


junit
junit
3.8.1
test


org.springframework
spring-core
4.2.5.RELEASE


com.fasterxml.jackson.core
jackson-core
2.7.2


org.springframework
spring-context
4.2.5.RELEASE


javax.servlet.jsp
jsp-api
2.2


jstl
jstl
1.2


org.springframework
spring-web
4.2.5.RELEASE


org.springframework
spring-webmvc
4.2.5.RELEASE


org.springframework.data
spring-data-jpa
1.9.4.RELEASE


org.hibernate.javax.persistence
hibernate-jpa-2.0-api
1.0.1.Final


org.hibernate
hibernate-entitymanager
5.1.0.Final


javax.servlet
servlet-api
2.5


mysql
mysql-connector-java
5.1.38


org.json
json
20160212


com.fasterxml.jackson.core
jackson-core
2.7.2


com.fasterxml.jackson.core
jackson-databind
2.7.2


org.mybatis
mybatis
3.3.1


org.mybatis
mybatis-spring
1.2.4



SSMTestProject


2、web配置

web.xml配置添加如下信息:


SSMTestProject

myspring
org.springframework.web.servlet.DispatcherServlet
1


myspring
/


encodingFilter
org.springframework.web.filter.CharacterEncodingFilter

encoding
UTF-8


forceEncoding
true



encodingFilter
/*

使用spring框架的默认DispatcherSerlet。load-on-starup标签表示servlet的启用时间,servlet-name指定了serevlet配置文件myspring。url -pattern是指所有路径均会被该servlet拦截。而filter一句是防止中文乱码,启用uft-8。

配置Servlet myspring-servlet.xml



<context:component-scan base-package="com.ssm.controller"/>


mvc:default-servlet-handler/


mvc:annotation-driven/








log4j.xml 配置文件如下:


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

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">











</log4j:configuration>

3、mybatis配置
可以使用注解或者xml的方式配置sql操作,这里使用注解方式:

// config.xml

















使用xml方式:

// userMapper.xml






insert into user(username,password) values(#{username},#{password})

Java类

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

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


Hello World!


<sf:form method="post" modelAttribute="user" action="/toJson">
用户名:<sf:input path="username"/>
密码:<sf:password path="password"/>

</sf:form>

// 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" %>


nice to meet you!





${result}


工程整体结构

工程整体结构

数据库脚本

// 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 @ 2017-10-22 18:27  KeepGulp  阅读(8564)  评论(6)    收藏  举报