最近把j2e的基础学了,不敢说精通,但我想尽快摸清java开发的套路,接触更多东西,故选择学习ssm框架。通过不断实践的方式来掌握更多知识。
声明:本系列文章全都是在什么都不懂的前提下不断摸索踩坑。本人一般看不下那些巨厚的教程书,我选择通过实践操作,再结合书籍、前人博客等资料来深入学习。但网络上无论有多少教程,自己操作时一定一定会遇到各种问题,还是要记录一下。
ssm框架是spring+springMVC+myBatis,一套近来很火的java互联网轻量级开发框架,有取代ssh的趋势。构建ssm项目的第一步是搭建开发框架,各种导包、配置文件。本次我使用工具有:idea2018.1.4,maven,tomcat9.07,jdk8,操作系统为manjaroKDE(一种linux,不重要)。主要参考了这个博客。
补充更新
- 在IDEA中添加tomcat时没有tomcat可选。解决方法:打开File-setting-搜索tomcat-在Plugins右边勾选tomcat。
- 在IDEA中运行tomcat的时提示没有权限。解决方法:打开终端,进入tomcat\bin目录,然后执行chmod 777 *.sh
新建maven项目
首先创建maven项目:选择Maven项目,更方便管理。勾选Create form archetype,选择下方带webapp的,next。注意观察图片。
填写GroupId,一般是网站的倒写,这里我填com.ssm.learn。ArtifactId为项目名称,这里我起名webssm。Version为本项目版本,一般不需要改。这些都会在下面的配置文件中体现。图没截到。
这里添加一行,name=archetypeCatalog,value=internal。防止maven更新,加载速度更快。文件结构及代码,注意修改以对应自己的项目
目录main下新建文件夹java、resources(貌似以前resources自动生成,但idea2018没有,要自己建)。目录src下新建文件夹test,test下新建文件夹java。结构如图:打开File-Project Structure-Modules,可以看到右边有4个标记结构目录。
修改pom.xml,maven会根据这个配置文件自动下载所需的jar包,包括spring包,mabatis等。这里给出的我的代码也是拿别人的,记住要经过仔细修改才能对应与自己的项目。
<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>com.ssm.learn</groupId> <!--改成自己的groupId-->
<artifactId>webssm</artifactId> <!--改成自己的项目名-->
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>webssm Maven Webapp</name> <!--前面改成自己的groupId-->
<url>http://maven.apache.org</url>
<properties>
<!-- 设置项目编码编码 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- spring版本号 -->
<spring.version>4.3.5.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.4.1</mybatis.version>
</properties>
<dependencies>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- 实现slf4j接口并整合 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.2</version>
</dependency>
<!-- JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
<!-- 数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
<scope>runtime</scope>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring整合包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
<build>
<!--改这里,项目名-->
<finalName>webssm</finalName>
</build>
</project>
接下来各种新建包,class,xml,properties文件。与图片中的目录结构对应,缺就建。注意再建spring-mvc.xml和spring-mybatis.xml文件时,idea的上面有提示配置,点击进去按照默认点ok就行。如图:
接下来打代码,过程中按照自己的项目修改import的包名,如有出错可以等全部代码打完再看错误点。记得根据提示引入javaEE 6的包,不然servlet报错:
UserController.java
package com.ssm.learn.controller;
import javax.servlet.http.HttpServletRequest;
import com.ssm.learn.pojo.User;
import com.ssm.learn.service.IUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private IUserService userService;
@RequestMapping("/showUser.do")
public void selectUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
long userId = Long.parseLong(request.getParameter("id"));
User user = this.userService.selectUser(userId);
ObjectMapper mapper = new ObjectMapper();
response.getWriter().write(mapper.writeValueAsString(user));
response.getWriter().close();
}
}
UserDao.xml(再dao.mapper目录下,是mybatis框架配合IUserDao的接口通过xml中的sql语句操作数据库,具体使用请了解mybatis)
<?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">
<!-- 设置为IUserDao接口方法提供sql语句配置,这个xml是mybatis的使用方式 -->
<mapper namespace="com.ssm.learn.dao.IUserDao">
<select id="selectUser" resultType="User" parameterType="long">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
IUserDao.java
package com.ssm.learn.dao;
import com.ssm.learn.pojo.User;
//mybatis框架,interface配合xml
public interface IUserDao {
User selectUser(long id);
}
User.java(简单java类,包含getter和setter)
package com.ssm.learn.pojo;
public class User {
private long id;
private String password;
private String username;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
UserServiceImpl.java(在service.impl目录下)
package com.ssm.learn.service.impl;
import com.ssm.learn.dao.IUserDao;
import com.ssm.learn.pojo.User;
import com.ssm.learn.service.IUserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service("userService")
public class UserServiceImpl implements IUserService {
@Resource
private IUserDao userDao;
public User selectUser(long userId) {
return this.userDao.selectUser(userId);
}
}
IUserService.java
package com.ssm.learn.service;
import com.ssm.learn.pojo.User;
public interface IUserService {
public User selectUser(long userId);
}
先在mysql命令行中建立一个测试数据库ssmtest
create database ssmtest;
使用idea的数据库工具连接数据库。
编写测试用ssmtest.sql文件。
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`password` varchar(255) NOT NULL COMMENT '用户密码',
`username` varchar(255) NOT NULL COMMENT '用户昵称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', '123', 'test');
SET FOREIGN_KEY_CHECKS=1;
jdbc.properties(数据库配置文件,填写数据库名,用户名,密码)
jdbc.driver=com.mysql.jdbc.Driver
#数据库地址(下面的ssmtest是我的测试用数据库,自行修改)
jdbc.url=jdbc:mysql://127.0.0.1:3306/ssmtest?useUnicode=true&characterEncoding=utf8
#用户名
jdbc.username=自己数据库用户名,一般为root
#密码
jdbc.password=自己数据库密码
#最大连接数
c3p0.maxPoolSize=30
#最小连接数
c3p0.minPoolSize=10
#关闭连接后不自动commit
c3p0.autoCommitOnClose=false
#获取连接超时时间
c3p0.checkoutTimeout=10000
#当获取连接失败重试次数
c3p0.acquireRetryAttempts=2
配置文件spring-mvc.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-3.0.xsd">
<!-- 扫描web相关的bean -->
<context:component-scan base-package="com.ssm.learn.controller"/>
<!-- 开启SpringMVC注解模式 -->
<mvc:annotation-driven/>
<!-- 静态资源默认servlet配置 -->
<mvc:default-servlet-handler/>
<!-- 配置jsp 显示ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
配置文件spring-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"
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/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">
<!-- 扫描service包下所有使用注解的类型 -->
<context:component-scan base-package="com.ssm.learn"/>
<!-- 配置数据库相关参数properties的属性:${url} -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
</bean>
<!-- 配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 扫描model包 使用别名 -->
<property name="typeAliasesPackage" value="com.ssm.learn.pojo"/>
<!-- 扫描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations" value="classpath:com/ssm/learn/dao/mapper/*.xml"/>
</bean>
<!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.ssm.learn.dao"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置基于注解的声明式事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
web.xml文件(在webapp.WEB-INF下)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>ChatRobot</display-name>
<description>ChatRobot_Alpha_0.0.1</description>
<!-- 编码过滤器 -->
<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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置DispatcherServlet -->
<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:spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<!--<servlet>-->
<!--<servlet-name>UserController</servlet-name>-->
<!--<servlet-class>com.ssm.learn.controller.UserController</servlet-class>-->
<!--</servlet>-->
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 匹配所有请求,此处也可以配置成 *.do 形式 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
index.html(先用一个html测试一下)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<script>
function selectUser() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("test").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "user/showUser.do", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("id=1");
}
</script>
<body>
<p id="test">Hello World!</p>
<button type="button" onclick="selectUser()">onclick test</button>
</body>
</html>
配置tomcat服务器
添加tomcat服务器,点击:
运行效果
运行效果1:结束语
搭建ssm框架是项目的第一步。我在搭这个时找了很多博客,资料,每个人的博客或多或少有不知。我希望通过这次记录一下搭建框架的流程,给后来者帮助。
参考资料
//www.greatytc.com/p/8e307939dd67
https://blog.csdn.net/u010740881/article/details/79480500
https://blog.csdn.net/qq598535550/article/details/51703190