DispatcherServlet是Spring MVC的核心,按照传统方式, 需要把它配置到web.xml中. 我个人比较不喜欢XML配置方式, XML看起来太累, 冗长繁琐. 还好借助于Servlet 3规范和Spring 3.1的功能增强, 可以采用一种全新的,更简洁的方式配置Spring MVC了. 下面按这种方式一个Hello World的MVC配置.

Step 1:先用eclipse创建一个Maven的WEB工程. pom.xml文件如下:

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 2   <modelVersion>4.0.0</modelVersion>
 3   <groupId>ocr</groupId>
 4   <artifactId>ocr</artifactId>
 5   <version>0.0.1-SNAPSHOT</version>
 6   <packaging>war</packaging>
 7
 8     <properties>
 9         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
10         <javaee-api.version>7.0</javaee-api.version>
11         <spring.version>4.2.0.RELEASE</spring.version>
12         <junit.version>4.12</junit.version>
13     </properties>
14
15     <dependencies>
16          <dependency>
17               <groupId>javax</groupId>
18               <artifactId>javaee-api</artifactId>
19               <version>${javaee-api.version}</version>
20         </dependency>
21         <dependency>
22                 <groupId>junit</groupId>
23                 <artifactId>junit</artifactId>
24                 <version>${junit.version}</version>
25         </dependency>
26         <dependency>
27             <groupId>org.springframework</groupId>
28             <artifactId>spring-context</artifactId>
29             <version>${spring.version}</version>
30         </dependency>
31         <dependency>
32             <groupId>org.springframework</groupId>
33             <artifactId>spring-aop</artifactId>
34             <version>${spring.version}</version>
35         </dependency>
36         <dependency>
37             <groupId>org.springframework</groupId>
38             <artifactId>spring-webmvc</artifactId>
39             <version>${spring.version}</version>
40         </dependency>
41         <dependency>
42             <groupId>org.springframework</groupId>
43             <artifactId>spring-web</artifactId>
44             <version>${spring.version}</version>
45         </dependency>
46
47         <dependency>
48             <groupId>javax.servlet</groupId>
49             <artifactId>jstl</artifactId>
50             <version>1.2</version>
51         </dependency>
52
53         <dependency>
54             <groupId>commons-logging</groupId>
55             <artifactId>commons-logging</artifactId>
56             <version>1.1.3</version>
57         </dependency>
58     </dependencies>
59
60
61     <build>
62         <plugins>
63             <plugin>
64                 <artifactId>maven-compiler-plugin</artifactId>
65                 <version>3.3</version>
66                 <configuration>
67                     <source>1.7</source>
68                     <target>1.7</target>
69                 </configuration>
70             </plugin>
71             <plugin>
72                 <artifactId>maven-war-plugin</artifactId>
73                 <version>2.6</version>
74                 <configuration>
75                     <warSourceDirectory>WebContent</warSourceDirectory>
76                     <failOnMissingWebXml>false</failOnMissingWebXml>
77                 </configuration>
78             </plugin>
79         </plugins>
80     </build>
81 </project>

Step 2: 配置DispatcherServlet. 需要创建一个Web初始化类OcrWebAppInitializer, 继承自AbstractAnnotationConfigDispatcherServletInitializer

 1 package com.chry.ocr.config;
 2
 3 import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
 4
 5 public class OcrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
 6
 7     @Override
 8     protected Class<?>[] getRootConfigClasses() {
 9         return new Class<?>[] { RootConfig.class };
10     }
11
12     @Override
13     protected Class<?>[] getServletConfigClasses() {
14         return new Class<?>[] { WebConfig.class };        //ָ指定Web配置类
15     }
16
17     @Override
18     protected String[] getServletMappings() {    //将DispatcherServlet映射到"/"
19         return new String[] { "/" };
20     }
21
22 }

Step 3: 配置Spring MVC视图解析WebConfig.java, 需要要创建一个类继承自WebMvcConfigurerAdapter

 1 package com.chry.ocr.config;
 2
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.ComponentScan;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.web.servlet.ViewResolver;
 7 import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
 8 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 9 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
10 import org.springframework.web.servlet.view.InternalResourceViewResolver;
11
12 @Configuration
13 @EnableWebMvc                                //启动SpringMVC
14 @ComponentScan("com.chry.ocr.controller")            //启动组件扫描
15 public class WebConfig extends WebMvcConfigurerAdapter {
16
17     //配置JSP视图解析器
18     @Bean
19     public ViewResolver viewResolver() {
20         InternalResourceViewResolver resolver = new InternalResourceViewResolver();
21         resolver.setPrefix("/WEB-INF/views/");
22         resolver.setSuffix(".jsp");
23         resolver.setExposeContextBeansAsAttributes(true);
24         return resolver;
25     }
26
27     //配置静态资源的处理
28     @Override
29     public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
30         configurer.enable();        //对静态资源的请求转发到容器缺省的servlet,而不使用DispatcherServlet
31     }
32
33 }

Step 4: 配置RootConfig.java

 1 package com.chry.ocr.config;
 2
 3 import org.springframework.context.annotation.ComponentScan;
 4 import org.springframework.context.annotation.ComponentScan.Filter;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.context.annotation.FilterType;
 7 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 8
 9 @Configuration
10 @ComponentScan( basePackages={"com.chry.ocr"},
11                 excludeFilters = { @Filter(type=FilterType.ANNOTATION,value=EnableWebMvc.class)}
12               )
13
14 public class RootConfig {
15
16 }

至此, 传统方式中需要通过web.xml进行配置的东西就已将全部完成有上面三个java类(OcrWebAppInitializer, RootConfig, WebConfig)完成. 可以开始写Controller和页面代码了

Step 5: 编写一个HomeController.java, 它将输出"hello World from Spring MVC"到home.jsp页面

 1 package com.chry.ocr.controller;
 2
 3 import static org.springframework.web.bind.annotation.RequestMethod.*;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 import org.springframework.web.bind.annotation.RequestMethod;
 7 import org.springframework.web.servlet.ModelAndView;
 8
 9 @Controller
10 public class HomeController {
11     @RequestMapping(value = "/", method=GET)
12     public ModelAndView home() {
13         String message = "Hello world from Spring MVC";
14         return new ModelAndView("home", "message", message);
15     }
16 }

Step 6: 编写一个jsp页面, 按照我们在视图解析器和Controller里面的配置,放在WEB-INF/views/home.jsp中

 1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="UTF-8"%>
 2 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 3 <html>
 4 <head>
 5 <title>Spring MVC Tutorial chry</title>
 6 <style type="text/css">
 7 </style>
 8 </head>
 9 <body>
10     <br>
11     <div style='text-align:center;'>
12         ${message}
13     </div>
14 </body>

Step 7: 至此所有工作完成, 使用maven的"clean install"选项进行编译打包后,在执行,访问http://localhost:8080即可. 页面效果和工程结构如下,工程里面没有web.xml

转载于:https://www.cnblogs.com/chry/p/6239510.html

如何用Java类配置Spring MVC(不通过web.xml和XML方式)相关推荐

  1. java配置springmvc_Java方式配置Spring MVC

    概述 使用Java方式配置Spring MVC,以及回顾一下Spring MVC的各种用法. Spring MVC简述 关于Spring MVC的介绍网上有很多,这里就不再赘述了,只是要说一下,Spr ...

  2. Spring MVC - 配置Spring MVC

    写在前面的话: 现在开始一段新的学习历程:Spring MVC.还是按照原来的三步走学习模式(what.why.how)进行讲解. 1.Spring MVC是什么(what) Spring MVC属于 ...

  3. java地址映射关系,Spring MVC——基础(简介,使用,地址映射)

    "大佬们"嘴中的SSH,SSM框架,我这种小白终于解除到第二个S了,关于Spring MVC框架,根据最近的学习发现,还是有很多不足和需要加强巩固的地方,所以,通过总结博客的方式将 ...

  4. Java中级篇——Spring MVC 是什么(附加响应状态代码列举)

    1.关于springMVC 基于Spring框架,主要解决后端服务器接受客户端服务器接受客户提交的请求,并给予响应相关的问题.的框架 目录 1.关于springMVC 基于Spring框架,主要解决后 ...

  5. linux spring mvc tomcat配置,Spring MVC配置详解

    一.Spring MVC处理流程 1.Spring MVC将所有请求都交由DispatchServlet进行处理. 2.DispatchServlet获取HandlerMapping(处理映射器),然 ...

  6. java spring获取bean_普通Java类获取Spring的Bean的方法

    普通Java类获取Spring的Bean的方法 在SSH集成的前提下.某些情况我们需要在Action以外的类中来获得Spring所管理的Service对象. 之前我在网上找了好几好久都没有找到合适的方 ...

  7. 使用Spring MVC开发Restful Web服务

    REST简介 摘自Wikipedia: REST风格的体系结构由客户端和服务器组成. 客户端向服务器发起请求: 服务器处理请求并返回适当的响应. 请求和响应围绕资源表示的传递而构建. 资源本质上可以是 ...

  8. 基于Spring + Spring MVC + Mybatis 高性能web构建

    一直想写这篇文章,前段时间 痴迷于JavaScript.NodeJs.AngularJS,做了大量的研究,对前后端交互有了更深层次的认识. 今天抽个时间写这篇文章,我有预感,这将是一篇很详细的文章,详 ...

  9. java 设置 cors,Spring MVC配置CORS

    Spring Framework 从4.2开始支持配置CORS. Spring MVC支持CORS的范围包括:方法级别配置CORS 全局配置CORS 方法级别配置CORS 使用注解@CrossOrgi ...

最新文章

  1. 【计算理论】计算复杂性 ( NP 类不同表述 | 团问题 | P 对 NP 问题 )
  2. poj2718 Smallest Difference
  3. 针对access数据库的增删改查
  4. 为什么美团全面推动 K8S 落地,咬紧牙关也要搞云原生?
  5. 设置jstree只展示到2级_你做的私域流量属于什么级别?80%的商家都还只在第2级...
  6. Tensorflow相关面试题
  7. 关于MySql的1146错误修正
  8. spring @component的作用详细介绍
  9. 20145239 《信息安全系统设计基础》第13周学习总结
  10. 为什么选择springcloud作为微服务架构
  11. python学习手册四版中文_Python学习手册(第4版) 中文版.pdf 全文免费
  12. CSAPP第二章家庭作业
  13. 干货分享|如何使用小鸟云服务器搭建Wordpress站点
  14. 百度网盘新用户超级会员多少钱
  15. 使用Rancher的RKE部署Kubernetes要点
  16. 计算机设备2后符号,表情符号含义展示的方法及设备与流程
  17. h5移动端生成海报,图文结合
  18. payjs插件php,基于payjs的discuz支付插件制作
  19. dodo:人脸识别方法个人见解(zz from prfans)
  20. 错觉图片生成实验 - 椭圆的艺术

热门文章

  1. JavaScript 的垃圾回收与内存泄露
  2. 常见网站各种类型页面的缓存时间及涉及的http头
  3. spring访问oracle函数,spring调用带参数的oracle函数应注意的问题
  4. ZYNQ_AXI4_Lite总线详解
  5. 三星emcp型号详解_嵌入式存储产品发展趋势:uMCP取代eMCP序幕拉开
  6. 牛客华为机试第6题python
  7. 从源码分析DEARGUI之add_tab 和 add_tab_bar
  8. opencv-python 视频处理之时光倒流
  9. AutoMl 的pytorch类似代码
  10. 算法(5) 归并排序