Eclispe中SpringMVC的简单开发---Annotation、Eclipse中SpringMVC的简单开发---XML配置两篇博文已经交代了SpringMVC的开发流程,这两种分别使用注解以及xnl文件来进行对控制层进行配置。但是无论哪种文件,还是需要进行xml文件的配置,比如web.xml和SpringMVC配置文件。但是随着servlet的发展,现在支持无web.xml的配置方式的出现,直接采用Java类来替换xml文件的配置。接下来则将上述例子在IDEA中采用无配置开发。以下是开发流程。
1.IDEA中创建Maven项目
首先创建一个Maven项目HelloSpringMVC,如下图所示:
接着将其配置成web项目,右键项目点击add framework support...
选择web application
至此,Maven项目建立成功,接着进行之后的操作。
2.pom.xml文件
由于是Maven项目 ,所以需要将依赖jar包都写入pom.xml文件,本项目的pom文件如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.carson</groupId>
<artifactId>HelloSpringMVC</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- Generic properties -->
<java.version>1.7</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>3.1.0</servlet.version>
<!-- Spring -->
<spring-framework.version>4.1.5.RELEASE</spring-framework.version>
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- 其他web依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- 使用SLF4J和LogBack作为日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
<version>${logback.version}</version>
</dependency>
<!--对json和xml格式的支持 -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.5.3</version>
</dependency>
<!-- file upload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 非必需,可简化IO操作 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.日志配置
在src/main/resources目录下(自己手动新建目录),新建logback.xml用来配置日志,如下所示:
<?xml version="1.0" encoding="UTF-8" ?>
<configuration scan = "true" scanPeriod="1 seconds">
<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
<resetJUL>true</resetJUL>
</contextListener>
<jmxConfigurator/>
<appender name = "console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>logback: %d{HH:mm:ss.SSS} %logger{36} - %msg%n</pattern>
</encoder>
<loogger name = "org.springframework.web" level = "DEBUG"/>
<root>
<appender-ref ref = "console"/>
</root>
</appender>
</configuration>
将org.springframework.web包下的类的日志级别设置为DEBUG,我们开发Spring MVC经常出现和参数类型相关的4XX错误,设置此项可以获取更详细的错误信息。
3.Spring MVC配置
由于本项目没有涉及复杂的功能,仅是简单的页面显示,因此只涉及一个视图解析器。这里构造一个SpringMVC的配置类,
package com.carson.spring_mvc;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
* Spring MVC 配置
*/
@Configuration
@EnableWebMvc
@ComponentScan("com.carson.spring_mvc")
public class MvcConfig {
@Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/");//页面会自动编译到该目录下面
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
}
可以该类只是把之前的配置文件转换成Java类,该类中的前缀设为"/WEB-INF/classes/views/",这个路径是指页面运行时所在路径,一般页面代码会自动编译到"/WEB-INF/classes/views/"。
4.web配置
可以看出之前使用xml文件配置web时,内容主要是SpringMVC控制器dispacherservlet的注册、SpringMVC的配置文件的注册、映射位置的编写。而这些则通过一个Java类实现,如下所示:
package com.carson.spring_mvc;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebInitializer implements WebApplicationInitializer {//WebApplicationInitializer是Servlet3.0+配置的接口,从而实现了替代web.xml的位置。实现此接口将会自动被SpringServletContainerInitializer(用来启动Servlet3.0容器)获取到
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(MvcConfig.class);//注册Spring MVC配置类
ctx.setServletContext(servletContext);//和当前servletContext关联
ServletRegistration.Dynamic servlet = servletContext.addServlet("diaspatcher",new DispatcherServlet(ctx));//注册Spring MVC的DispatcherServlet。
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
WebApplicationInitializer是Spring提供用来配置Servlet3.0+配置的接口,从而实现替代web.xml的位置。实现此接口将会自动被SpringServletContainerInitializer(用来启动Servlet3.0容器)获取到。
5.页面编写
首先是index.jsp的编写
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="hello">welcome</a>
<a href="reject">reject</a>
</body>
</html>
接着是hello.jsp和reject.jsp,这两个文件则放在/WEB-INF/jsp/(自行新建)下:
hello.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<div>
<center>
<body>
hello,carson!welcome to this page!
</body>
</center>
</div>
<form action="hello.action"></form>
</html>
reject.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>sorry,you can't open this page</h1>
</body>
</html>
6.控制器开发
package com.carson.spring_mvc.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController
{
@RequestMapping("/index")
public String index(){
return "index";
}
@RequestMapping("/hello")
public String hello(Model model)
{
model.addAttribute("msg","hello!Carson!welcome to this page.");
return "hello";
}
@RequestMapping("/reject")
public String reject()
{
System.out.println("sorry,you can't open this page");
return "reject";
}
}
7.运行
配置tomcat并发布相应的包。
启动,输入http://localhost:8080/index得到如下页面:
点击welcome
点击reject
比较这三种方式,可以看出得到相同页面,但是这种方式的话xml配置文件更少,只需要用Java类来替代xml配置文件即可,这样门槛更低,只需要了解web、springmvc相关的类即可。
最后附上目录: