Spring MVC项目快速搭建
示例
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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.wisely</groupId> <artifactId>hightlight_springmvc4</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <jsp.version>2.2</jsp.version> <jstl.version>1.2</jstl.version> <servlet.version>3.1.0</servlet.version> <spring-framwork.version>4.1.5.RELEASE</spring-framwork.version> <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> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-framwork.version}</version> </dependency> <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> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring-framwork.version}</version> </dependency> <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> </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>
</plugins>
</build> </project> |
logback.xml |
<?xml version="1.0" encoding="UTF-8"?> <configuration scan="true" scanPeriod="1 seconds"> <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator"> <restJUL>true</restJUL> </contextListener> <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>logback: %d{yyyy-MM-dd HH:mm:ss.SSS} %logger{36} - %msg%n</pattern> </encoder> </appender> <logger name="org.springframework.web" level="DEBUG"> <root level="info"> <appender-ref ref="console"/> </root> </logger>
</configuration> |
在src/main/resources下建立views目录,并在此目录下新建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> <pre>Welcome to Spring MVC world</pre> </body> </html> |
SpringMVC配置 |
package hightlight_springmvc4;
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;
@Configuration @EnableWebMvc @ComponentScan("hightlight_springmvc4") public class MyMvcConfig {
public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/classes/views/"); viewResolver.setSuffix(".jsp"); viewResolver.setViewClass(JstlView.class); return viewResolver; }
}
|
Web配置 |
package hightlight_springmvc4;
import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet;
/** * 1.WebApplicationInitializer是Spring提供用来配置Servlet3.0+配置接口,从而实现了替代web.xml的位置。实现此接口将会自动被SpringServletContainerInitializer获取到 * 2.新建WebApplicationContext,注册配置类,并将其和当前servletContext关联。 * 3.注册Spring MVC的DispatcherServlet * */ public class WebInitializer implements WebApplicationInitializer {
@Override public void onStartup(ServletContext servletContext) throws ServletException { //1 AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(MyMvcConfig.class); ctx.setServletContext(servletContext); //2 Dynamic servlet =servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); //3 servlet.addMapping("/"); servlet.setLoadOnStartup(1); }
}
|
简单的控制器 |
package hightlight_springmvc4;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;
/** * 1.利用Controller注解声明是一个控制器。 * 2.利用@RequestMapping配置URL和方法之间的映射 * 3.通过ViewResolver的Bean配置,返回值为index,说明我们的页面放置的路径为/WEB-INF/classes/views/index.jsp * */ @Controller //1 public class HelloController { @RequestMapping("/index") //2 public String hello() { return "index"; //3 } }
|
Spring MVC的常用注解
1.点睛
Spring MVC常用以下几个注解。
(1)@Controller
@Controller注解在类上,表明这个类是Spring MVC里的Controller,将其声明为Spring的一个Bean,Dispatcher Servlet会自动扫描注解了此注解的类,并将Web请求映射到注解了@RequestMapping的方法上。这里特别指出,在声明普通Bean的时候,使用@Component、@Service、@Repository、@Controller都组合了@Compoment元注解;但在Spring MVC声明控制器Bean的时候,只能使用@Controller。
(2)@RequestMapping
@RequestMapping注解是用来映射web请求、处理类和方法的。@RequestMapping可注解在类或方法上。注解在方法上的@RequestMapping路径会继承注解在类上的路径,@RequestMapping支持Servlet的request和response作为参数,也支持对request和response的媒体类型进行配置。
(3)@ResponseBody
@ResponseBody支持将返回值放在response体内,而不是返回一个页面。外面在很多基于ajax程序的时候,可以以此注解返回数据而不是页面;此注解可放置在返回值前或者方法上。
(4)@RequestBody
@RequestBody允许request的参数在request体中,而不是直接连接在地址后面。此注解放置在参数前。
(5)@PathVariable
@PathVariable用来接收路径参数,如/news/001,看接收001作为参数,此注解放置在参数前。
(6)@RestController
@RestController是一个组合注解,组合了@Controller和@ResponseBody,着就意味着当你只开发一个和页面交互数据的控制的时候,需要使用此注解。若没有此注解,要想实现上述功能,则需自己在代码中加@Controller和@ResponseBody两个注解。
Spring Boot快速搭建
定制Banner
在Spring Boot启动的时候会有一个默认图案,在src/main/resources下新建一个banner.txt,通过改变文件内容可以改变启动图案。(http://patorjk.com/software/taag)
Spring Boot的配置文件
Spring Boot使用一个全局的配置文件Application.properties放置在src/main/resources目录或者类路径的/config下。
#端口号修改为80 server.port=80 #将默认的访问路径/修改为/helloboot server.context-path=/helloboot |
使用XML配置
Spring Boot提倡零配置,即无xml配置,但是在实际项目中,可能有一些特殊的要求你必须使用xml配置,这时我们可以通过Spring提供的@ImportResource来加载xml配置。例如:
@ImportResources({“classpath:some-context.xml”,”classpath:another-context.xml”})
常规属性配置
通过@PropertySource指明properties文件的位置,然后通过@value注入值。在SpringBoot中,我们只需要在application.properties定义属性,直接使用@Value注入即可。
Thymeleaf基础知识
Thymeleaf是一个java类库,他是一个xml/xhtml/html5的引擎末班,可以作为MVC的web应用的view层。Thymeleaf还提供了额外的模块与Spring MVC集成,所以我们可以使用Thymeleaf完全替代JSP。
引入Thymeleaf
下面的代码是一个基本Thymeleaf模版页面,在这里我们引入Bootstrap(作为样式控制)和jQuary(Dom操作),当然他们不是必须的。
代码解释
通过xmlns:th=http://www.thymeleaf.org 命名空间,将镜头页面转换为动态视图。需要进行动态处理的元素使用“th:“为前缀;
通过“@{}“引用web静态资源,这在jsp下是极易出错的。
访问model中的数据
通过“${}“访问model中的属性,这和JSP极为相似。
代码解释
(1)使用<span th:test=”${singelPerson.name}”></span>访问model中的singlePerson的name属性。注意:需要处理的动态内容需要加上“th”前缀。
在JavaScript中访问model
在项目中,外面经常需要在javaScript访问model中的值,在Thymeleaf里实现代码如下:
<title>Insert title here</title> <script th:inline="javascript"> var single=[[${singlePerson}]]; </script> |
代码解释
·通过th:inline=”javascript”添加到script标签,这样JavaScript代码即可访问model中的属性;
·通过”[[${}]]”格式获得实际的值。