创建项目
打开IDEA
-File
-Project
项目大致目录
项目目录类型
修改pom.xml
添加maven依赖
<properties>
<!-- 设置项目编码编码 -->
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<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>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.5</version>
</dependency>
<!-- 实现slf4j接口并整合 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<!-- JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-ssm</finalName>
</build>
配置DispatcherServlet
有关DispatcherServlet前端控制器的文章可以查看SpringMVC之DispatcherServlet前置控制器
编辑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>ssm</display-name>
<!--添加防止乱码的过滤器-->
<filter>
<!--过滤器名称-->
<filter-name>SetCharacterEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--设置CharacterEncodingFilter属性-->
<!--encoding属性-->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!--forceEncoding属性-->
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!--映射过滤器-->
<filter-mapping>
<!--使用哪个过滤器-->
<filter-name>SetCharacterEncoding</filter-name>
<!--配置全局路由需要使用这个过滤器-->
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置 DispatcherServlet 调度器-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--初始化 DispatcherServlet-->
<!-- SpringMVC通过web.xml文件中servlet标签下的DispatcherServlet类完成自身的初始化-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!--映射所有请求到 DispatcherServlet 调度器-->
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 默认首页 -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
在这里提一嘴,很多同学不太明白拦截器
和过滤器
的区别,现在跟大家解释一下两者的区别:
- 拦截器是基于Java的反射机制的,而过滤器则是基于函数的回调
- 拦截器是实现HandleInterceptor,过滤器则是实现Filter接口
- 拦截器不依赖于Servlet容器,过滤器依赖于Servlet容器
- 拦截器使用来验证请求,能截断请求。过滤器用来设置request,response参数、属性,侧重对数据的过滤
- 过滤器在拦截器之前执行
- 过滤器是tomcat服务器创建的对象,拦截器是springmvc容器创建的对象
- 过滤器可以处理jsp、js、html等;拦截器是侧重拦截Controller的对象,如果你的请求不能被DispatcherServlet接收,这个请求不会执行拦截器的内容
- 拦截器可以获取IOC容器中的各个bean,而过滤器就不行,这点很重要,在拦截器里注入一个service,可以调用业务逻辑
配置SpringMVC
在classpath
目录下也就是resources
目录下新增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.xsd ">
<!--扫描控制器的包路径-->
<context:component-scan base-package="com.bystart.ssm.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>
集成MySQL、MyBatis
同样是是在resources
目录下,首先先创建mysql
的连接配置文件jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
#数据库地址
jdbc.url=jdbc:mysql://127.0.0.1:3306/ssmdb?useUnicode=true&characterEncoding=utf8&useSSL=false
#用户名
jdbc.username=root
#密码
jdbc.password=123456
#最大连接数
c3p0.maxPoolSize=30
#最小连接数
c3p0.minPoolSize=10
#关闭连接后不自动commit
c3p0.autoCommitOnClose=false
#获取连接超时时间
c3p0.checkoutTimeout=10000
#当获取连接失败重试次数
c3p0.acquireRetryAttempts=2
继续添加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">
<!--配置数据库相关信息-->
<!--读取数据库的连接配置信息-->
<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"/>
<!--扫描entity包 使用别名-->
<property name="typeAliasesPackage" value="com.bystart.ssm.model"/>
<!--扫描mapper文件-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!--配置事务管理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据连接池-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置使用注解声明式事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--扫描Dao接口包 自动注入到spring容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--dao接口包路径-->
<property name="basePackage" value="com.bystart.ssm.dao"/>
</bean>
<!--扫描dao包下所有使用注解的类型-->
<context:component-scan base-package="com.bystart.ssm.dao"/>
<!--扫描service包下所有使用注解的类型-->
<context:component-scan base-package="com.bystart.ssm.service"/>
</beans>
添加日志输出
新增logback-spring.xml
同样是在resources
目录下
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
实战从数据库查询数据
数据库表结构:
CREATE TABLE `sys_user` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
`username` varchar(32) NOT NULL COMMENT '用户名',
`password` varchar(32) NOT NULL COMMENT '密码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
插入数据:
INSERT INTO `sys_user` (`id`, `username`, `password`) VALUES (1, 'sysadmin', '123456');
编写数据表对应的JavaBean
在包路径com.bystart.ssm.model
下创建数据库表对应的Java类实体
package com.bystart.ssm.model;
public class SysUserEntity {
/**
* 自增id
*/
private Long id;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
public SysUserEntity() {
}
public SysUserEntity(Long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = 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;
}
@Override
public String toString() {
return "SysUserEntity{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
编写数据交互层DAO
在包com.bystart.ssm.dao
路径下添加接口
package com.bystart.ssm.dao;
import com.bystart.ssm.model.SysUserEntity;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
public interface SysUserDao{
/**
* 查询所有的用户
* */
List<SysUserEntity> getUserList();
/**
* 根据用户名查询指定用户
* */
SysUserEntity getUserByUsername(@Param("username") String username);
}
编写SysUserDao.xml
在resources
-mapper
目录下新增SysUserDao.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.bystart.ssm.dao.SysUserDao">
<select id="getUserList" resultType="com.bystart.ssm.model.SysUserEntity">
select * from sys_user
</select>
<select id="getUserByUsername" resultType="com.bystart.ssm.model.SysUserEntity">
select *
from sys_user
where username = #{username}
</select>
</mapper>
编写业务层接口
在com.bystart.ssm.service
新增SysUserService
接口,并提供两个方法
package com.bystart.ssm.service;
import com.bystart.ssm.model.SysUserEntity;
import java.util.List;
public interface SysUserService {
/**
* 查询所有的用户
* */
List<SysUserEntity> getUserList();
/**
* 根据用户名查询用户的信息
* @param username 用户名查询条件
* */
SysUserEntity getUserByUsername(String username);
}
添加service
的实现类,在com.bystart.ssm.service.impl
包下新增SysUserServiceImpl
实现类
package com.bystart.ssm.service.impl;
import com.bystart.ssm.dao.SysUserDao;
import com.bystart.ssm.model.SysUserEntity;
import com.bystart.ssm.service.SysUserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class SysUserServiceImpl implements SysUserService {
@Resource
private SysUserDao dao;
@Override
public List<SysUserEntity> getUserList() {
return dao.getUserList();
}
@Override
public SysUserEntity getUserByUsername(String username) {
return dao.getUserByUsername(username);
}
}
编写controller
com.bystart.ssm.controller
包下新增SysUserController
package com.bystart.ssm.controller;
import com.bystart.ssm.model.SysUserEntity;
import com.bystart.ssm.service.SysUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
@Controller
public class SysUserController {
@Resource
private SysUserService service;
/**
* 查询用户列表并返回到JSP进行数据渲染
*/
@RequestMapping("/getUserList")
public String getUserList(Model model) {
List<SysUserEntity> userList = service.getUserList();
model.addAttribute("userList", userList);
// 返回到 webapp目录下的 WEB-INF > views > userList.jsp
return "userList";
}
/**
* 根据用户名查询指定用户
* 将查询到的数据以json形式返回到页面
*
* @param username 用户名
*/
@RequestMapping("/getUserByUsername")
@ResponseBody
public SysUserEntity getUserByUsername(@RequestParam String username) {
SysUserEntity user = service.getUserByUsername(username);
return user;
}
}
编写JSP页面
在webapp -> WEB-INF -> views
目录下新增userList.jsp
:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: bystart
Date: 2023/7/6
Time: 15:32
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<table border=1>
<thead>
<tr>
<th>序号</th>
<th>用户名</th>
<th>密码</th>
</tr>
</thead>
<tbody>
<c:forEach items="${userList}" var="user">
<tr>
<th>${user.id}</th>
<th>${user.username}</th>
<th>${user.password}</th>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
配置tomcat
配置好tomcat后即可运行起来
测试发起请求获得数据
我们编写的SysUserController
中有两个接口,一个会返回页面,一个会返回json数据
我们在浏览器中请求http://localhost:8080/ssm/
此处的地址可以在这里查看
在浏览器访问http://localhost:8080/ssm/getUserList
再去访问http://localhost:8080/ssm/getUserByUsername?username=sysadmin
如果能跟我一样正常显示,说明ssm框架搭建完成,并且可以跟数据库进行交互
评论 (0)