Spring和Spring Mvc 5整合详解

Spring和Spring Mvc 5整合详解

一、官方主页

Spring

Spring Mvc

低版本的SpringMvc,可以参考这一篇《Spring和Spring Mvc整合详解》

二、概述

Spring Mvc的启动方式不同于Spring Boot,Spring Boot内嵌了tomcat容器,可以打包成jar文件快速启动。Spring Mvc仍需要打包成war包。所以,它是离不开web.xml配置。

配置Spring和Spring Mvc,主要有:

  • 1.在web.xml中配置好Spring相关Listener/Filter/Servlet,并指明Spring和Spring Mvc的配置文件,当然,也可以不指定,放在classpath下就行,严谨一点还是写出来为好。
  • 2.配置applicationContext.xml,这个是给Spring用的,名字随意,只要在web.xml指定就行。
  • 3.配置 spring-servlet.xml,这个是给Spring Mvc用的,名字随意,只要在web.xml指定就行。

Git地址:
Gitee

项目地址:
品茗IT-同步发布

品茗IT 提供在线支持:

一键快速构建Spring项目工具

一键快速构建SpringBoot项目工具

一键快速构建SpringCloud项目工具

一站式Springboot项目生成

如果大家正在寻找一个java的学习环境,或者在开发中遇到困难,可以加入我们的java学习圈,点击即可加入,共同学习,节约学习时间,减少很多在学习中遇到的难题。

三、开始搭建

3.1 依赖Jar包


<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0modelVersion>
	<parent>
		<groupId>cn.pomitgroupId>
		<artifactId>SpringWorkartifactId>
		<version>0.0.1-SNAPSHOTversion>
	parent>
	<artifactId>WebartifactId>
	<packaging>warpackaging>
	<name>Webname>
	<url>http://maven.apache.orgurl>
	<dependencies>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-coreartifactId>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-webartifactId>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-webmvcartifactId>
		dependency>
		<dependency>
			<groupId>org.apache.logging.log4jgroupId>
			<artifactId>log4j-apiartifactId>
		dependency>

		
		<dependency>
			<groupId>org.apache.logging.log4jgroupId>
			<artifactId>log4j-coreartifactId>
		dependency>

		
		<dependency>
			<groupId>org.apache.logging.log4jgroupId>
			<artifactId>log4j-webartifactId>
		dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.coregroupId>
			<artifactId>jackson-annotationsartifactId>
		dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.coregroupId>
			<artifactId>jackson-coreartifactId>
		dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.coregroupId>
			<artifactId>jackson-databindartifactId>
		dependency>

		<dependency>
			<groupId>cn.pomitgroupId>
			<artifactId>EhcacheartifactId>
			<version>${project.version}version>
		dependency>
	dependencies>
	<build>
		<finalName>WebfinalName>
	build>
project>

父pom管理了所有依赖jar包的版本,地址:
https://www.pomit.cn/spring/SpringWork/pom.xml

3.2 web.xml


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="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_3_0.xsd"
	version="3.0">
	<display-name>springwork-maindisplay-name>
	<listener>
		<listener-class>org.apache.logging.log4j.web.Log4jServletContextListenerlistener-class>
	listener>

	<filter>
		<filter-name>log4jServletFilterfilter-name>
		<filter-class>org.apache.logging.log4j.web.Log4jServletFilterfilter-class>
	filter>
	<filter-mapping>
		<filter-name>log4jServletFilterfilter-name>
		<url-pattern>/*url-pattern>
		<dispatcher>REQUESTdispatcher>
		<dispatcher>FORWARDdispatcher>
		<dispatcher>INCLUDEdispatcher>
		<dispatcher>ERRORdispatcher>
	filter-mapping>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
	listener>
	<context-param>
		<param-name>contextConfigLocationparam-name>
		<param-value>classpath:applicationContext.xmlparam-value>
	context-param>
	<filter>
		<filter-name>characterEncodingFilterfilter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
		<init-param>
			<param-name>encodingparam-name>
			<param-value>UTF-8param-value>
		init-param>
		<init-param>
			<param-name>forceEncodingparam-name>
			<param-value>trueparam-value>
		init-param>
	filter>
	<filter-mapping>
		<filter-name>characterEncodingFilterfilter-name>
		<url-pattern>/*url-pattern>
	filter-mapping>

	









	<servlet>
		<servlet-name>springDispatcherServletservlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
		<init-param>
			<param-name>contextConfigLocationparam-name>
			<param-value>classpath:spring-servlet.xmlparam-value>
		init-param>
		<load-on-startup>1load-on-startup>
	servlet>
	<servlet-mapping>
		<servlet-name>springDispatcherServletservlet-name>
		<url-pattern>/url-pattern>
	servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.htmlwelcome-file>
	welcome-file-list>
web-app>

3.3 Spring配置

applicationContext.xml是Spring的配置文件。

applicationContext.xml:


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" 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/tx 
                    http://www.springframework.org/schema/tx/spring-tx.xsd
                    http://www.springframework.org/schema/aop 
                    http://www.springframework.org/schema/aop/spring-aop.xsd
                    http://www.springframework.org/schema/context      
                    http://www.springframework.org/schema/context/spring-context.xsd">

	<context:annotation-config />
	<context:component-scan base-package="cn.pomit.springwork">
	context:component-scan>
	
	<import resource="classpath*:spring-mybatis.xml"/>
	<import resource="classpath*:spring-ehcache.xml"/>
beans>

这个配置文件里可以写入一些bean的配置。

Spring是一个大的父容器,Spring Mvc是其中的一个子容器。父容器不能访问子容器对象,但是子容器可以访问父容器对象。 因此,bean的配置要写到这个文件中,而不是Spring Mvc的配置文件中。

3.4 Spring Mvc配置

spring-servlet.xml是Springmvc的配置文件


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	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:annotation-config />
	<context:component-scan base-package="cn.pomit.springwork" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
		<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController" />
	context:component-scan>
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="" />
	bean>


	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean
				class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>application/json;charset=UTF-8value>
					list>
				property>
			bean>
		mvc:message-converters>
	mvc:annotation-driven>

	<mvc:resources location="/img/" mapping="/img/**" />
	<mvc:resources location="/css/" mapping="/css/**" />
	<mvc:resources location="/js/" mapping="/js/**" />
	<mvc:default-servlet-handler/>
beans>

Spring是一个大的父容器,Spring Mvc是其中的一个子容器。父容器不能访问子容器对象,但是子容器可以访问父容器对象。 因此,bean的配置要写到这个文件中,而不是Spring Mvc的配置文件中。

:

  • 这里是配置Spingmvc只扫描Controller和RestController注解,避免和Spring扫描过程冲突。

  • 惨痛教训:不隔离开两个包扫描的过程,会导致@Scheduled注解执行两次,而且注解使用的缓存会失效。

3.5 log4j配置


<Configuration status="OFF" monitorInterval="1800">
    <properties>
        <property name="LOG_HOME">D:/log/SpringWorkLogproperty>
        <property name="FILE_NAME">SpringWorkLogproperty>
    properties>
 
 
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        Console>
 
        <RollingFile name="running-log" fileName="${LOG_HOME}/${FILE_NAME}.log"
            filePattern="${LOG_HOME}/$${date:yyyy-MM}/${FILE_NAME}-%d{yyyy-MM-dd}-%i.log.gz"
            immediateFlush="true">
            <PatternLayout
                pattern="%date{yyyy-MM-dd HH:mm:ss.SSS} %level [%thread][%file:%line] - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="10 MB" />
            Policies>
            <DefaultRolloverStrategy max="20" />
        RollingFile>
    Appenders>
    <Loggers>
 



 
        <Root level="debug">
               
            <AppenderRef ref="running-log" />
            
            <AppenderRef ref="Console" />
        Root>
    Loggers>
Configuration>

四、测试代码

4.1 简单的Controller

WebController:

package cn.pomit.springwork.web.endpoint;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/web")
public class WebController {

	@RequestMapping(value = "/json", method = { RequestMethod.GET })
	public String welCome() {

		return "redirect:/json.html";
	}
}

4.2 简单的RestController

RestController提供rest服务,一般都是提供json数据的。

WebRest:

package cn.pomit.springwork.web.endpoint;

import java.util.UUID;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.pomit.springwork.web.entity.WelEntity;


@RestController
@RequestMapping("/pub")
public class WebRest {
	
	@RequestMapping(value = "/welCome", method = { RequestMethod.GET })
	public WelEntity welCome(@RequestParam(value = "reqType", required = false) String reqType) {
		String uuid = UUID.randomUUID().toString();
		String welMsg = "welcome 程序猿";
		if(reqType != null && "1000".equals(reqType)){
			welMsg = "welcome 程序媛";
		}
		WelEntity welEntity = new WelEntity();
		welEntity.setUuid(uuid);
		welEntity.setWelMsg(welMsg);
		return welEntity;
	}
}

详细完整代码,可以访问品茗IT-博客《Spring和Spring Mvc 5整合详解》,也可以在Spring组件化构建中选择查看,并下载。

快速构建项目

Spring组件化构建

喜欢这篇文章么,喜欢就加入我们一起讨论Spring技术吧!
品茗IT交流群

你可能感兴趣的:(Spring之路)