深度解析Spring5源码

51--SpringMVC源码阅读环境搭建

2019-02-16  本文已影响7人  闲来也无事
1.引

前面的章节已经分析了Spring的IOC容器、AOP、事物管理等,今天开始分析SpringMVC的实现。当然需要先搭建一下SpringMVC源码的阅读环境,因为之前的代码分析都是非Web环境的。

2.新建Gradle模块
2.1 右键spring源码根目录,新建模块,弹出窗口选择Gradle --> 同时勾选java和web
在这里插入图片描述
2.2 选择根目录并输入ArtifactId,点击确定
在这里插入图片描述
2.3 完善项目结构
  1. 通过前两步的操作,得到一个空的web项目,接下来就要将其完善。打开build.gradle配置文件,并配置:
plugins {
    id 'java'
    id 'war'
}

group 'org.springframework'
version '5.1.0.RC1'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile(project(":spring-beans"))
    compile(project(":spring-core"))
    optional(project(":spring-aop"))
    optional(project(":spring-context"))
    optional(project(":spring-oxm"))
    optional(project(":spring-jdbc"))
    optional(project(":spring-web"))
    optional(project(":spring-webmvc"))
    optional(project(":spring-test"))

    optional group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
    optional group: 'asm', name: 'asm', version: '3.3.1'
    optional group: 'junit', name: 'junit', version: '4.12'
    optional group: 'cglib', name: 'cglib', version: '2.2.2'
    optional group: 'org.jsoup', name: 'jsoup', version: '1.11.3'
    optional group: 'commons-dbcp', name: 'commons-dbcp', version: '1.4'
    optional group: 'mysql', name: 'mysql-connector-java', version: '5.1.38'

    optional("javax.annotation:javax.annotation-api:1.3.2")
    optional("javax.ejb:javax.ejb-api:3.2")
    optional("javax.enterprise.concurrent:javax.enterprise.concurrent-api:1.0")
    optional("javax.inject:javax.inject:1")
    optional("javax.interceptor:javax.interceptor-api:1.2.2")
    optional("javax.money:money-api:1.0.3")
    optional("javax.validation:validation-api:1.1.0.Final")
    optional("javax.xml.ws:jaxws-api:2.3.0")
    optional("org.aspectj:aspectjweaver:${aspectjVersion}")
    optional("org.codehaus.groovy:groovy:${groovyVersion}")
    optional("org.beanshell:bsh:2.0b5")
    optional("joda-time:joda-time:2.10")
    optional("org.hibernate:hibernate-validator:5.4.2.Final")
    optional("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}")
    optional("org.jetbrains.kotlin:kotlin-stdlib:${kotlinVersion}")
    testCompile("org.codehaus.groovy:groovy-xml:${groovyVersion}")
    testCompile("org.codehaus.groovy:groovy-jsr223:${groovyVersion}")
    testCompile("org.codehaus.groovy:groovy-test:${groovyVersion}")
    testCompile("org.apache.commons:commons-pool2:2.6.0")
    testCompile("javax.inject:javax.inject-tck:1")
    testRuntime("javax.xml.bind:jaxb-api:2.3.0")
    testRuntime("org.glassfish:javax.el:3.0.1-b08")
    testRuntime("org.javamoney:moneta:1.3")
}
  1. 在resources资源文件下添加log4j.properties和spring-context.xml配置文件
# Output pattern : date [thread] priority category - message   FATAL 0  ERROR 3  WARN 4  INFO 6  DEBUG 7 
log4j.rootLogger=INFO, Console, RollingFile

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d %-5p [%c{5}] - %m%n

#RollingFile
log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingFile.File=mylog.log
log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

#log4j.logger.java.sql=DEBUG

#Springframework level
#log4j.logger.org.springframework=ERROR

#Hibernate level
#log4j.logger.org.hibernate=ERROR
#log4j.logger.org.hibernate.cache.ehcache.AbstractEhcacheRegionFactory=ERROR
#log4j.logger.org.hibernate.search.impl.ConfigContext=ERROR
#log4j.logger.net.sf.ehcache.config.CacheConfiguration=ERROR

#Project defalult level
#log4j.logger.org.activiti.engine.impl.persistence=DEBUG
#log4j.logger.org.apache.shiro=DEBUG
log4j.logger.com.thinkgem.jeesite=DEBUG
log4j.logger.com.thinkgem.jeesite.common.security.shiro=WARN
log4j.logger.com.thinkgem.jeesite.common.utils.JedisUtils=WARN
log4j.logger.com.thinkgem.jeesite.modules.sys.web.LoginController=WARN
log4j.logger.com.thinkgem.jeesite.modules.oa.dao.OaNotifyDao.findCount=WARN

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"
       default-lazy-init="true">

    <!-- 采用注释的方式配置bean -->
    <context:annotation-config />

    <!-- proxy-target-class默认"false",更改为"ture"使用CGLib动态代理 -->
    <aop:aspectj-autoproxy/>

    <!-- 开启自动扫包 -->
    <context:component-scan base-package="com.lyc.cn">
        <!--制定扫包规则,不扫描@Controller注解的JAVA类,其他的还是要扫描 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>
  1. 在WEB-INF下添加web.xml和example-servlet.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <!-- 项目名 -->
    <display-name>example</display-name>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>/example/</url-pattern>
    </servlet-mapping>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-context.xml</param-value>
    </context-param>
    
    <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>
<?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-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!-- 开启注解模式驱动 -->
    <!-- springmvc中配置这个标签默认注册三个bean:RequestMappingHandlerMapping,RequestMappingHandlerAdapter,DefaultHandlerExceptionResolver -->
    <mvc:annotation-driven />

    <!-- 扫包 -->
    <context:component-scan base-package="com.lyc.cn"></context:component-scan>

    <!-- 视图渲染 jsp/freemaker/velocity -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 制定页面存放的路径 -->
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <!-- 文件的后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>
  1. 在WEB-INF下新建pages文件夹并添加sayHello.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
    sayHello...<br/>
    ${myBean.name}<br/>
    ${myBean.age}
</body>
</html>
  1. 添加TestController和MyBean
package com.lyc.cn.controller;

import com.lyc.cn.vo.MyBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class TestController {

    @RequestMapping("sayHello")
    @ResponseBody
    public ModelAndView sayHello(int age, String name) {
        ModelAndView mav = new ModelAndView();
        MyBean bean = new MyBean(age, name);
        mav.addObject("myBean", bean);
        mav.setViewName("sayHello");
        System.out.println(bean.toString());
        return mav;
    }
}
package com.lyc.cn.vo;

public class MyBean {
    private int age;
    private String name;

    public MyBean(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
3.配置tomcat并运行项目

tomcat配置比较简单,不赘述了。启动项目在地址栏输入:http://localhost:8080/example/sayHello?age=12&name=Jack

上一篇下一篇

猜你喜欢

热点阅读