Spring framework MVC 4.2.X无web.xml搭建web工程

版权声明:此文章如需转载请联系听云College团队成员阮小乙,邮箱:ruanqy#tingyun.com
无web.xml搭建web工程就是要将一般用web.xml配置的类及参数用编程的方式实现。用Annotation的方式可实现无xml化,或是减少一些xml配置。这里只是一个java web工程一般的配置,简单的可启用的web工程。给大家做个参考,大家要是有更复杂的需求可以在些基础上做添加。
工程是用maven建立的,我用的是apache-maven-3.0.5先看一眼pom.xml

<?xml version="1.0"?>

<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0">

<modelVersion>4.0.0</modelVersion>

<groupId>demo</groupId>

<artifactId>demo</artifactId>

<packaging>war</packaging>

<version>0.0.1-SNAPSHOT</version>

<name>demo Maven Webapp</name>

<url>http://maven.apache.org</url>


<build>

<finalName>demo</finalName>

</build>


<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

</properties>


<dependencies>


<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-aspects</artifactId>

<version>4.2.4.RELEASE</version>

</dependency>


<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>4.2.1.RELEASE</version>

</dependency>


<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-web</artifactId>

<version>4.2.1.RELEASE</version>

</dependency>


<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>

<version>4.2.1.RELEASE</version>

</dependency>


<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context-support</artifactId>

<version>4.2.1.RELEASE</version>

</dependency>


<dependency>

<groupId>log4j</groupId>

<artifactId>log4j</artifactId>

<version>1.2.17</version>

</dependency>


<dependency>

<groupId>javax.servlet.jsp</groupId>

<artifactId>javax.servlet.jsp-api</artifactId>

<version>2.3.2-b02</version>

</dependency>


<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

<version>1.2</version>

</dependency>


<dependency>

<groupId>javax.servlet</groupId>

<artifactId>javax.servlet-api</artifactId>

<version>3.1.0</version>

</dependency>

</dependencies>


<profiles>


<profile>

<id>jdk-1.8</id>


<activation>

<activeByDefault>true</activeByDefault>

<jdk>1.8</jdk>

</activation>


<properties>

<maven.compiler.source>1.8</maven.compiler.source>

<maven.compiler.target>1.8</maven.compiler.target>

<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>

</properties>

</profile>

</profiles>

</project>

工程目录结构如下:
图片描述
DefaultConfigration.java 为工程起动类。
要实现org.springframework.web.
WebApplicationInitializer接口的onStartup 方法。
内容如下:

package com.demo.common;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
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;

public class DefaultConfigration implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext context) throws ServletException {
        //以annotation的方式装来加载配置
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        //扫描spring的配置类。
        rootContext.scan("com.demo.common");
        context.addListener(new ContextLoaderListener(rootContext));

        //添加DispatcherServlet
        ServletRegistration.Dynamic dispatcher = context.addServlet("dispatcher", new DispatcherServlet(rootContext));
        dispatcher.setLoadOnStartup(1);
        //设置servlet mapping
        dispatcher.addMapping("/");
        // Set whether this servlet should dispatch an HTTP OPTIONS request to the #doService method.
        dispatcher.setInitParameter("dispatchOptionsRequest", "true");
        // Set whether this servlet should dispatch an HTTP TRACE request to the #doService method.
        dispatcher.setInitParameter("dispatchTraceRequest", "true");
        dispatcher.setAsyncSupported(true);

        // 设置编码
        CharacterEncodingFilter encodingfilter = new CharacterEncodingFilter();
        encodingfilter.setEncoding("UTF-8");
        encodingfilter.setForceEncoding(true);
        FilterRegistration.Dynamic encodingfilterDynamic = context.addFilter("encodingfilter", encodingfilter);
        encodingfilterDynamic.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, "dispatcher");

        // 加载国际化消息
        context.setInitParameter("javax.servlet.jsp.jstl.fmt.localizationContext", "message");
    }
}

SpringConfig.java,自己定义的类,主要用以bean的方式加载spring的配置。
内容如下:

package com.demo.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

//声明spring要加载类中的以@bean标注的bean
@Configuration
// 支持mvc
@EnableWebMvc
// 相当于<context:component-scan>
@ComponentScan(basePackages = "com.demo")
// 加载.properties配置文件
@PropertySource("classpath:sys-conf.properties")
// 加载.xml如果没有使用到额外的.xml配置文件,则无需加载
@ImportResource({ "classpath:spring-config.xml" })
public class SpringConfig {
    @Autowired
    Environment env;

    @Bean
    // 设置 InternalResourceViewResolver. 为跳转页面自动加上前缀及后缀
    public InternalResourceViewResolver jspViewResolver() {
        InternalResourceViewResolver jspViewResolver = new InternalResourceViewResolver();
        // 前缀
        jspViewResolver.setPrefix("/jsp/");
        // 后缀
        jspViewResolver.setSuffix(".jsp");
        return jspViewResolver;
    }

    @Bean
    // 加载配置文件,加载之后,可以在 @ImportResource({ "classpath:*.xml" })导入的文中使用占位符${}
    public PropertyPlaceholderConfigurer placeholderConfigurer() {
        PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
        placeholderConfigurer.setFileEncoding("UTF-8");
        // 用ClassPathResource的方式加载
        placeholderConfigurer.setLocations(new ClassPathResource("sys-conf.properties"));
        return placeholderConfigurer;
    }
};

package com.demo.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

//声明spring要加载类中的以@bean标注的bean
@Configuration
// 支持mvc
@EnableWebMvc
// 相当于
@ComponentScan(basePackages = “com.demo”)
// 加载.properties配置文件
@PropertySource(“classpath:sys-conf.properties”)
// 加载.xml如果没有使用到额外的.xml配置文件,则无需加载
@ImportResource({ “classpath:spring-config.xml” })
public class SpringConfig {
@Autowired
Environment env;

@Bean
// 设置 InternalResourceViewResolver. 为跳转页面自动加上前缀及后缀
public InternalResourceViewResolver jspViewResolver() {
    InternalResourceViewResolver jspViewResolver = new InternalResourceViewResolver();
    // 前缀
    jspViewResolver.setPrefix("/jsp/");
    // 后缀
    jspViewResolver.setSuffix(".jsp");
    return jspViewResolver;
}

@Bean
// 加载配置文件,加载之后,可以在 @ImportResource({ "classpath:*.xml" })导入的文中使用占位符${}
public PropertyPlaceholderConfigurer placeholderConfigurer() {
    PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
    placeholderConfigurer.setFileEncoding("UTF-8");
    // 用ClassPathResource的方式加载
    placeholderConfigurer.setLocations(new ClassPathResource("sys-conf.properties"));
    return placeholderConfigurer;
}

}
WebConfig.java实现
org.springframework.web.servlet.config.
annotation.WebMvcConfigurerAdapter
用来自定义一些sprngmvc关于web的配置。如需配置,可直接重写其相关的方法。
图片描述
Global.java主要是用做存放全局变量。在这里只演示如何加载*.properties中的值
内容如下:

package com.demo.common;

import java.util.HashMap;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

//@Component会自动导入SpringConfig.java中已经加载过的*.properties文件内容到 Environment中。
@Component
public class Global {

    @Autowired
    Environment env;

    public static int KEY_PAGE_ROWS = 12;

    // 定义允许上传的文件扩展名
    public static final HashMap<String, String> uploadExtMap = new HashMap<String, String>();

    @PostConstruct
    public void init() {
        KEY_PAGE_ROWS = Integer.parseInt(env.getProperty("page.rows", "12"));
    }
}

TestController.java用来做测试的Controller,内容如下:

package com.demo.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestController {
    @RequestMapping(value = "/hw")
    public String hello(HttpServletRequest request, Model model) throws IOException {
        model.addAttribute("hello", "Hello World!");
        return "hello";
    }
}

工程启动后可访问:http://localhost/demo/demo.html
图片描述
http://localhost/demo/hw.do
图片描述
想阅读更多技术文章,请访问听云技术博客,访问听云官方网站感受更多应用性能优化魔力。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在使用Spring框架的MVC模式进行Web开发时,我们需要导入org.springframework.web.servlet包。这个包中包含了一些用于处理HTTP请求和响应的类和接口。 首先,在项目中使用Spring框架需要在项目的构建工具中加入spring-webmvc依赖,例如在Maven项目中,在pom.xml文件中添加以下依赖项: ```xml <dependencies> <!-- Spring webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.1.RELEASE</version> </dependency> </dependencies> ``` 然后,在我们的Java类中使用import语句导入org.springframework.web.servlet包中的相应类和接口。例如,在一个Controller类中,我们可能需要导入以下类: ```java import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; ``` 其中,Controller是一个接口,我们可以通过实现该接口来处理HTTP请求。ModelAndView类表示一个包含模型数据和相应视图的对象。 当我们导入了org.springframework.web.servlet包后,就可以使用其中的类和接口来编写处理Web请求的逻辑了。比如,我们可以创建一个实现了Controller接口的类,重写handleRequest方法来处理具体的请求,并返回相应的视图。 总结来说,导入org.springframework.web.servlet包是为了能够使用Spring框架提供的处理HTTP请求和响应的类和接口。这些类和接口可以帮助我们简化Web开发过程,并提供了一些方便的方法和工具来处理请求、渲染视图等操作。 ### 回答2: 为了使用org.springframework.web.servlet包,您需要执行以下步骤: 1. 打开您的Java项目,并确保您的项目已经配置了Maven或Gradle依赖管理工具。 2. 在您的项目配置文件(例如pom.xml或build.gradle)中添加Spring MVC的相关依赖。 3. 在依赖配置文件中,添加以下依赖项: - Maven: ```xml <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>您需要的版本号</version> </dependency> </dependencies> ``` - Gradle: ```groovy dependencies { implementation 'org.springframework:spring-webmvc:您需要的版本号' } ``` 4. 保存并更新您的项目配置文件,以便Maven或Gradle可以自动下载所需的库和依赖项。 5. 在您的Java类中,导入org.springframework.web.servlet相关类: ```java import org.springframework.web.servlet.*; ``` 6. 现在,您可以在您的代码中使用Spring MVC提供的类和功能。 通过遵循上述步骤,您就可以成功导入org.springframework.web.servlet包,并开始使用Spring MVC框架提供的功能开发Web应用程序。 ### 回答3: 导入org.springframework.web.servlet包是为了使用Spring MVC框架提供的Servlet相关的类和接口。Spring MVC是一种基于Servlet的Web应用程序框架,用于开发灵活、可扩展的Web应用程序。 在导入org.springframework.web.servlet包之前,需要首先在项目的构建管理工具中添加对Spring MVC框架的依赖,例如使用Maven的话,在项目的pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>版本号</version> </dependency> ``` 这将自动引入org.springframework.web.servlet包及其相关依赖。 在代码中导入org.springframework.web.servlet包,可以使用以下语句: ``` import org.springframework.web.servlet.*; ``` 导入该包后,可以使用Spring MVC提供的一系列类和接口,例如: - DispatcherServlet:Servlet派发器,用于将请求派发给相应的处理器。 - HandlerMapping:处理器映射,用于将请求映射到相应的处理器。 - HandlerAdapter:处理器适配器,用于处理请求并调用相应的处理器方法。 - ModelAndView:模型和视图,用于封装处理器处理后的数据和视图信息。 - ViewResolver:视图解析器,用于根据逻辑视图名解析出具体的视图。 导入org.springframework.web.servlet包后,就可以利用Spring MVC的功能进行Web应用程序的开发,包括URL映射、请求处理、参数绑定、模型和视图的处理等,提供了快速、简单和灵活的Web开发方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值