基于Spring MVC的Web应用的正确创建姿势

本文介绍了在IntelliJ IDEA中创建Spring MVC项目的正确步骤,包括选择Spring MVC模板,配置Tomcat,使用Maven添加依赖,创建配置文件和控制器,以及避免在web.xml中配置。强调了使用JavaConfig注解配置,@EnableWebMvc的使用细节,以及Spring 5.0中不再推荐使用WebMvcConfigurerAdapter的事实。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前一段时间,创建Spring MVC可能遇到了一些创建失败以及不规范的情况,今天就来系统的总结一下正确的创建姿势。


  1. 在IntelliJ IDEA中点击new project,然后选择Spring–>Spring MVC,点击next
    Spring MVC

  2. 出现下载的页面表示顺利进行,等待完毕即可,否则删除重新创建
    download

  3. 配置Tomcat,并设置热部署
    Tomcat

  4. 增加添加其他框架,选择Maven框架,并在Maven添加所需依赖
    Maven

  5. 将Maven中的依赖的包添加到项目中,双击Test下的Lib包,直到他们都被添加进去
    add

  6. 在Java源文件夹创建配置文件和一个测试控制器,并在web文件夹下创建相应的jsp
    config

WebInit.java

package FirstMVC.config;

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

public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {

    //创建ContextLoaderListener应用上下文
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] {RootConfig.class};
    }

    //创建DispatcherServlet应用上下文
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] {WebConfig.class};
    }

    //将DispatcherServlet映射到/
    protected String[] getServletMappings() {
        return new String[] {"/"};
    }
}

RootConfig.java

package FirstMVC.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;

//配置加载非Web组件的Bean的ContextLoaderListener应用上下文的JavaConfig
@Configuration
@ComponentScan(basePackages = {"FirstMVC"},
        excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class)})
public class RootConfig {
}

WebConfig.java

package FirstMVC.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.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

//配置DispatcherServlet应用上下文的JavaConfig
//@EnableWebMvc注解开启Spring MVC
@Configuration
//@EnableWebMvc
@ComponentScan("FirstMVC.Controller") //启用组件扫描, 组件扫描只会扫描到这里设置的包及其子包
public class WebConfig extends WebMvcConfigurationSupport {
    //配置ViewResolver视图解析器具体解析view名字的规则
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }

    //配置对静态资源的处理
    //通过调用DefaultServletHandlerConfigurer的enable()方法,
    //要求DispatcherServlet将对静态资源的请求转发到Servlet容器中默认的Servlet上,
    //而不是DispatcherServelt本身来处理这类请求.
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

Test.java

package FirstMVC.Controller;

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

@Controller
@RequestMapping(value = "/main")
public class Test {
    @RequestMapping(method = RequestMethod.GET)
    public String welcome(){
        return "home";
    }
}
  1. 关于web的设置,在web/WEB-INF/中,xml文件不要有任何配置,我们使用注解来配置Spring,而不是通过xml文件。并新建views文件夹,将jsp文件放到其中。
    这里写图片描述
    home.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>home</title>
    </head>

    <body>
        <h1>This is my home !</h1>
    </body>
</html>
测试运行

测试运行


一些要注意的点

  1. 采用JavaConfig注解的方式进行配置,那么xml文件不需要有任何的配置。
  2. RootConfig和WebConfig要注意组件扫描的包不要填错。
  3. @EnableWebMvc注解的一些问题:

EnableWebMvc

DelegatingWebMvcConfiguration

@EnableWebMvc注解引入了DelegatingWebMvcConfiguration类,而该类继承了WebMvcConfigurationSupport,如果只是用该注解,那么表示用的是默认设置。并且只有一个配置类可以有该注解,如果要自定义一些配置,可以采用如下配置:

  • 利用@EnableWebMvc注解,并实现WebMvcConfigurer
 @Configuration
 @EnableWebMvc
 @ComponentScan(basePackageClasses = MyConfiguration.class)
 public class MyConfiguration implements WebMvcConfigurer {
        //to do
 }
  • 如果想用一些高级设置,那么可以移除@EnableWebMvc注解,直接继承WebMvcConfigurationSupport
 @Configuration
 @ComponentScan(basePackageClasses = { MyConfiguration.class })
 public class MyConfiguration extends WebMvcConfigurationSupport {
        //to do
}

注意:书上继承WebMvcConfigurerAdapter(WebMvcConfigurer的实现类)来实现,但在Spring 5.0中WebMvcConfigurerAdapter已被废弃,不建议再使用了。

参考:Spring官方文档

1.0.5 从web项目迁移成maven项目 1.0.6 增加菜单框架ext实现,类路径调整 1.0.7 增加http工具类,demo例子 1.0.8 socket工具类,权限组件,菜单组件,jdbc分页支持多种数据库,ant路径工具类,增加jquery easyUI 1.0.9 版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 Word工具类 Java NIO实现socket工具类 分布式session jdk升级到1.7 嵌入式redis服务(只支持linux) 1.0.13 修改默认的beanName生成策略,controller参数扩展 1.0.14 分布式session使用zookeeper 1.0.15 zookeeper工具类优化 增加工具类 1.0.16 页面html标志修改 httpclient中文支持 工具类增强(zip,reflect,thread) 1.0.17 ftp服务端和客户端工具类,配置文件maven和web项目路径统一 1.1.0 soapui工具类(web版本) properties等工具类 1.1.1 工具类数据校验 jsp自定义标签 Spring自定义注解 默认requestMapping 1.1.2 代码生成器 1.1.3 首页修改 dateformat.js 时间参数转换 SpringMVC配置文件集中 快递参数接口 1.1.4 des加解密字符串和文件 1.1.5 redis 加锁,redis升级成2.8.2 freemarker工具类 1.1.6 spring websocket 实现在线聊天 maven升级jdk1.8 jetty9.2.4 web升级jdk1.7 tomcat7 1.1.7(maven only) 包名修改 从此不再支持web版本,只支持maven版本 1.1.8 jquery 图片预览插件 图片滚动显示插件 1.1.9 jquery实现鼠标在按钮上显示窗口,离开窗口和按钮时消失 1.1.10 rabbitMQ集成 视频截图 图片缩略图旋转 集成Mybatis 使用数据库连接池druid dubbo使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值