Java Novice Learning Guide [day38]---SpringMvc+Spring+Mybatis

SSM integration

SSM integration = SpringMvc+Spring+Mybatis integration

1. Preparation

①, create a dynamic web project

Pay attention to check the Tomcat environment

② Import the required jar package

The jar package is now manually imported, and it will be loaded after it is connected to the network through maven.

③, modify the project address in the server

2. Create a configuration file (resource folder)

①, create a database link configuration filejdbc.properties

Store the database-related configuration, pay attention to adding a prefix jdbc., otherwise problems will occur. Because the username is already in use by Spring, it will cause our username to become invalid and cause an error! Of course, the error can also be solved in the form of configuration:

<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="NEVER" />
#驱动全限定类名
jdbc.driverClassName=com.mysql.jdbc.Driver
#数据库连接地址
jdbc.url=jdbc:mysql:///ssm?useUnicode=true&characterEncoding=UTF-8
#数据库用户名
jdbc.username=root
#数据库密码
jdbc.password=root

②, Spring configuration file applicationContext.xml (spring+mybatis)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
 	http://www.springframework.org/schema/beans/spring-beans.xsd
 	http://www.springframework.org/schema/mvc
 	http://www.springframework.org/schema/mvc/spring-mvc.xsd
 	http://www.springframework.org/schema/context
 	http://www.springframework.org/schema/context/spring-context.xsd">
 
</beans>

Code will be filled in internally later

<!-- 1、配置连接需要连接的数据库,匹配当前src下查找jdbc.properties文件 -->
	<context:component-scan base-package="jdbc.properties"></context:component-scan>
	<!-- 2、管理连接池,获取数据库的“四大金刚”,注意名字要匹配 -->
	<bean id="dS" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}"></property>
		<property name="url" value="${jdbc.url}"></property>
		<property name="username" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>
	<!-- 3、spring管理SqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dS"></property>
		<!-- 配置mybatis (mapper)映射器路径 -->
		<property name="mapperLocations" value="classpath:cn/xxxx/mapper/*Mapper.xml" />
		<!-- 配置别名 -->
		<property name="typeAliasesPackage" value="cn.xxxx.domain"></property>
	</bean>
	<!-- 4.配置扫描Mapper:动态创建mapper包中所有接口的【动态实例】 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 这句可以省略,自动注册 -->
		<!-- <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> -->
		<!-- 找到Mapper接口 创建实例 -->
		<property name="basePackage" value="cn.xxxx.mapper"></property>
		<!-- 指定注解的类,一般不配置 -->
		<!-- <property name="annotationClass" value="com.fire.annotation.Mybatis"></property> -->
	</bean>
	<!-- 5.配置扫描Service domain 查询@service注解 -->
	<context:component-scan base-package="cn.xxxx.service"></context:component-scan>

③, SpringMVC configuration file spring-mvc.xml

The code is the same as the applicationContext.xml file, the content will be filled in later

	<!-- 1. 配置扫描包路径,只扫描controller包 -->
	<context:component-scan base-package="cn.xxxx.controller"></context:component-scan>
	<!-- 2. 配置静态资源放行 -->
	<mvc:default-servlet-handler />
	<!-- 3. 配置开启Spring对mvc的支持,支持@RequestMapping注解 -->
	<mvc:annotation-driven></mvc:annotation-driven>
	<!-- 4. 配置视图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	<!-- 5.拦截器 -->
	<!-- 4.文件上传解析器 -->

④, log log4j.properties

#5.控制台输出+自定义布局
log4j.rootLogger=DEBUG,my
#指定输出器
log4j.appender.my=org.apache.log4j.ConsoleAppender
#指定布局器(自定义布局)
#指定布局为自定义布局
log4j.appender.my.layout=org.apache.log4j.PatternLayout
#指定在自定义布局的格式,%d -- 表示当前系统时间,%t -- 执行该业务的线程名称,%p -- 日记器的级别,-5 -- 5表示输出字符的个数,符号表示右对齐
#%c -- 表示指定业务所在的类的完全限定名(包名.类名),%m -- 输出额外信息,%n -- 表示换行
log4j.appender.my.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
#设置package(可以是自定义的包也可以是api的包)输出级别
log4j.logger.org.springframework=info
log4j.logger.cn.xxxx=debug

⑤, web.xml configuration

Start Tomcat at the same time because the listener is configured, so the spring container is started at the same time, and the front controller of SpringMVC is configured at the same time

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>practice</display-name>
  <!-- Spring实现的上下文监听器:启动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>
	
	<!-- SpringMVC前端控制器 -->
	<servlet>
		<servlet-name>dispatcherServlet</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>
    <!-- 拦截所有格式,但是不会拦截.jsp -->
	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- SpringMVC过滤器:针对请求对象设置编码,解决乱码问题 -->
	<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>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>EncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

Overall layout

1604320833485

Three, background function realization

①, create the entity class of the database

Note that the data types are all done with wrappers, which is convenient for method calls

②. Creation of front-end display page

Create the front-end display page show.jsp and place it in the root directory of web.xml

Create index.jsp, configuration is <jsp:forward page="emp/list"></jsp:forward>easy to jump (but note that it can be used only if path is not configured in server.xml, otherwise the jsp file will be created out of order)

③, prepare the controller to jump

After entering from index.jsp, you need to jump to show.jsp to display when all the queries are completed.

④, write Mapper.java interface and mapper mapping file

package cn.xxxx.mapper;

import java.util.List;

import cn.xxxx.domain.Emp;

public interface EmpMapper {
    
    
	public List<Emp> findAll();
}

mapper mapping file

<mapper namespace="cn.xxxx.mapper.EmpMapper">
    <!--注意方法名要保持一致-->
	<select id="findAll" resultType="emp">
		select * from emp
	</select>
</mapper> 

⑤, write Service

Service interface

package cn.xxxx.service;

import java.util.List;

import cn.xxxx.domain.Emp;

public interface IEmpService {
    
    
	public List<Emp> findAll();
}

Service implementation class

@Service
public class EmpServiceImpl implements IEmpService{
    
    
	//声明接口
	@Autowired
	private EmpMapper empMapper;

	@Override
	public List<Emp> findAll() {
    
    
		return empMapper.findAll();
	}
}

⑥, write the controller

@Controller
@RequestMapping("/emp")
public class EmpController {
    
    
	@Autowired
	private IEmpService service;
	@RequestMapping("/list")
	public String list(Model model){
    
    //使用service查询数据
		List<Emp> emps = service.findAll();
		//传递给前台进行展示
		model.addAttribute("emps", emps);
		return "show";
	}
}

Note that the name here should correspond

1604327902762 1604327952789 1604327902762 1604327952789

⑦、Test

Four, advanced query

Driven programming, first use and then edit (can be automatically generated according to the prompt)

Controller:

@RequestMapping("/findByCondition")
	public String findByCondition(Emp emp , Model model){
    
    //使用service查询数据
		List<Emp> emps = service.findByCondition(emp);
		//传递给前台进行展示
		model.addAttribute("emps", emps);
		return "show";
	}

service interface:

public List<Emp> findByCondition(Emp emp);

Service implementation class :

	@Override
	public List<Emp> findByCondition(Emp emp) {
    
    
		return empMapper.findByCondition(emp);
	}

Mapper:

public List<Emp> findByCondition(Emp emp);

Mapper file:

	<select id="findByCondition" parameterType="emp" resultType="emp">
		select * from emp
	</select>

Five, MyBatis dynamic sql

Introduction: The use of Mybatis dynamic SQL is very similar to JSTL, and different SQL statements can be constructed in xml

<if>Two functions: 1. Make a judgment, and splice the content of the label when the condition is passed 2. It will automatically add a space

<where>Two functions: 1. Join a where 2. Ignore the first redundant and or or 3. Automatically add spaces

Optimize the conditions in the above Mapper file

<select id="findByCondition" parameterType="emp" resultType="emp">
		select * from emp
		<where>

			<include refid="deptno"></include>

			<!-- 字符串要对null和“”进行判断,同时还有空格的情况 -->
			<if test='ename != null and !"".equals(ename.trim())'><!--trim()是字符串的函数 -->
				and ename like CONCAT('%',trim(#{ename}),'%')<!-- trim()是mysql的函数 -->
			</if>
			<if test='address != null and !"".equals(address.trim())'>
				and address like CONCAT('%',trim(#{address}),'%')
			</if>
			<!-- 再对sal进行筛选,需要用到choose标签 -->
			<if test="sal != null">
				<choose>
					<when test="sal==3000"><!-- 3000以下 -->
						and sal &lt;=#{sal}
					</when>
					<when test="sal==5000"><!-- [3000-5000) -->
						and sal &lt;#{sal} and sal &gt;=#{sal}
					</when>
					<when test="sal==8000"><!-- [5000-8000) -->
						and sal &lt;#{sal} and sal &gt;=#{sal}-3000
					</when>
					<when test="sal==8001"><!-- 8000以上 -->
						and sal &gt;=#{sal}
					</when>
				</choose>
			</if>
		</where>
	</select>
	<!-- 使用<sql>抽取: -->
	<sql id="deptno">
		<if test="deptno != null"><!-- 进行判断,前台传了才会有后面的where代码 -->
			and deptno = #{deptno}
		</if>
	</sql>

Guess you like

Origin blog.csdn.net/WLK0423/article/details/111144768