idea创建SSM项目(Spring+SpringMVC+MyBatis)
本人小白一个,如果有错误的地方,欢迎指正
项目创建
点击next
选择本地配置好的maven(maven配置可查看相关博客),点击finish
复制粘贴 dependencies标签内的内容就好
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mybatis_test</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>mybatis_test Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--Hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.6.5</version>
</dependency>
<!--LomBok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
<!-- Spring+SpringMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.8.RELEASE</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 事务管理 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<!-- Spring的jdbc模块 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<!-- 做jdbc的连接管理 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
<!-- jsp-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<!-- MyBatis-Spring连接包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
<!-- 日志管理 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.13</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
配置好之后点一下右上角的按钮,开始下载相关的jar包
右键src,选择new,directory
创建这四个文件夹(如果不需要测试的话,也可以只创建main下的两个)
那现在这就是我们暂时的目录结构
创建数据库
/* 创建mybatis数据库 */
create database mybatis;
use mybatis;
/* 创建用户表 */
create table user
(
id int auto_increment,
username varchar(255) not null,
password varchar(255) not null,
constraint primary key (id)
);
/* 创建角色表 */
create table role(
id int auto_increment,
name varchar(255) not null ,
constraint primary key (id)
);
/* 创建用户-角色详情表 */
create table userinfo(
id int auto_increment,
user_id int not null ,
role_id int not null ,
constraint primary key (id)
);
解释一下这三个表之间的关系
这里我并没有设置外键约束,其实设置一下也没问题。
有人可能不太理解role表的含义,这里我解释一下,类似权限的划分。
是游客用户?还是普通用户?或者是VIP用户?
/* 插入几个数据 */
insert into user (username, password) values ('abc','123');
insert into user (username, password) values ('admin','123456');
insert into role (name) values ('tourist');
insert into role (name) values ('common');
insert into userinfo (user_id, role_id) values (1,1);
insert into userinfo (user_id, role_id) values (1,1);
insert into userinfo (user_id, role_id) values (2,1);
自动生成mapper
这里需要下载几个jar包
链接:https://pan.baidu.com/s/1KZyUXrCZ6DU0V2frbk8aew?pwd=lej6
提取码:lej6
改好xml之后,复制mybatis自动生成命令,输入cmd+回车
(也可以用cmd cd到当前auto目录,也可以选中auto+按住shift+右键选择cmd/powershell打开)
输入命令后回车,看到successfully表示生成成功了
如果有其他情况,没有successfully,可能是generatorConfig.xml出错了,找不到数据库/表
直接将生成的com.XXX.domain/mapper复制粘贴到java下
稍微修改一下目录结构(在resources下新建mapper文件夹,将xml文件全部移到mapper文件夹内)
这里三个实体类自动生成了get和set方法,但其实可以用pom.xml里下载好的lombok插件来配置
public class Role {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Role {
private Integer id;
private String name;
}
/* 感兴趣的可以去搜一下lombok的注解
@Data、@AllArgsConstructor、@NoArgsConstructor
这里我们就这么配置
*/
// user
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String username;
private String password;
// 注意:这里我添加了一个属性
private List<UserInfo> userInfoList;
}
// role
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Role {
private Integer id;
private String name;
// 注意:这里我添加了一个属性
private List<UserInfo> userInfoList;
}
// userinfo
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserInfo {
private Integer id;
private Integer userId;
private Integer roleId;
}
先做一个简单的测试
我们可以上网找一下返回结果工具类(下面也提供了一个不完全的)
在com.XXX下新建一个util文件夹(idea右键,new,directory//也可以直接在外面项目文件夹新建)
package com.twh.util;
import java.io.Serializable;
public class Result<T> implements Serializable {//返回的结果集类
private Integer code;//服务器响应的状态 不是http状态
private String msg;//备注
private T data;//返回的数据
public Result() {
}
public Result(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public Integer getCode() {
return code;
}
public Result setCode(Integer code) {
this.code = code;
return this;
}
public String getMsg() {
return msg;
}
public Result setMsg(String msg) {
this.msg = msg;
return this;
}
public T getData() {
return data;
}
public Result setData(T data) {
this.data = data;
return this;
}
@Override
public String toString() {
return "Result{" +
"code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
public Result setCode(com.twh.util.ResultEnum resultEnum) {
this.code = resultEnum.code;
return this;
}
}
//--------------------------------------------
package com.twh.util;
public enum ResultEnum {//枚举类
/**
* 成功
*/
SUCCESS(200),
/**
* 失败
*/
FAIL(400),
/**
* 接口不存在
*/
NOT_FOUND(404),
/**
* 服务器内部错误
*/
INTERNAL_SERVER_ERROR(500);
public int code;
ResultEnum(int code) {
this.code = code;
}
}
//-----------------------------------------
package com.twh.util;
import com.twh.util.Result;
import com.twh.util.ResultEnum;
public class ResultUtil {
public static <T> Result<T> defineSuccess(Integer code, T data) {
Result result = new Result<>();
return result.setCode(code).setData(data);
}
public static <T> Result<T> success(T data) {
Result result = new Result();
result.setCode(ResultEnum.SUCCESS).setData(data);
return result;
}
public static <T> Result<T> fail(String msg) {
Result result = new Result();
result.setCode(ResultEnum.FAIL).setMsg(msg);
return result;
}
public static <T> Result<T> defineFail(int code, String msg){
Result result = new Result();
result.setCode(code).setMsg(msg);
return result;
}
public static <T> Result<T> define(int code, String msg, T data){
Result result = new Result();
result.setCode(code).setMsg(msg).setData(data);
return result;
}
}
这里遇到了奇奇怪怪的报错,设置有点问题
设置为8,点击OK,错误消除了
新建impl
新建controller
以下配置 可参考博客https://blog.csdn.net/weixin_45301250/article/details/121298472(我已省略)
<!-- mybatis-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>
<settings>
<!-- mybatis通过日志来打印sql语句 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="useGeneratedKeys" value="true"/>
</settings>
<!--设置别名-->
<typeAliases>
<package name="com.twh.domain"/>
</typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"/>
</plugins>
<!--绑定mapper映射文件-->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
<mapper resource="mapper/UserInfoMapper.xml"/>
<mapper resource="mapper/RoleMapper.xml"/>
</mappers>
</configuration>
那么,基本配置到此结束,开始编写代码
// usermapper.java
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User row);
int insertSelective(User row);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User row);
int updateByPrimaryKey(User row);
List<User> getAllUsers();
// 根据账号查找用户
User selectByUsername(@Param("username") String username);
// 根据user id查找对应的多个userinfo
User selectUserInfoByUsername(@Param("username") String username);
}
<!-- usermapper.xml -->
<select id="getAllUsers" resultType="User">
select id,username,password from user;
</select>
<select id="selectByUsername" parameterType="java.lang.String" resultType="User">
select id,username,password from user where username=#{username};
</select>
<select id="selectUserInfoByUsername" parameterType="java.lang.String" resultMap="UserInfoByUserId">
select u.id,username,password,info.id,info.user_id,info.role_id from user u join userinfo info where info.user_id in (select u.id from user s where u.username=#{username});
</select>
<resultMap id="UserInfoByUserId" type="User">
<result property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<collection property="userInfoList" ofType="UserInfo">
<result property="id" column="id"/>
<result property="userId" column="user_id"/>
<result property="roleId" column="role_id"/>
</collection>
</resultMap>
</mapper>
// mytest.java
public class MyTest {
// 获取全部users
@Test
public void test1(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.getAllUsers();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
// 获取指定账号的user
@Test
public void test2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectByUsername("admin");
System.out.println(user);
sqlSession.close();
}
// 获取指定user账号的userinfo
@Test
public void test3(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectUserInfoByUsername("abc");
System.out.println(user);
sqlSession.close();
}
}
这里可以查到user id对应的userinfo 的内容(直接在MyTest下test1、test2、test3处点击运行即可)
这是运行test1(test2、test3就分别在他们的方法内右键运行)
暂时MyBatis相关配置已经成功了
更改一些配置文件,删除了一些配置
接下来配置其他的
在resources下再额外新建两个xml文件(springmvc.xml applicationContext.xml)
<!-- applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.twh.*">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 1.管理数据库连接,使用数据库连接池的方式 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 2.获得sqlsessionFactory -->
<bean id="sqlsessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
</bean>
<!-- 3.扫描mapper.xml文件,获得mapper对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.twh.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlsessionFactory"></property>
</bean>
<!-- 4.管理事务 DML操作:增删改 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
</beans>
<!-- springmvc.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:component-scan base-package="com.twh.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
这个xml是原本就有得,现在需要进行一些配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Archetype Created Web Application</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 自定义springmvc的配置文件路径 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter><!-- post/put -->
<filter-name>CharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
这里的配置与applicationContext.xml的配置重复了,注释掉,不然会报错
实现登录功能
// userservice
public interface UserService {
Object login(User user);
}
//---------------------------------------------------------------
// userserviceImpl
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public Object login(User user) {
String username=user.getUsername();
String password=user.getPassword();
// 需要导入hutool工具类才能这么写
if(StrUtil.hasEmpty(username,password)){
return ResultUtil.fail("账号或密码为空");
}
// 否则得这样写
// if(username==null||username.equals("")||password==null||password.equals(""))
User u=userMapper.selectByUsername(username);
if(u==null){
return ResultUtil.fail("账号未注册");
}else {
if(u.getPassword().equals(password)){
return ResultUtil.success("登陆成功");
}else {
return ResultUtil.fail("密码错误");
}
}
}
}
//---------------------------------------------------------------
// usercontroller 这里写的有点low
// 暂时先这么写 编写一个html登录页面就可以传账号、密码进来了 后面会改用ajax来写
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public Object login(String username,String password) {
User user=new User();
user.setUsername(username);
user.setPassword(password);
return userService.login(user);
}
}
login.html建在webapp下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="user/login" method="post">
<label>账号:</label><input type="text" name="username" class="username" placeholder="账号"/><br>
<label>密码:</label><input type="password" name="password" class="password" placeholder="密码"/><br>
<input type="submit" value="登录"/>
</form>
</body>
</html>
删除后面的内容
开始运行
输入账号密码,登陆成功
这里我用了插件,json数据看起来会好看点(可以在网上搜浏览器json插件)
去bootstrap官网下了一个免费模板
链接:https://pan.baidu.com/s/1aLX8iJBdeeE2nQEXnVjBfw?pwd=94ky
提取码:94ky
这是登录页面
<script src="js/jquery.min.js"></script>
<!-- 这里在登录页面加了一个点击事件,只用复制粘贴 οnclick="login()"到页面该位置即可 -->
<button type="button" class="btn btn-block btn-primary" onclick="login()">Sign in
</button>
<script>
function login() {
let username = $("#input-email").val();
let password = $("#input-password").val();
let user = {
"username": username,
"password": password
};
$.ajax({
url: "user/login",
type: "post",
dataType: "json",
contentType:"application/json",
data: JSON.stringify(user),
success: function (message) {
console.log(message);
},
error: function (message) {
console.log("失败");
}
})
}
</script>
<!-- 打包一个user对象发给后端usercontrolller -->
// usercontroller改为下面的代码即可
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public Object login(@RequestBody User user) {
return userService.login(user);
}
}
打开F12,输入账号密码登录
其他业务方法也是类似写,发送ajax请求,通过对后端返回得code来进行判断是否成功,并进行相应的处理
全代码
链接:https://pan.baidu.com/s/1TvGHH6BISzQCYIJWIJwgxg?pwd=kqp5
提取码:kqp5