【编程不良人】快速入门SpringMVC学习笔记02---Spring+SpringMVC+MyBatis整合编程

本文主要是介绍【编程不良人】快速入门SpringMVC学习笔记02---Spring+SpringMVC+MyBatis整合编程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.新建maven-webapp工程,添加java、resources目录及test目录下的java、resources

2.引入依赖

  <!--spring核心及相关依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>4.3.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>4.3.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>4.3.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>4.3.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>4.3.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>4.3.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-expression</artifactId><version>4.3.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>4.3.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>4.3.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>4.3.2.RELEASE</version></dependency>​<!--springmvc核心依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>4.3.2.RELEASE</version></dependency>​<!--servlet-api--><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version><scope>provided</scope></dependency>​<!--jstl--><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency>​<!--mybatis--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.2.8</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.3</version></dependency>​<!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.38</version></dependency>​<!--druid--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.17</version></dependency>​<!--log4j--><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.10.0</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.25</version></dependency>​<!--fastjson--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version></dependency>

3.Spring+Mybatis整合

3.1 新建表

3.2 新建实体类

  package com.study.entity;​import java.util.Date;​/*** @ClassName User* @Description TODO* @Author Jiangnan Cui* @Date 2022/4/23 10:46* @Version 1.0*/public class User {private String id;private String name;private Integer age;private Date bir;​@Overridepublic String toString() {return "User{" +"id='" + id + '\'' +", name='" + name + '\'' +", age=" + age +", bir=" + bir +'}';}​public User() {}​public User(String id, String name, Integer age, Date bir) {this.id = id;this.name = name;this.age = age;this.bir = bir;}​public String getId() {return id;}​public void setId(String id) {this.id = id;}​public String getName() {return name;}​public void setName(String name) {this.name = name;}​public Integer getAge() {return age;}​public void setAge(Integer age) {this.age = age;}​public Date getBir() {return bir;}​public void setBir(Date bir) {this.bir = bir;}}​

3.3 新建DAO接口

  package com.study.dao;​import com.study.entity.User;​import java.util.List;​/*** @ClassName UserDAO* @Description TODO* @Author Jiangnan Cui* @Date 2022/4/23 10:45* @Version 1.0*/public interface UserDAO {​/*** @MethodName selectAllUsers* @Description 查询所有用户* @return: java.util.List<com.study.entity.User>* @Author Jiangnan Cui* @Date 2022/4/23 10:50*/List<User> selectAllUsers();​/*** @MethodName insertUser* @Description 添加用户* @param: user* @Author Jiangnan Cui* @Date 2022/4/23 10:49*/void insertUser(User user);​}​

3.4 新建Mapper配置文件

  <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd" >​<mapper namespace="com.study.dao.UserDAO"><!--selectAllUsers--><select id="selectAllUsers" resultType="User">select id,name,age,bir from t_user</select>​<!--insertUser--><insert id="insertUser" parameterType="User">insert into t_user values(#{id},#{name},#{age},#{bir})</insert>​​</mapper>

3.5 新建Service接口

  package com.study.service;​import com.study.entity.User;​import java.util.List;​/*** @ClassName UserService* @Description TODO* @Author Jiangnan Cui* @Date 2022/4/23 10:55* @Version 1.0*/public interface UserService {/*** @MethodName selectAllUsers* @Description 查询所有用户* @return: java.util.List<com.study.entity.User>* @Author Jiangnan Cui* @Date 2022/4/23 10:50*/List<User> selectAllUsers();​/*** @MethodName insertUser* @Description 添加用户* @param: user* @Author Jiangnan Cui* @Date 2022/4/23 10:49*/void insertUser(User user);​}​

3.6 新建ServiceImpl实现类

  package com.study.service;​import com.study.dao.UserDAO;import com.study.entity.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;​import java.util.List;import java.util.UUID;​/*** @ClassName UserServiceImpl* @Description TODO* @Author Jiangnan Cui* @Date 2022/4/23 10:55* @Version 1.0*/@Service("userService")@Transactionalpublic class UserServiceImpl implements UserService{@Autowiredprivate UserDAO userDAO;​@Override@Transactional(propagation = Propagation.SUPPORTS)public List<User> selectAllUsers() {return userDAO.selectAllUsers();}​@Overridepublic void insertUser(User user) {user.setId(UUID.randomUUID().toString());userDAO.insertUser(user);}}​

3.7 引入spring.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:component-scan base-package="com.study"/>​<!--创建数据源对象--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF-8&amp;useSSL=false"/><property name="username" value="root"/><property name="password" value="123456"/></bean>​<!--创建SqlSessionFactory--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="mapperLocations" value="classpath:com/study/mapper/*.xml"/><property name="typeAliasesPackage" value="com.study.entity"/></bean>​<!--创建DAO--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/><property name="basePackage" value="com.study.dao"/></bean>​<!--创建事务管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean>​<!--开启注解式事务生效--><tx:annotation-driven transaction-manager="transactionManager"/>​</beans>

3.8 引入log4j.properties

  log4j.rootLogger=ERROR,stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.conversionPattern=[%p] %d{yyyy-MM-dd} %m%n•log4j.logger.com.study.dao=DEBUGlog4j.logger.org.springframework=ERROR

3.9 测试Service方法是否可以成功调用

  package com.study.test;​import com.study.entity.User;import com.study.service.UserService;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;​import java.util.List;​/*** @ClassName TestUserService* @Description TODO* @Author Jiangnan Cui* @Date 2022/4/23 11:11* @Version 1.0*/public class TestUserService {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");UserService userService = (UserService) context.getBean("userService");List<User> users = userService.selectAllUsers();for (User user : users) {System.out.println("user = " + user);}}}​

测试结果:

  [DEBUG] 2022-04-23 ==>  Preparing: select id,name,age,bir from t_user [DEBUG] 2022-04-23 ==> Parameters: [DEBUG] 2022-04-23 <==      Total: 18user = User{id='1', name='张三', age=10, bir=Fri Apr 01 00:00:00 CST 2022}user = User{id='2', name='李四', age=20, bir=Sat Apr 02 00:00:00 CST 2022}user = User{id='2d237778-835d-477b-9721-fe6f575064b9', name='波比', age=18, bir=Sun Feb 02 00:00:00 CST 2020}user = User{id='2f278828-6422-432d-ab1b-a727b33c23bc', name='小胖墩', age=3, bir=Mon Apr 11 21:43:57 CST 2022}user = User{id='3', name='王五', age=30, bir=Sun Apr 03 00:00:00 CST 2022}user = User{id='4', name='灰太狼', age=60, bir=Sun Apr 10 09:56:17 CST 2022}user = User{id='5', name='小超超', age=36, bir=Sun Apr 10 09:55:41 CST 2022}user = User{id='586a5f71-836c-4171-a038-4620fe0f9354', name='葫芦娃', age=5, bir=Tue Apr 12 09:45:17 CST 2022}user = User{id='6', name='小呆呆', age=60, bir=Sun Apr 10 09:55:43 CST 2022}user = User{id='7', name='小超超', age=36, bir=Sun Apr 10 09:55:44 CST 2022}user = User{id='7a1a00aa-1507-461a-95c0-50110d6f4333', name='唐三', age=20, bir=Fri Apr 15 00:00:00 CST 2022}user = User{id='8', name='胖嘟嘟', age=50, bir=Sun Apr 10 09:55:39 CST 2022}user = User{id='8a3e8ab8-5abc-44e1-9aec-31f3978d97f2', name='小胖墩', age=3, bir=Tue Apr 12 10:23:33 CST 2022}user = User{id='9', name='小崔', age=25, bir=Sun Apr 10 09:55:52 CST 2022}user = User{id='985cd035-dedc-4e84-973a-a5fdaa2b8475', name='喜洋洋', age=8, bir=Tue Oct 10 00:00:00 CST 2000}user = User{id='a6be9263-f05f-415f-855e-33843b22e71d', name='皮卡丘', age=10, bir=Thu Apr 14 00:00:00 CST 2022}user = User{id='cd280176-68b2-4ceb-b781-ba2f5e1fbeff', name='小胖墩', age=3, bir=Tue Apr 12 10:21:18 CST 2022}user = User{id='e3863fd3-173c-46f4-a753-c72f7c92ad56', name='小猫咪', age=3, bir=Mon Apr 11 21:36:31 CST 2022}

4.Spring+SpringMVC整合

4.1 配置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>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:spring.xml</param-value></context-param>​<!--配置springmvc核心servlet--><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></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping>​<!--配置post请求参数的中文乱码问题--><filter><filter-name>charset</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>charset</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>​

4.2 引入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.xsd"><!--开启注解扫描--><context:component-scan base-package="com.study.controller"/>​<!--配置处理映射器和处理适配器--><mvc:annotation-driven/>​<!--配置视图解析器--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/"/><property name="suffix" value=".jsp"/></bean><!--解决静态资源拦截的配置--><mvc:default-servlet-handler/>​</beans>

4.3 新建Controller

  package com.study.controller;​import com.study.entity.User;import com.study.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;​import javax.servlet.http.HttpServletRequest;import java.util.List;​/*** @ClassName UserController* @Description TODO* @Author Jiangnan Cui* @Date 2022/4/23 12:12* @Version 1.0*/@Controller@RequestMapping("user")public class UserController {@Autowiredprivate UserService userService;​@RequestMapping("selectAllUsers")public String selectAllUsers(HttpServletRequest request){//1.收集数据//2.调用业务对象List<User> users = userService.selectAllUsers();request.setAttribute("users",users);return "selectAllUsers";}​@RequestMapping("insertUser")public String insertUser(User user){//1.收集参数//2.调用业务方法try {userService.insertUser(user);return "redirect:/user/selectAllUsers";} catch (Exception e) {e.printStackTrace();return "redirect:/insertUser.jsp";}}​​}​

4.4 添加jsp文件

selectAllUsers.jsp

  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %><!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>用来展示所有用户信息</title><script src="${pageContext.request.contextPath}/js/jquery-3.5.1.min.js"></script><script>$(function(){alert();})</script></head><body><h1>展示用户列表</h1><c:forEach items="${requestScope.users}" var="user">${user.id} ==== ${user.name} ==== ${user.age} ==== ${user.bir} <br></c:forEach>​<a href="${pageContext.request.contextPath}/insertUser.jsp">添加用户信息</a></body></html>

insertUser.jsp

  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %><!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>添加用户信息</title></head><body><h1>添加用户信息</h1><form action="${pageContext.request.contextPath}/user/insertUser" method="post">姓名:<input type="text" name="name"/> <br>年龄:<input type="text" name="age"/> <br>生日:<input type="text" name="bir"/> <br><input type="submit" value="保存用户信息"></form></body></html>

5. 部署tomcat服务器测试

 测试结果:

6.总结

附项目目录结构:

 

这篇关于【编程不良人】快速入门SpringMVC学习笔记02---Spring+SpringMVC+MyBatis整合编程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/325923

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

mybatis的整体架构

mybatis的整体架构分为三层: 1.基础支持层 该层包括:数据源模块、事务管理模块、缓存模块、Binding模块、反射模块、类型转换模块、日志模块、资源加载模块、解析器模块 2.核心处理层 该层包括:配置解析、参数映射、SQL解析、SQL执行、结果集映射、插件 3.接口层 该层包括:SqlSession 基础支持层 该层保护mybatis的基础模块,它们为核心处理层提供了良好的支撑。