SpringMVC——新建SpringMVC项目

Posted sadoshi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringMVC——新建SpringMVC项目相关的知识,希望对你有一定的参考价值。

环境准备

eclipse:Oxygen.1 Release (4.7.1)

servlet:3.1.0

新建maven项目

 

 

关于转换项目为Servlet3.x,请参考《Eclipse新建基于Servlet3.x的maven项目》。

SpringMVC传统是通过XML方式配置。后来也增加了java方式配置。

XML方式配置

先编辑pom.xml

<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sadoshi.springmvc</groupId>
	<artifactId>test1</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>test1 Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<properties>
		<spring.version>5.3.9</spring.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.6</version>
		</dependency>
	</dependencies>
</project>

接着编辑src/main/webapp/WEB-INF/web.xml文件、如果没有webapp目录,可以按此路径新建。

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

	<display-name>Archetype Created Web Application</display-name>

	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springContext.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

新建一个HelloController:

package com.sadoshi.xmlconf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {
	
	private String message = "Welcome to Spring MVC!";

	@RequestMapping("/hello")
    public ModelAndView showMessage(@RequestParam(value = "name", required = false, defaultValue = "Spring") String name) {
 
        ModelAndView mv = new ModelAndView("hellospring");//指定视图向视图中添加所要展示或使用的内容,将在页面中使用
        mv.addObject("message", message);
        mv.addObject("name", name);
        return mv;
    }

}

在webapps下的WEB-INF的目录views下新建页面hellospring.jsp,如果找不到views目录就新建一个:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring 5 MVC - HelloWorld Index Page</title>
</head>
<body>
 
    <center>
        <h2>Hello World</h2>
        <h3>
            <a href="hello?name=zhangsan">点击跳转</a>
        </h3>
    </center>
</body>
</html>

在resource目录下新建springContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- 搜索spring控件 -->
	<context:component-scan base-package="com.sadoshi.xmlconf.controller"></context:component-scan>
	<!-- 视图页面配置 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/views/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
</beans>

注意<context:component-scan>标签里的包路径要改成自己项目需要扫描注解的包。

之后把项目添加到tomcat服务器中,启动tomcat。尝试访问路径http://localhost:8081/SpringMVCXml/hello

 端口号以自身的tomcat端口为准,因为默认的8080端口我用来跑别的业务,所以这个tomcat用8081端口。

java方式配置

pom.xml、HelloController、jsp页面都不需要改变。java配置方式主要是通过java代码,替代web.xml上的配置(但web.xml这个文件还是需要的),以及springContext.xml的配置。

首先我们的web.xml就不用这么复杂了:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:web="http://xmlns.jcp.org/xml/ns/javaee">
  <display-name>Archetype Created Web Application</display-name>
</web-app>

接着要继承AbstractAnnotationConfigDispatcherServletInitializer,创建MyWebAppInitializer。web容器初始化时会自动调用这个类的方法:

package com.sadoshi.springmvc.test3.config;

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

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class<?>[] {RootConfig.class};
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class<?>[] {WebConfig.class};
	}

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

}

接着创建RootConfig类,这个类我们添加了@ComponentScan注解,会扫描com.sadoshi.springmvc.test3.controller下的包。读者选择自己的Controller所在的包

package com.sadoshi.springmvc.test3.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;

@Configuration
@ComponentScan(basePackages = { "com.sadoshi.springmvc.test3.controller" },
        excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class)})
public class RootConfig {

}

最后创建WebConfig类,设置视图的路径等:

package com.sadoshi.springmvc.test3.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.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("com.sadoshi.springmvc.test3.config")
public class WebConfig implements WebMvcConfigurer{

	@Bean
	public ViewResolver viewResolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("WEB-INF/views/");
		resolver.setSuffix(".jsp");
		resolver.setExposeContextBeansAsAttributes(true);
		return resolver;
	}

	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		WebMvcConfigurer.super.configureDefaultServletHandling(configurer);
		configurer.enable();
	}

}

xml配置所需的springContext.xml不再需要。然后也是同样的方式启动和测试即可。以上就是java配置方式。

小结

本文只是把最简单的quick start展示出来。实际上SpringMVC的配置很多,java配置方式的套路也有很多(官网上有讲),后面或许研究源码的话可以深挖

以上是关于SpringMVC——新建SpringMVC项目的主要内容,如果未能解决你的问题,请参考以下文章

SpringMVC——新建SpringMVC项目

IDEA2022新建springMVC项目

eclipse maven新建springMVC项目(原创)

手动搭建SpringMVC项目

手动搭建SpringMVC项目

手动搭建SpringMVC项目