笔记23 搭建Spring MVC
搭建一个最简单的SpringMVC示例
1.配置DispatcherServlet
DispatcherServlet是Spring MVC的核心。在这里请求会第一次 接触到框架,它要负责将请求路由到其他的组件之中。
使用Java将DispatcherServlet配置在Servlet容器中,而不 会再使用web.xml文件。
SpittrWebAppInitializer.java==================web.xml
package spittr.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[] { RootConfig.class };
} @Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[] { WebConfig.class };
} @Override
protected String[] getServletMappings() { // 将DispatcherServlet映射到“/”
// TODO Auto-generated method stub
return new String[] { "/" };
} }
扩 展AbstractAnnotationConfigDispatcherServletInitializer的任意类都会自动地 配置Dispatcher-Servlet和Spring应用上下文,Spring的应用上下 文会位于应用程序的Servlet上下文之中。
2.Spring MVC配置类
WebConfig.java=========================myspringmvc-servlet.xml
package spittr.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.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration
@EnableWebMvc // 启用Spring MVC
@ComponentScan("spittr.web") // 启用组件扫描
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean // 配置JSP视图解析器
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
} @Override // 配置静态资源处理
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
// TODO Auto-generated method stub
configurer.enable();
} }
上面的代码中第一件需要注意的事情是WebConfig现在添加了 @Component-Scan注解,因此将会扫描spitter.web包来查找组件。稍后编写的控制器将会带有@Controller注 解,这会使其成为组件扫描时的候选bean。因此,不需要在配置 类中显式声明任何的控制器。
然后添加了一个ViewResolver bean。更具体来讲, 是Internal-ResourceViewResolver。功能是查找JSP文件,在查找的 时候,它会在视图名称上加一个特定的前缀和后缀。
最后,新的WebConfig类还扩展了WebMvcConfigurerAdapter 并重写了其configureDefaultServletHandling()方法。通过 调用DefaultServlet-HandlerConfigurer的enable()方法,要求DispatcherServlet将对静态资源的请求转发到Servlet容 器中默认的Servlet上,而不是使用DispatcherServlet本身来处理 此类请求。
3.RootConfig.java
因为主要聚焦于Web开 发,而Web相关的配置通过DispatcherServlet创建的应用上下文 都已经配置好了,因此现在的RootConfig相对很简单
package spittr.config; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration
@ComponentScan(basePackages = { "spittr" }, excludeFilters = {
@Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class) })
public class RootConfig { }
4.编写一个简单的控制器HomeController,用于显示首页
package spittr.web; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; @Controller // 声明为一个控制器
public class HomeController {
public HomeController() {
} @RequestMapping(value = "/", method = RequestMethod.GET)
public String home() {
return "home";
}
}
HomeController唯一的一个方法,也就是home()方法,带 有@RequestMapping注解。它的value属性指定了这个方法所要处 理的请求路径,method属性细化了它所处理的HTTP方法。
在本例 中,当收到对“/”的HTTP GET请求时(也可以是其他的,例如value的值为home),就会调用home()方法。
home()方法其实并没有做太多的事情:它返回了一 个String类型的“home”。这个String将会被Spring MVC解读为要 渲染的视图名称。
DispatcherServlet会要求视图解析器将这个 逻辑名称解析为实际的视图。 鉴于配置InternalResourceViewResolver的方式,视图 名“home”将会解析为“/WEB-INF/views/home.jsp”路径的JSP
5.home.jsp编写
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>Spittr</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
<h1>Welcome to Spittr</h1>
<a href="<c:url value="/spittles"/>">Spittles</a>
<a href="<c:url value="/spitter/register"/>">Register</a>
</body>
</html>
6.测试
测试分为两种,一种是采用单元测试的方法,另一种是部署到tomcat服务器上进行测试。
测试一:单元测试
<1>编写HomeControllerTest.java
package spittr.web; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; public class HomeControllerTest {
@Test
public void testHomePage() throws Exception {
HomeController controller = new HomeController();
// 搭建MockMvc
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
// 对“/”执行GET请求 预期得到home视图
mockMvc.perform(get("/")).andExpect(view().name("home"));
}
}
发起了对“/”的GET请求,并断言结果视图的名称为 home。它首先传递一个HomeController实例 到MockMvcBuilders.standaloneSetup()并调用build()来构 建MockMvc实例。然后它使用MockMvc实例来执行针对“/”的GET请 求并设置期望得到的视图名称。
<2>需要的jar包
官网下载spring-framework-5.0.5.RELEASE,外加junit-4.12jar和hamcrest-all-1.3.jar
测试二:服务器测试
<1>需要的jar包
<2>结果
最新文章
- DOM 概况
- HttpHelper类
- Swift 函数做参数和闭包做参数的一个细节差别
- Shiro-多Realm验证
- python load mat 并按变量名赋值
- PTPX中的time_based analysis
- Ubuntu 14.10 下查看系统硬件信息(实例详解)
- HDU-4725 The Shortest Path in Nya Graph 最短路
- [RxJS] Returning subscriptions from the subscribe function
- jquery 弹出框 showDialog.js具体用法
- 变态最大值--nyoj题目811
- Delphi XE的RTTI增强,动态Hook某些内部事件
- jQuery EasyUI 数字框(NumberBox)用法
- Linux学习历程——Centos 7 账户管理命令(用户篇)useradd usermod userdel
- html转markdown网站
- 在新建的python3环境下运行jupyter失败的原因
- 如何使squild服务只能使用自定义的端口号
- ECharts公共组件:title详解、 tooltip详解、toolbox详解、legend详解、dataZoom详解、visualMap全解
- Hyperledger Fabric(v1.2.0)代码分析1——channel创建
- Linux系统常用命令示例