SSM框架(从0到发布)
作者:互联网
SSM(spring-springMVC-mybatis)
开发工具
idea2020.1.3
jdk1.8
centOS 7.x
navicat
xshell
xftp
以下部分均不包含软件安装和环境变量的配置,如果安装有问题请私信,近期会出一篇针对安装的问题
以下部分暂不包含部署问题,部署部分包含在我的另一篇博客 部署的文章
一、项目创建
1、新建项目,选中spring内的springMVC
2、输入项目名,我这里是testJava
2.1、可能会遇到代理的问题
2.1.1、可重试try again
2.1.2、点击Set up HTTP proxy settings。
点击后,在第二项添加华为Maven仓库https://mirrors.huaweicloud.com/repository/maven/
点击Try again
参照 https://blog.csdn.net/Y920036515/article/details/105982550
我是通过2.1.1的办法解决了
3、由于我们不通过tomcat启动服务,而是通过springApplication启动,所以不需要配置tomcat。
下载对应的包之后,右键项目名,Add Framwork Support
勾选maven,点击确定
4、修改groupId,build项目
以上就配置完一个带有SpringMVC+Maven 的项目了
二、配置mybatis以及数据库
1、新建mybatis配置文件applicationContext-myibatis.xml
2、添加mybatis配置的路径
3、通过xshell进入服务器,新建数据库
mysql -uroot -p
输入密码
CREATE DATABASE 数据库的名字;(这个分号一定要加,不加不执行)
创建完成后,使用navicat连接会显示这个数据库
4、新建表,并添加字段
这里的ID,我是自动递增,然后不能为空,其他的大家自由发挥
输入表名就可以了,我这里是t_user。
5、配置mybatis
resource下新增 mybatis.properties文件
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://xx.xx.xx.xx:端口号/XXXX?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
database.username=数据库名字
database.password=数据库密码
database.maxActive=100
database.maxWait=30000
database.maxIdle=5
sqlSessionFactory.configLocation=classpath:/mybatis/mybatis-config.xml
6、applicationContext.xml新增内容
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:刚刚创建的文件名字.properties</value> <!--指向数据库的配置文件-->
</list>
</property>
</bean>
7、新建sqlMapConfig.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>
<!-- 这个配置使全局的映射器启用或禁用缓存 -->
<setting name="cacheEnabled" value="true" />
<!-- 允许 JDBC 支持生成的键。需要适合[修改为:适当]的驱动。如果设置为true,则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如 Derby) -->
<setting name="useGeneratedKeys" value="true" />
<!-- 配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 -->
<setting name="defaultExecutorType" value="REUSE" />
<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 设置超时时间,它决定驱动等待一个数据库响应的时间 -->
<setting name="defaultStatementTimeout" value="25000"/>
<setting name="callSettersOnNulls" value="true"/>
<!--log4-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="lazyLoadingEnabled" value="true"></setting>
<setting name="aggressiveLazyLoading" value="false"></setting>
</settings>
</configuration>
7、新建包名,配置pom.xml文件,添加mybatis依赖
<?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>testJava</groupId>
<artifactId>testJava</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!--BasicDataSource-->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
</dependencies>
</project>
9、配置application'Context-mybatis.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"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:annotation-config/>
<!--
当有多个全局配置文件的时候,有可能会出现重复扫描导致出错
这里的 <context:component-scan base-package="com.tronrun.exhibition">
指定了要扫描的包名但是下面的
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
指定排除扫描所有加了@Controller注解的类 (排除 排除 排除)
-->
<context:component-scan base-package="com.javatest.beans">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--配置mybatis连接数据库的参数-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<!--连接池的最大数据库连接数 -->
<property name="maxActive" value="${database.maxActive}"/>
<!--最大等待连接中的数量 -->
<property name="maxIdle" value="${database.maxIdle}"/>
<!--最大等待毫秒数 -->
<property name="maxWait" value="${database.maxWait}"/>
<property name="defaultAutoCommit" value="true"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--引用数据库bean对象-->
<property name="dataSource" ref="dataSource"/>
<!--引用MyBatis的配置文件的文件路径
注意路径是否对,否者运行出错很难发现问题,切记-->
<property name="configLocation" value="WEB-INF/sqlMapConfig.xml"/>
<!--Mapper所在的文件路径(这里的*.xml表示所有.xml结尾的文件)
注意路径是否对,否者运行出错很难发现问题,切记-->
<!--Mapper文件的路径
注意路径是否对,否者运行出错很难发现问题,切记-->
<property name="mapperLocations" value="classpath*:com/javatest/mapper/*.xml"/>
</bean>
<!--Mapper扫描配置-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--basePackage扫描的路径
注意路径是否对,否者运行出错很难发现问题,切记-->
<property name="basePackage" value="com.javatest.mapper"></property>
<!--传入sqlSessionFactoryBeanName对象,指向的是上面配置的sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<!--对注入标签@Repository生效-->
<property name="annotationClass" value="org.springframework.stereotype.Repository"></property>
</bean>
</beans>
配置完成之后,这里会报错,暂时不管,等添加xml文件之后会消失
10、配置dispatch-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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 定义扫描装载控制器的包路径,排除用了@Service标签的类 -->
<context:component-scan base-package="com.javatest">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
<!-- 定义视图解析器,找到Web工程/WEB-INF/JSP文件夹,且文件结尾为jsp的文件作为映射 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter"></ref>
</list>
</property>
</bean>
<!--配置MappingJackson2HttpMessageConverter的编码方式防止中文乱码-->
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</beans>
三、配置实体类等文件
1、添加UserBean实体类
package com.javatest.beans;
public class UserBean {
private int id;
private String userName;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2、添加mapper.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="com.Lipt0n.test.Mapper.UserInfoMapper">
<insert id="addUser" parameterType="String">
insert into t_user (
id,username,age)
values (#{id},#{username},#{age})
</insert>
<delete id="deleteUser" parameterType="String">
delete from t_uer where id=#{id}
</delete>
<select id="getUser" parameterMap="com.javatest.beans.UserBean">
select * from t_user where id=#{id}
</select>
<update id="updateUser" parameterMap="String">
update t_user set username=#{username},age=#{age} where id=#{id}
</update>
</mapper>
3、添加UserMapper.class
package com.javatest.mapper;
import com.javatest.beans.UserBean;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper {
void addUser(int id,String username,int age);
void deleteUser(int id);
void updateUser(int id,String username,int age);
UserBean getUser(int id);
}
4、添加UserService.class
package com.javatest.service;
import com.javatest.beans.UserBean;
public interface UserService {
void addUser(UserBean bean);
void deleteUser(int id);
void updateUser(UserBean bean);
UserBean getUser(int id);
}
5、添加UserImpl.class
package com.javatest.impl;
import com.javatest.beans.UserBean;
import com.javatest.mapper.UserMapper;
import com.javatest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public void addUser(UserBean bean) {
userMapper.addUser(bean.getId(),bean.getUserName(),bean.getAge());
}
public void deleteUser(int id) {
userMapper.deleteUser(id);
}
public void updateUser(UserBean bean) {
userMapper.updateUser(bean.getId(),bean.getUserName(),bean.getAge());
}
public UserBean getUser(int id) {
return userMapper.getUser(id);
}
}
6、新建一个普通类BaseResultBean.class,用于返回基本类型等
package com.javatest;
public class BaseResultBean {
private int code;
private String msg;
private Object result;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
}
7、新建ctroller包名,并新建UserControll.class
package com.javatest.controller;
import com.javatest.BaseResultBean;
import com.javatest.beans.UserBean;
import com.javatest.service.UserService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserControll {
@Autowired
private UserService userService =null;
@RequestMapping(value = "/addUser",method = RequestMethod.POST)
//新增用户信息
public BaseResultBean insertUser(UserBean userBean) {
BaseResultBean resultBean = new BaseResultBean();
int code = userService.addUser(userBean);
resultBean.setCode(-1);
resultBean.setMsg("新增用户失败");
if (code==1){
resultBean.setCode(0);
resultBean.setMsg("新增用户成功");
}
return resultBean;
}
@RequestMapping(value = "/deleteUser",method = RequestMethod.GET)
//删除用户信息
public BaseResultBean deleteUser(UserBean userBean) {
BaseResultBean resultBean = new BaseResultBean();
int code = userService.deleteUser(userBean.getId());
resultBean.setCode(-1);
resultBean.setMsg("删除用户失败");
if (code==1){
resultBean.setCode(0);
resultBean.setMsg("删除用户成功");
}
return resultBean;
}
@RequestMapping(value = "/updateUser",method = RequestMethod.GET)
//修改用户信息
public BaseResultBean updateUser(UserBean userBean) {
BaseResultBean resultBean = new BaseResultBean();
int code = userService.updateUser(userBean);
resultBean.setCode(-1);
resultBean.setMsg("更新用户失败");
if (code==1){
resultBean.setCode(0);
resultBean.setMsg("更新用户成功");
}
return resultBean;
}
@RequestMapping(value = "/getUser",method = RequestMethod.GET)
//查询用户信息
public BaseResultBean getUser(UserBean userBean) {
BaseResultBean resultBean = new BaseResultBean();
UserBean bean = userService.getUser(userBean.getId());
resultBean.setCode(-1);
resultBean.setMsg("查询用户失败");
if (bean !=null ){
resultBean.setCode(0);
JSONObject jsonObject = JSONObject.fromObject(bean);
resultBean.setMsg(jsonObject.toString());
}
return resultBean;
}
}
8、新建tool包名,并新建JsonTools.class
package com.javatest.tool;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
public class JsonTools extends ObjectMapper {
private static final long serialVersionUID = 1L;
public JsonTools() {
super();
// 空值处理为空串
this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException {
jg.writeString("");
}
});
}
}
9、在dispatch-servlet.xml文件中新增内容,适配baseResult
<!-- 使用注解驱动 -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<!--封装好的适配器,把null的数据转成空字符-->
<bean class="com.javatest.tool.JsonTools">
<!-- 处理responseBody 里面日期类型 -->
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
</bean>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
四、准备打包运行,解决出现的问题
参考内容链接
https://www.jianshu.com/p/78a1cb4cefff?from=singlemessage
标签:框架,int,id,SSM,发布,resultBean,import,com,public 来源: https://blog.csdn.net/WalterZhoukick/article/details/112762862