SpringMVC的两种配置方式:.xml / .class

SpringMVC的两种配置方式:.xml / .class_第1张图片
The request processing workflow in Spring Web MVC (high level)
这里主要介绍SpringMVC的两种配置文件的方式:
  • 1、使用传统的.xml配置文件;
  • 2、现在比较流行的使用代码配置代码的方式(用普通的Java类实现配置)。

以下用代码的方式表述详细过程:

@Section one : .xml

- 1、applicationContext.xml

该文件路径应为:根目录"/"下,即:与package放在同一路径下



   
         
    
    
    
    
    
    
    
    
    
    
        
        
        
        
        
        
            
    

    
    
        
        
        
            
                hibernate.dialect=org.hibernate.dialect.MySQLDialect
                hibernate.show_sql=true
                hibernate.format_sql=true
            
        
    

    
    
        
    

    


- 2、frontController-servlet.xml

该文件是配置视图控制器的,在其中可以设置前缀后缀等
该文件路径应为:"/WEB-INF"下



   
         
    
    
    
    
    
    
        
        
        
    


- 3、web.xml

这个文件尤其重要,这是这个项目的配置文件,我们可以在里面配置很多东西,比如默认页面、前端控制器、过滤器、监听器等

该文件路径为:"/WEB-INF"下,这个文件可以在创建项目时勾选选项自动生成,此处强烈建议留下这个web.xml配置文件



    
    
        index.do
    
    
    
    
        contextConfigLocation
        classpath:app.xml
    
 
    
    
        fc
        
            org.springframework.web.servlet.DispatcherServlet
        
        1
    

    
        fc
        *.do
    
 
    
    
        
            org.springframework.web.context.ContextLoaderListener
        
    

@Section two : .class

现在的开发者们大都比较喜欢使用代码配置代码的方式来给项目进行配置,最新的springframework的官方文档中最开始也是介绍如何使用该配置方法的,也是先推荐使用的方法。但是在实际开发中,可能会遇到一些遗留项目,这些遗留项目大多都是使用.xml配置文件进行配置的,所以还是要掌握使用xml配置文件。

在写这些文件的时候,我们可以单独给它们创建一个包,把所有的配置文件类都集中在放在这个包底下,集中管理。
大体结构如图:


来自 - 我的马儿有些瘦

具体代码如下:
- 1、APPConfig.java

这个类和上面的applicationContext.xml文件的作用是一样的,用于springIOC容器的配置,可以在其中创建bean,纳入springIOC容器的管理,同时整合hibernate配置连接池(c3p0或者dbcp2,只要加入相应的jar包即可),创建数据源对象(DataSource)、会话工厂对象(SessionFactory)和事务管理器(TransactionManager),以便业务管理处理时自动注入这些需要的对象。

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableAspectJAutoProxy
@EnableTransactionManagement
@ComponentScan(basePackages = "com.qfedu.springmvc" )
public class AppConfig {
    
    @Bean
    public DataSource dataSource () {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/dang?useUnicode=true&CharacterEncoding=utf8");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setInitialSize(10);
        dataSource.setMaxTotal(50);
        dataSource.setMaxWaitMillis(15000);
        return dataSource;
    }
    
    @Bean
    public LocalSessionFactoryBean sessionFactory (DataSource dataSource) {
        LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
        bean.setDataSource(dataSource);
        Properties props = new Properties();
        props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQlDialect");
        props.setProperty("hibernate.show_sql", "true");
        props.setProperty("hibernate.format_sql", "true");
        bean.setHibernateProperties(props);
        return bean;
    }
    
    @Bean
    public HibernateTransactionManager transactionManager (DataSource dataSource) {
        HibernateTransactionManager tm = new HibernateTransactionManager();
        tm.setDataSource(dataSource);
        return tm;
    }

}

- 2、MyWebAppInitializer.java(名字可以自己决定,一般顾名思义)

这个Java类的主要作用是初始化webapp,拿到SpringIOC容器的类的类对象、springMVC的类的类对象、以及配置映射路径等。

这个类必须继承AbstractAnnotationConfigDispatcherServletInitializer这个类,重写回调方法。

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class[] getRootConfigClasses() {
        // 返回配置IOC容器的类的类对象
        return new Class[] { AppConfig.class };
    }

    @Override
    protected Class[] getServletConfigClasses() {
        // 返回配置SpringMVC的类的类对象
        return new Class[] { WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" }; //映射路径
    }
}

- 3、WebConfig .java

这是在配置视图解析器,用于配合前端控制器使用,在这里可以配置view的前缀和后缀

package com.qfedu.springmvc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.qfedu.springmvc.controller")
public class WebConfig extends WebMvcConfigurerAdapter {
    
    @Bean
    public ViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver  resolver = 
                new InternalResourceViewResolver();
        resolver.setViewClass(JstlView.class);
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    // 为了保证静态页面不用做根路径,做了以下处理
    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}

你可能感兴趣的:(SpringMVC的两种配置方式:.xml / .class)