SpringMVC入门项目搭建JavaConfig配置方式(零XML)



简介

Spring项目搭建基础请阅读博主上篇文章:SpringMVC入门项目搭建XML配置方式

对比xml与Javacofig配置方式
xml:①配置繁琐②耦合低
Javacofig:方便灵活②耦合相对较高
其他方面读者自行体会.

软件环境

eclipse+maven(3.3.9)+tomcat(8)+jdk(笔者使用1.8)

Jar包准备

  <!-- 导入java ee jar 包 -->
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
    </dependency>
    <!-- JavaConfig方式搭建SpringMvc环境,servlet最低版本3.0.1 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
    </dependency>
<!-- spring framework 建议4.0以上-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

项目搭建结构图

这里写图片描述

创建项目

基础项目这里将不做赘述

WebAppInitializer.java与web.xml比对 ———->程序入口
web.xml
<?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"   
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
    id="WebApp_ID" version="3.0">  
     <!-- 字符集过滤器 -->  
    <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>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  <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>
    <servlet-mapping>
        <servlet-name>dispatcherservlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
  <!-- 首页 -->  
    <welcome-file-list>  
        <welcome-file>index.jsp</welcome-file>  
    </welcome-file-list>  
</web-app>  
WebAppInitializer.java
package com.src.xiaobu.config;


import java.nio.charset.StandardCharsets;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import com.src.xiaobu.config.filter.SysFilter;
/**
 * Created by FANQIBU on 2017/4/17.
 */
public class WebAppInitializer   implements WebApplicationInitializer{
    /**
     * 配置其他的 servlet 和 filter
     *
     * @param servletContext
     * @throws ServletException
     */
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        //字符集过滤器 
        FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class);
        encodingFilter.setInitParameter("encoding", String.valueOf(StandardCharsets.UTF_8));
        encodingFilter.setInitParameter("forceEncoding", "true");
        encodingFilter.addMappingForUrlPatterns(null, false, "/*");
        //系统过滤器 
        FilterRegistration.Dynamic sysFilter = servletContext.addFilter("sysFilter", SysFilter.class);
        sysFilter.addMappingForUrlPatterns(null, false, "/*");
        //实施这类WebApplicationContext接受注明@Configuration的类
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();  
        //配置注释的类
        rootContext.register(RootConfig.class);  
        servletContext.addListener(new ContextLoaderListener(rootContext));  
        //同上
        AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();  
        webContext.register(WebConfig.class);  
       //声明SpringMVC核心控制器
        DispatcherServlet dispatcher = new DispatcherServlet(webContext);
        dispatcher.setThrowExceptionIfNoHandlerFound(true);
        //DispatcherServlet添加到servletContext(上下文)
        ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher", dispatcher);  
        registration.setLoadOnStartup(1);  
        //映射路径
        registration.addMapping("/");   
    }
}
对比图

这里写图片描述
这里写图片描述

RootConfig.java+WebConfig.java与spring-mvc.xml比对 ———->SpringMVC配置文件
spring-mvc.xml
<?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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
    <context:component-scan base-package="com.sc.xiaobu.controller" />

    <!-- 视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
            <property name="prefix" value="/WEB-INF/pages/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
        <!-- 上传文件支持 -->  
    <bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >  
        <!-- 大小限制 -->  
        <property name="maxUploadSize" value="10485760"></property>      
        <property name="defaultEncoding" value="utf-8"></property>     
    </bean> 
      <!-- 访问静态资源 -->
36     <mvc:resources location="/static" mapping="/**"/>
</beans>
RootConfig.java
package com.src.xiaobu.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * Created by FANQIBU on 2017/4/17.
 */
@Configuration
@ComponentScan(basePackages={"com.src.xiaobu.controller"},
        excludeFilters={
                @ComponentScan.Filter(type= FilterType.ANNOTATION, value=EnableWebMvc.class)
        })
        //配置mybatis设置
/*@MapperScan("com.hbjr.mapper")  */
public class RootConfig {
}
WebConfig.java
package com.src.xiaobu.config;

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.scheduling.annotation.EnableScheduling;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * Created by FANQIBU on 2017/4/17.
 */
@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy
@EnableScheduling
@ComponentScan(basePackages = {"com.src.xiaobu.*"})
public class WebConfig extends WebMvcConfigurerAdapter {
//视图解析器
    @Bean
    public ViewResolver viewResolver(){
        InternalResourceViewResolver resolver =
                new InternalResourceViewResolver();

        resolver.setPrefix("/WEB-INF/pages/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);

        return resolver;
    }
    //跳转主页面
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
      registry.addViewController("/").setViewName("login");
    }
    //   访问静态资源
    @Override  
    public void addResourceHandlers(ResourceHandlerRegistry registry) {  
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }  
    /**                                                            
     * 描述 : <文件上传处理器>                                                                                                                                                                                                                                           
     * @return                                                                                                        
     */    
    @Bean(name="multipartResolver")  
     public CommonsMultipartResolver commonsMultipartResolver(){  
         CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver();
         multipartResolver.setResolveLazily(true);
         multipartResolver.setMaxUploadSize(1048576000L);
         return multipartResolver;  
     }  
    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer){
        configurer.enable();
    }
    /**
     * 异常处理
     * @return
     */
    /*
    @Bean
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver(){
        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
        // 1:page and statusCode pare 
          *//*resolver.addStatusCode("error/404", 404);
          resolver.addStatusCode("error/500", 500); *//*
        // 2: you also can use method setStatusCodes(properties)
          //resolver.setStatusCodes(properties);
        //set views for exception 
        Properties pro= new Properties();  
        try {
            pro.load(this.getClass().getResourceAsStream("/exception.properties"));
        } catch (IOException e) {
            logger.error("load exception.properties error !", e);
        }
        resolver.setExceptionMappings(pro);
        return resolver;
    }*/
   //向容器中添加自定义工具类
   /* @Bean(name="springBeanFactoryUtils")
    public SpringBeanFactoryUtils springBeanFactoryUtils(){
        return new SpringBeanFactoryUtils();
    }*/
}

运行展示

这里写图片描述

项目源码下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值