写在开头的话:
难者不会会者不难,麻烦冗长
今日份的小曲是童丽阿姨的女儿情开始,她的歌温润婉转,少妇味。第一次听到她的女儿情时,直呼这是在女儿国录的音。
忘了发了,写了有好两天了,因为tyora到论坛图片需要手动点,当时就懒得上传,之后就忘了。
新建maven工程
创建文件夹,让它有一个大致的文件结构。
pom导入依赖
<?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>ssm4</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssm4 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<slf4j.version>1.7.25</slf4j.version>
<log4j.version>2.8.2</log4j.version>
<spring.version>4.3.14.RELEASE</spring.version>
<security.version>4.2.5.RELEASE</security.version>
</properties>
<dependencies>
<!--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-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-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</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-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!--spring完-->
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<!--spring依赖-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.10</version>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!-- Druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
<!--dbcp连接池-->
<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>
<!-- json配置-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0.pr3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0.pr3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0.pr3</version>
</dependency>
<!-- google的json格式支持 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<!--阿里fastJson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
<!-- freemarker -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<!--freemarker完-->
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--jstl-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--log4j2-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<!--核心log4j2jar包-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<!--用于与slf4j保持桥接-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j.version}</version>
</dependency>
<!--web工程需要包含log4j-web,非web工程不需要-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>${log4j.version}</version>
<scope>runtime</scope>
</dependency>
<!--需要使用log4j2的AsyncLogger需要包含disruptor-->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.7</version>
</dependency>
<!--log4j2完-->
<!--shiro-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.3.2</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.4.0</version>
<scope>compile</scope>
</dependency>
<!-- c3p0-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
</dependencies>
<build>
<finalName>ssm4</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
实体类和库一起写:
package zzzzmdzz.pojo;
import java.io.Serializable;
public class User implements Serializable {//序列化
private Integer id;
private Integer no;
private String name;
private String pass;
private String sex;
private Integer age;
private String dataTime;
//getset
dao和service,这里写完可以测试一下Spring框架,我为了让正文精简一点,私底下的测试不贴上来,你就知道写个applicationContext.xml和test执行就行。
package zzzzmdzz.dao;
import zzzzmdzz.pojo.User;
import java.util.List;
public interface UserDao {
public List<User> findAll();
public void saveUser(User user);
}
service
package zzzzmdzz.service;
import zzzzmdzz.pojo.User;
import java.util.List;
public interface UserService {
public List<User> findAll();//查询全部
public void saveUser(User user);//保存
}
package zzzzmdzz.service.Impl;
import org.springframework.stereotype.Service;
import zzzzmdzz.pojo.User;
import zzzzmdzz.service.UserService;
import java.util.List;
@Service("userService")
public class UserServiceImpl implements UserService {
@Override
public List<User> findAll(){
System.out.println("查询全部");
return null;
}
@Override
public void saveUser(User user){
System.out.println("保存");
}
}
controller:
package zzzzmdzz.controller;
public class UserController {
public String findAll(){
System.out.println("Fand All");
return "list";
}
}
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 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>Archetype Created Web Application</display-name>
<!--配置Spring监听器-->
<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>
<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>
<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>
</web-app>
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: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">
<!-- 扫描controller-->
<context:component-scan base-package="zzzzmdzz.controller"/>
<!-- 配置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/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--<!– 过滤资源–>-->
<!-- <mvc:resources mapping="/css/**" location="/css"/>-->
<!-- <mvc:resources mapping="/img/**" location="/img/"/>-->
<!-- <mvc:resources mapping="/js/**" location="/js/"/>-->
<!-- 开启SpringMVC注解模式 -->
<mvc:annotation-driven/>
<!-- 静态资源默认servlet配置 -->
<mvc:default-servlet-handler/>
</beans>
现在就可以写个index.jsp测试了
配置tomcat,执行。
现在开始,往这个框架里加东西。
web.xml加入监听器
<!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
<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>
controller加入调用:
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/user/findAll")
public String findAll(){
System.out.println("Fand All");
List<User> list= userService.findAll();
return "list";
代码不完整,自行补全吧,头头尾尾的。
在测试一下,控制台能看到这个:
至此,spring,springmvc写好。现在写MyBatis。
dao里加注解,这就是sql语句了,batis你好强大!
@Repository
public interface UserDao {
@Select("select * from user")
public List<User> findAll();
@Insert("insert into user (no,name,pass,sex,age) value(#{no},#{name},#{pass},#{sex},#{age})")
public void saveUser(User user);
数据库连接配置,里面的参数也按个人口味酌情更改
<?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>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///ssmuser"/>
<property name="username" value="root"/>
<property name="password" value="x5"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="zzzzmdzz.dao"/>
</mappers>
</configuration>
写个batis的test,并测试
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 org.junit.Test;
import zzzzmdzz.dao.UserDao;
import zzzzmdzz.pojo.User;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class TestMyBatis {
@Test
public void run2() throws IOException{
User user=new User();
user.setName("yyds");
user.setAge(114514);
user.setNo(4);
user.setPass("lbwnb");
user.setSex("futa");
// 加载配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 创建SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 创建SqlSession
SqlSession session = factory.openSession();
//获取代理对象
UserDao dao=session.getMapper(UserDao.class);
//保存
dao.saveUser(user);
//提交
session.commit();
//关闭
session.close();
in.close();
}
public void run3() throws Exception{
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory fac=new SqlSessionFactoryBuilder().build(in);
SqlSession se=fac.openSession();
UserDao dao=se.getMapper(UserDao.class);
List<User> list=dao.findAll();
for (User user:list){
System.out.println(user);
}
se.close();
in.close();
}
}
执行完了就会在数据库里加这么一项新的,有时候需要刷新一下数据库。
下一步,将mybatis的配置转移进spring。
即sqlmapconfig.xml里的数据库,连接池,dao接口包,装进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: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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 扫描service包下所有使用注解的类型 -->
<context:component-scan base-package="zzzzmdzz">
<!-- 不扫controller-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--Spring整合MyBatis框架-->
<!--配置连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///ssmuser"/>
<property name="user" value="root"/>
<property name="password" value="x5"/>
</bean>
<!--配置SqlSessionFactory工厂-->
<bean id="sqlSessonFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置Userdao接口所在包-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="zzzzmdzz.dao"/>
</bean>
</beans>
自己看看区别,把缺的东西粘过去吧。
在UserServiceImpl里添加Dao的调用。
public class UserServiceImpl implements UserService {
//@Override
@Autowired
// UserService userService;
private UserDao userDao;
public List<User> findAll(){
System.out.println("查询全部");
return userDao.findAll();
}
就是定义了个UserDao,然后return到findall。
controller层添加调用:
完善list.jsp,让它能输出一些东西。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP page</title>
</head>
<body>
<h2>我是你爹!</h2>
<h1>find all</h1>
<c:forEach items="${list}" var="user">
${user.name}
</c:forEach>
</body>
</html>
yysy,html的“c”语言我是不会写的,这是抄来的。
tomcat测试一下。
到这里基本就是完成了,剩下的就是配置事务,是在能跑起来的情况下的扩展。
applicationContext.xml里再加一些配置。
这些也都是有固定依赖的定式,上网冲浪复制粘贴就有了:
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!--配置AOP增强-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* zzzzmdzz.service.Impl.*ServiceImpl.*(..))"/>
</aop:config>
这里的文件目录记得改。
完善一下index:
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<body>
<a href="user/findAll">点击一键找爹</a>
<h3>test</h3>
<form action="user/save" method="post">
name:<input type="text" name="name" /><br/>
pass: <input type="text" name="pass" /><br/>
sex: <input type="text" name="sex" /><br/>
age: <input type="text" name="age"/><br/>
<input type="submit" value="保存"/><br/>
</form>
</body>
</html>
去service和controller把保存也写了:
@RequestMapping("/user/save")
public void save(User user, HttpServletRequest request,
HttpServletResponse response)throws IOException{
userService.saveUser(user);
response.sendRedirect(request.getContextPath()+"/user/findAll");
return;
}
测试:
完成。
最后是扯淡,与正文无关,不想看的可以直接退了。
1,感谢这些人的教程:https://yichun.blog.csdn.net/article/details/100192558
https://blog.csdn.net/m0_51430600/article/details/115349894?spm=1001.2014.3001.5501
https://blog.csdn.net/The_3/article/details/115111530?spm=1001.2014.3001.5501
我写着玩意也不能算是教程,毕竟都是参考上面这些人,综合写出来的,只能说进攻参考吧。
2,遇到了很多问题,全靠面向csdn解决,最感谢的是这份资料,帮我解决这问题,让我早睡两个小时,万分感谢:
无意冒犯,仅做分享,如果原作者介意的话,给我留个言马上就删。
3,jsp里的大标题,本来我是打算写个helloworld啥的,当时我同桌捅咕过来:“我是你爹!”然后我就脑子一热写进来了。