小四整理一丢丢关于spring的学习笔记(spring+SpringMVC+MyBatis)

小四整理一丢丢关于spring的学习笔记(spring+SpringMVC+MyBatis)

  • 三框架整合+根据id查询数据库

Spring简介

Spring是一个轻量级Java开发框架,最早有Rod Johnson创建,目的是为了解决企业级应用开发的业务逻辑层和其他各层的耦合问题。它是一个分层的JavaSE/JavaEE full-stack(一站式)轻量级开源框架,为开发Java应用程序提供全面的基础架构支持。Spring负责基础架构,因此Java开发者可以专注于应用程序的开发。
呸呸呸。。。
这样的理论知识太过于枯燥乏味
小四的老师曾经说过:作为初学者,你可以不知道为什么这么做,但你要知道改怎么做。让时间来积累你的知识量,你就会知道为什么这么做了。
其实我也不知道为什么这么做,我也咩有读过spring的源码
但这么做能做好这件事就完事了
废话少说,下面来开始快乐代码时间

我们要做点啥

目的:利用Spring+SpringMVC+MyBatis实现登录并且增删改查
这里插入一张我老师画的快乐思路图
这里插入一张我老师画的快乐思路图

1.添加jar包:

在这里插入图片描述
在这里插入图片描述
做增删改查暂时先用着先

2.三框架整合:

首先咱要先配置web.xml
利用web.xml整合Spring和Spring MVC
解决中文乱码,org.springframework.web.filter.CharacterEncodingFilter
话不多说咱代码安排上来再说(其实这是我老师写好发给我的< !–捧腹大笑–>)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
	<display-name>ssm</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
  <!-- 把spring集成到web项目里面 -->
  <!-- 配置Spring 配置文件的路径 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring.xml</param-value>
	</context-param>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- spring mvc的前端控制器 -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <!-- 解决中文乱码问题 -->
    <filter>
        <filter-name>CharacterEncodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

web.xml是在创建项目的时候自动生成的在WebContentContent下面
然后进行配置就行

然后Spring-mvc.xml
配置Spring MVC
注意(自定义的):
控制器所在的包,cn.edu.wic
JSP路径:/WEB-INF/jsp/
静态资源:/res/
话不多说咱代码盘起来

<?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:p="http://www.springframework.org/schema/p" 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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<context:component-scan base-package="cn.edu.wic" />
	
	<mvc:annotation-driven/>

	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
	
	<mvc:resources location="/res/" mapping="/res/**"></mvc:resources>
</beans>   

然后就是Spring.xml了
spring.xml:Spring bean,整合MyBatis
Spring Bean所在的包
数据库连接信息
dataSource.url,dataSource.username,dataSource.password
MyBatis的相关配置:
SqlSessionFactoryBean

<?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">
	<!-- 所有的bean所在的包 -->
	<context:component-scan base-package="cn.edu.wic" />

	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<!-- 基本属性 url、user、password -->
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://localhost:3306/ssm2020?useUnicode=true&amp;characterEncoding=UTF-8" />
		<property name="username" value="root" />
		<property name="password" value="" />

		<!-- 配置监控统计拦截的filters -->
		<property name="filters" value="stat" />

		<!-- 配置初始化大小、最小、最大 -->
		<property name="maxActive" value="20" />
		<property name="initialSize" value="1" />
		<property name="minIdle" value="1" />

		<!-- 配置获取连接等待超时的时间 -->
		<property name="maxWait" value="60000" />

		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />

		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="300000" />

		<property name="testWhileIdle" value="true" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />

		<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
		<property name="poolPreparedStatements" value="true" />
		<property name="maxOpenPreparedStatements" value="20" />
	</bean>

	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<tx:annotation-driven transaction-manager="transactionManager" />

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mapperLocations">
			<array>
				<value>classpath:cn/edu/wic/mapper/ *Mapper.xml</value>
			</array>
		</property>
		<property name="configLocation" value="classpath:mybatis-config.xml" />
		<property name="typeAliasesPackage" value="cn.edu.wic.entity"></property>
	</bean>

	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="cn.edu.wic.mapper" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>

</beans>

忘记了一个mybatis-config.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>
</configuration>

还有一个小日志 log4j.properties
《---------------------快乐分隔符》
log4j.rootCategory=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n
log4j.logger=DEBUG
《---------------------快乐分隔符》
这就直接粘过来了
把他们都放在一起:
在这里插入图片描述

这样子spring的繁琐的配置就基本完成了
这也是spring的一大缺陷(xml太烦人了,不过还好我站在老师的肩膀上,无所畏惧)

完成一个查询界面

我们从后往前做起,这就是传说中的自底向上
首先mapper包下面的Usermapper.xml
这个用来写sql语句的

<?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="cn.edu.wic.mapper.UserMapper">
<select id="get" resultType="User">
	SELECT id,name,username,sex,password,age,phone,e_mail,qq
	FROM user
	WHERE id=#{id}
</select>
</mapper>

然后UseMapper接口安排上

package cn.edu.wic.mapper;
import cn.edu.wic.entity.User;
public interface UserMapper {
	public User get(Integer id);
}

进入service接口(我是直接复制粘贴)

package cn.edu.wic.service;
import cn.edu.wic.entity.User;
public interface UserService {
	public User get(Integer id);
}

然后就是serviceImpl(有注解的)

package cn.edu.wic.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.edu.wic.entity.User;
import cn.edu.wic.mapper.UserMapper;
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
	
	@Override
	public User get(Integer id) {
		
		return userMapper.get(id);
	}

然后就是控制器controller(也是有很多注解)
通过return “user”;
进入user.jsp

package cn.edu.wic.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.ui.Model;
import cn.edu.wic.entity.User;
import cn.edu.wic.service.UserService;
@Controller
public class UserController {
		@Autowired
		private UserService userService;
		@RequestMapping("/user")
		public String get(@RequestParam("id") Integer id, Model model){
			User user = userService.get(id);
			model.addAttribute("user", user);
			return  "user";
		}
}


还需要建一个User类和它的get set 方法

package cn.edu.wic.entity;
public class User {
	private String username;
	private String name;
	private String password;
	private String sex;
	private String qq;
	private String e_mail;
	private String phone;
	private Integer id;
	private Integer age;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getQq() {
		return qq;
	}
	public void setQq(String qq) {
		this.qq = qq;
	}
	public String getE_mail() {
		return e_mail;
	}
	public void setE_mail(String e_mail) {
		this.e_mail = e_mail;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", name=" + name + ", password="
				+ password + ", sex=" + sex + ", qq=" + qq + ", e_mail="
				+ e_mail + ", phone=" + phone + ", id=" + id + ", age=" + age
				+ "]";
	}
	
	
}

然后是jsp了(jsp再不是放在跟这些class一个路径的,它在/WEB-INF/jsp/下 前文有提到过)
use.jsp
这里有用到jstl中的循环

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<c:import url="_res.jsp"></c:import>
<title>Insert title here</title>
</head>
<body>
	<div class="container">
	<h1 class="page-header">用户信息</h1>
	<table class="table table-striped table-hover table-bordered" >
		<!--  for (User i : user){} -->
		<tr>
			<th>id</th>
		 	<th>用户名</th>
		 	<th>用户姓名</th>
		 	<th>密码</th>
		 	<th>年龄</th>
		 	<th>性别</th>
		 	<th>e_mail</th>
		 	<th>qq</th>
		 	<th></th>
		 	</tr>
		 	<c:forEach items="${ users }" var="i">
		 	
		 		<tr>
		 			<td>${i.id }</td>
		 			<td>${i.username}</td>
		 			<td>${i.name}</td>
		 			<td>${i.password}</td>
		 			<td>${i.age}</td>
		 			<td>${i.sex }</td>
		 			<td>${i.e_mail}</td>
		 			<td>${i.qq}</td>
		 		</tr>
			</c:forEach>
		</body>

这样子就可以一条一条
显示数据库的内容了
给你们看看成品的图片
在这里插入图片描述

在这里插入图片描述
抄就完事了啊哈哈哈哈哈哈哈哈< !–捧腹大笑–>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值