SpringMVC (1) - New SpringMVC project

Environmental preparation

eclipse:Oxygen.1 Release (4.7.1)

servlet:3.1.0

Create a new maven project

 

 

For converting the project to Servlet3.x, please refer to " Eclipse Creates a Maven Project Based on Servlet3.x ".

SpringMVC is traditionally configured through XML. Later, java configuration was added.

XML configuration

Edit pom.xml first

<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>

Then edit the src/main/webapp/WEB-INF/web.xml file. If there is no webapp directory, you can create a new one according to this path.

<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>

Create a new 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;
    }

}

Create a new page hellospring.jsp under the WEB-INF directory views under webapps, if you can’t find the views directory, create a new one:

<%@ 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>

Create a new springContext.xml in the resource directory:

<?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>

Note that the package path in the <context:component-scan> tag should be changed to the package that needs to be scanned for annotations in your own project.

Then add the project to the tomcat server and start tomcat. Try to access the path http://localhost:8081/SpringMVCXml/hello

 The port number is subject to its own tomcat port, because I use the default port 8080 to run other businesses, so this tomcat uses port 8081.

java configuration

pom.xml, HelloController, jsp pages do not need to be changed. The java configuration method mainly uses java code to replace the configuration on web.xml (but the web.xml file is still required), and the configuration of springContext.xml.

First of all, our web.xml does not need to be so complicated:

<?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>

Then inherit AbstractAnnotationConfigDispatcherServletInitializer and create MyWebAppInitializer. The method of this class is automatically called when the web container is initialized:

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[] {"/"};
	}

}

Then create the RootConfig class. We added the @ComponentScan annotation to this class, which will scan the packages under com.sadoshi.springmvc.test3.controller. Readers choose the package where their Controller is located

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 {

}

Finally, create the WebConfig class, set the path of the view, etc.:

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();
	}

}

The springContext.xml required for xml configuration is no longer needed. Then start and test in the same way. The above is the java configuration method.

summary

This article just shows the simplest quick start. In fact, there are many configurations of SpringMVC, and there are many routines of java configuration methods (the official website talks about it). Maybe you can dig deeper if you study the source code later.

Guess you like

Origin blog.csdn.net/sadoshi/article/details/120954389