成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

Spring實戰(zhàn)5-基于Spring構(gòu)建Web應(yīng)用

sourcenode / 1162人閱讀

摘要:的框架用于解決上述提到的問題,基于模型,可以幫助開發(fā)人員構(gòu)建靈活易擴展的應(yīng)用。在這一章中,將專注于構(gòu)建該應(yīng)用的層,創(chuàng)建控制器和顯示,以及處理用戶注冊的表單。類有兩個靜態(tài)接口,代表兩種模擬服務(wù)的方式獨立測試和集成測試。

主要內(nèi)容

將web請求映射到Spring控制器

綁定form參數(shù)

驗證表單提交的參數(shù)

寫在前面:關(guān)于Java Web,首先推薦一篇文章——寫給java web一年左右工作經(jīng)驗的人,這篇文章的作者用精練的話語勾勒除了各種Java框架的緣由和最基本的原理。我們在學(xué)習(xí)Spring的過程中也要切記,不僅要知道怎么做?還要深究背后的思考和權(quán)衡。

對于很多Java程序員來說,他們的主要工作就是開發(fā)Web應(yīng)用,如果你也在做這樣的工作,那么你一定會了解到構(gòu)建這類系統(tǒng)所面臨的挑戰(zhàn),例如狀態(tài)管理、工作流和參數(shù)驗證等。HTTP協(xié)議的無狀態(tài)性使得這些任務(wù)極具挑戰(zhàn)性。

Spring的web框架用于解決上述提到的問題,基于Model-View-Controller(MVC)模型,Spring MVC可以幫助開發(fā)人員構(gòu)建靈活易擴展的Web
應(yīng)用。

這一章將涉及Spring MVC框架的主要知識,由于基于注解開發(fā)是目前Spring社區(qū)的潮流,因此我們將側(cè)重介紹如何使用注解創(chuàng)建控制器,進(jìn)而處理各類web請求和表單提交。在深入介紹各個專題之前,首先從一個比較高的層面觀察和理解下Spring MVC的工作原理。

5.1 Spring MVC入門 5.1.1 request的處理過程

用戶每次點擊瀏覽器界面的一個按鈕,都發(fā)出一個web請求(request)。一個web請求的工作就像一個快遞員,負(fù)責(zé)將信息從一個地方運送到另一個地方。

從web請求離開瀏覽器(1)到返回響應(yīng),中間經(jīng)歷了幾個節(jié)點,在每個節(jié)點都進(jìn)行一些操作用于交換信息。下圖展示了Spring MVC應(yīng)用中web請求會遇到的幾個節(jié)點。

請求旅行的第一站是Spring的DispatcherServlet,和大多數(shù)Javaweb應(yīng)用相同,Spring MVC通過一個多帶帶的前端控制器過濾分發(fā)請求。當(dāng)Web應(yīng)用委托一個servlet將請求分發(fā)給應(yīng)用的其他組件時,這個servlert稱為前端控制器(front controller)。在Spring MVC中,DispatcherServlet就是前端控制器。

DispatcherServlet的任務(wù)是將請求發(fā)送給某個Spring控制器。控制器(controller)是Spring應(yīng)用中處理請求的組件。一般在一個應(yīng)用中會有多個控制器,DispatcherServlet來決定把請求發(fā)給哪個控制器處理。DispatcherServlet會維護(hù)一個或者多個處理器映射(2),用于指出request的下一站——根據(jù)請求攜帶的URL做決定。

一旦選好了控制器,DispatcherServlet會把請求發(fā)送給指定的控制器(3),控制器中的處理方法負(fù)責(zé)從請求中取得用戶提交的信息,然后委托給對應(yīng)的業(yè)務(wù)邏輯組件(service objects)處理。

控制器的處理結(jié)果包含一些需要傳回給用戶或者顯示在瀏覽器中的信息。這些信息存放在模型(model)中,但是直接把原始信息返回給用戶非常低效——最好格式化成用戶友好的格式,例如HTML或者JSON格式。為了生成HTML格式的文件,需要把這些信息傳給指定的視圖(view),一般而言是JSP。

控制器的最后一個任務(wù)就是將數(shù)據(jù)打包在模型中,然后指定一個視圖的邏輯名稱(由該視圖名稱解析HTML格式的輸出),然后將請求和模型、視圖名稱一起發(fā)送回DispatcherServlet4)。

注意,控制器并不負(fù)責(zé)指定具體的視圖,返回給DispatcherServlet的視圖名稱也不會指定具體的JSP頁面(或者其他類型的頁面);控制器返回的僅僅是視圖的邏輯名稱,DispatcherServlet用這個名稱查找對應(yīng)的視圖解析器(5),負(fù)責(zé)將邏輯名稱轉(zhuǎn)換成對應(yīng)的頁面實現(xiàn),可能是JSP也可能不是。

現(xiàn)在DispatcherServlet就已經(jīng)知道將由哪個視圖渲染結(jié)果,至此一個請求的處理就基本完成了。最后一步就是視圖的實現(xiàn)(6),最經(jīng)典的是JSP。視圖會使用模型數(shù)據(jù)填充到視圖實現(xiàn)中,然后將結(jié)果放在HTTP響應(yīng)對象中(7)。

5.1.2 設(shè)置Spring MVC

如上一小節(jié)的圖展示的,看起來需要填寫很多配置信息。幸運地是,Spring的最新版本提供了很多容易配置的選項,降低了Spring MVC的學(xué)習(xí)門檻。這里我們先簡單配置一個Spring MVC應(yīng)用,作為這一章將會不斷完善的例子。

CONFIGURING DISPATCHERSERVLET

DispatcherServlet是Spring MVC的核心,每當(dāng)應(yīng)用接受一個HTTP請求,由DispatcherServlet負(fù)責(zé)將請求分發(fā)給應(yīng)用的其他組件。

在舊版本中,DispatcherServlet之類的servlet一般在web.xml文件中配置,該文件一般會打包進(jìn)最后的war包種;但是Spring 3引入了注解,我們在這一章將展示如何基于注解配置Spring MVC。

既然不適用web.xml文件,你需要在servlet容器中使用Java配置DispatcherServlet,具體的代碼列舉如下:

package org.test.spittr.config;

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

public class SpittrWebAppInitializer
        extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class[] getRootConfigClasses() { //根容器
        return new Class[] { RootConfig.class };
    }

    @Override
    protected Class[] getServletConfigClasses() { //Spring mvc容器
        return new Class[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() { //DispatcherServlet映射,從"/"開始
        return new String[] { "/" };
    }
}

spitter這個單詞是我們應(yīng)用的名稱,SpittrWebAppInitializer類是整個應(yīng)用的總配置類。

AbstractAnnotationConfigDispatcherServletInitializer這個類負(fù)責(zé)配置DispatcherServlet、初始化Spring MVC容器和Spring容器。getRootConfigClasses()方法用于獲取Spring應(yīng)用容器的配置文件,這里我們給定預(yù)先定義的RootConfig.classgetServletConfigClasses負(fù)責(zé)獲取Spring MVC應(yīng)用容器,這里傳入預(yù)先定義好的WebConfig.classgetServletMappings()方法負(fù)責(zé)指定需要由DispatcherServlet映射的路徑,這里給定的是"/",意思是由DispatcherServlet處理所有向該應(yīng)用發(fā)起的請求。

A TALE OF TWO APPLICATION CONTEXT

當(dāng)DispatcherServlet啟動時,會創(chuàng)建一個Spring MVC應(yīng)用容器并開始加載配置文件中定義好的beans。通過getServletConfigClasses()方法,可以獲取由DispatcherServlet加載的定義在WebConfig.class中的beans。

在Spring Web應(yīng)用中,還有另一個Spring應(yīng)用容器,這個容器由ContextLoaderListener創(chuàng)建。

我們希望DispatcherServlet僅加載web組件之類的beans,例如controllers(控制器)、view resolvers(視圖解析器)和處理器映射(handler mappings);而希望ContextLoaderListener加載應(yīng)用中的其他類型的beans——例如業(yè)務(wù)邏輯組件、數(shù)據(jù)庫操作組件等等。

實際上,AbstractAnnotationConfigDispatcherServletInitializer創(chuàng)建了DispatcherServletContextLoaderListenergetServletConfigClasses()返回的配置類定義了Spring MVC應(yīng)用容器中的beans;getRootConfigClasses()返回的配置類定義了Spring應(yīng)用根容器中的beans。【書中沒有說的】:Spring MVC容器是根容器的子容器,子容器可以看到根容器中定義的beans,反之不行。

注意:通過AbstractAnnotationConfigDispatcherServletInitializer配置DispatcherServlet僅僅是傳統(tǒng)的web.xml文件方式的另一個可選項。盡管你也可以使用AbstractAnnotationConfigDispatcherServletInitializer的一個子類引入web.xml文件來配置,但這沒有必要。

這種方式配置DispatcherServlet需要支持Servlert 3.0的容器,例如Apache Tomcat 7或者更高版本的。

ENABLING SPRING MVC

正如可以通過多種方式配置DispatcherServlet一樣,也可以通過多種方式啟動Spring MVC特性。原來我們一般在xml文件中使用元素啟動注解驅(qū)動的Spring MVC特性。

這里我們?nèi)匀皇褂肑avaConfig配置,最簡單的Spring MVC配置類代碼如下:

package org.test.spittr.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
public class WebConfig {
}

@Configuration表示這是Java配置類;@EnableWebMvc注解用于啟動Spring MVC特性。

僅僅這些代碼就可以啟動Spring MVC了,雖然它換缺了一些必要的組件:

沒有配置視圖解析器。這種情況下,Spring會使用BeanNameViewResolver,這個視圖解析器通過查找ID與邏輯視圖名稱匹配且實現(xiàn)了View接口的beans。

沒有啟動Component-scanning。

DispatcherServlet作為默認(rèn)的servlet,將負(fù)責(zé)處理所有的請求,包括對靜態(tài)資源的請求,例如圖片和CSS文件等。

因此,我們還需要在配置文件中增加一些配置,使得這個應(yīng)用可以完成最簡單的功能,代碼如下:

package org.test.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
@ComponentScan("org.test.spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter{
    @Bean
    public ViewResolver viewResolver() { //配置JSP視圖解析器
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        //可以在JSP頁面中通過${}訪問beans
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable(); //配置靜態(tài)文件處理
    }
}

首先,通過@ComponentScan("org.test.spittr.web")注解指定bean的自動發(fā)現(xiàn)機制作用的范圍,待會會看到,被@Controller等注解修飾的web的bean將被發(fā)現(xiàn)并加載到spring mvc應(yīng)用容器。這樣就不需要在配置類中顯式定義任何控制器bean了。

然后,你通過@Bean注解添加一個ViewResolverbean,具體來說是InternalResourceViewResolver。后面我們會專門探討視圖解析器,這里的三個函數(shù)的含義依次是:setPrefix()方法用于設(shè)置視圖路徑的前綴;setSuffix()用于設(shè)置視圖路徑的后綴,即如果給定一個邏輯視圖名稱——"home",則會被解析成"/WEB-INF/views/home.jsp"; setExposeContextBeansAsAttributes(true)使得可以在JSP頁面中通過${ }訪問容器中的bean。

最后,WebConfig繼承了WebMvcConfigurerAdapter類,然后覆蓋了其提供的configureDefaultServletHandling()方法,通過調(diào)用configer.enable(),DispatcherServlet將會把針對靜態(tài)資源的請求轉(zhuǎn)交給servlert容器的default servlet處理。

RootConfig的配置就非常簡單了,唯一需要注意的是,它在設(shè)置掃描機制的時候,將之前WebConfig設(shè)置過的那個包排除了;也就是說,這兩個掃描機制作用的范圍正交。RootConfig的代碼如下:

package org.test.spittr.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 = {"org.test.spittr"},
        excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class)})
public class RootConfig {
}
5.1.3 Spittr應(yīng)用簡介

這一章要用的例子應(yīng)用,從Twitter獲取了一些靈感,因此最開始叫Spitter;然后又借鑒了最近比較流行的網(wǎng)站Flickr,因此我們也把e去掉,最終形成Spittr這個名字。這也有利于區(qū)分領(lǐng)域名稱(類似于twitter,這里用spring實現(xiàn),因此叫spitter)和應(yīng)用名稱。

Spittr應(yīng)用有兩個關(guān)鍵的領(lǐng)域概念:spitters(應(yīng)用的用戶)和spittles(用戶發(fā)布的狀態(tài)更新)。在這一章中,將專注于構(gòu)建該應(yīng)用的web層,創(chuàng)建控制器和顯示spittles,以及處理用戶注冊的表單。

基礎(chǔ)已經(jīng)打好了,你已經(jīng)配置好了DispatcherServlet,啟動了Spring MVC特性等,接下來看看如何編寫Spring MVC控制器。

5.2 編寫簡單的控制器

在Spring MVC應(yīng)用中,控制器類就是含有被@RequestMapping注解修飾的方法的類,其中該注解用于指出這些方法要處理的請求類型。

我們從最簡單的請求"/"開始,用于渲染該應(yīng)用的主頁,HomeController的代碼列舉如下:

package org.test.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 {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home() {
        return "home";
    }
}

@Controller是一個模式化的注解,它的作用跟@Component一樣;Component-scanning機制會自動發(fā)現(xiàn)該控制器,并在Spring容器中創(chuàng)建對應(yīng)的bean。

HomeController中的home()方法用于處理http://localhost:8080/這個URL對應(yīng)的"/"請求,且僅處理GET方法,方法的內(nèi)容是返回一個邏輯名稱為"home"的視圖。DispatcherServlet將會讓視圖解析器通過這個邏輯名稱解析出真正的視圖。

根據(jù)之前配置的InternalResourceViewResolver,最后解析成/WEB-INF/views/home.jsp,home.jsp的內(nèi)容列舉如下:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" session="false" %>


    Spittr

    

Welcome to Spittr

">Spittles ">Register

啟動應(yīng)用,然后訪問http://localhost:8080/,Spittr應(yīng)用的主頁如下圖所示:

5.2.1 控制器測試

控制器的測試通過Mockito框架進(jìn)行,首先在pom文件中引入需要的依賴庫:


    org.springframework
    spring-test



    org.mockito
    mockito-all
    ${mockito.version}

    junit
    junit
    ${junit.version}

然后,對應(yīng)的單元測試用例HomeControllerTest的代碼如下所示:

package org.test.spittr.web;

import org.junit.Before;import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;

public class HomeControllerTest {
    MockMvc mockMvc;

    @Before
    public void setupMock() {
        HomeController controller = new HomeController();
        mockMvc = standaloneSetup(controller).build();
    }

    @Test
    public void testHomePage() throws Exception {
        mockMvc.perform(get("/"))
                .andExpect(view().name("home"));
    }
}

首先stanaloneSetup()方法通過HomeController的實例模擬出一個web服務(wù),然后使用perform執(zhí)行對應(yīng)的GET請求,并檢查返回的視圖的名稱。MockMvcBuilders類有兩個靜態(tài)接口,代表兩種模擬web服務(wù)的方式:獨立測試和集成測試。上面這段代碼是獨立測試,我們也嘗試了集成測試的方式,最終代碼如下:

package org.test.spittr.web;

import org.junit.Before;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import org.test.spittr.config.RootConfig;
import org.test.spittr.config.WebConfig;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "src/main/webapp")
@ContextHierarchy({
        @ContextConfiguration(name = "parent", classes = RootConfig.class),
        @ContextConfiguration(name = "child", classes = WebConfig.class)})
public class HomeControllerTest {
    @Autowired
    private WebApplicationContext context;

    MockMvc mockMvc;

    @Before
    public void setupMock() {
        //HomeController controller = new HomeController();
        //mockMvc = standaloneSetup(controller).build();
        mockMvc = webAppContextSetup(context).build();
    }

    @Test
    public void testHomePage() throws Exception {
        mockMvc.perform(get("/"))
                .andExpect(view().name("home"));
    }
}
5.2.2 定義類級別的請求處理

上面一節(jié)對之前的HomeController進(jìn)行了簡單的測試,現(xiàn)在可以對它進(jìn)行進(jìn)一步的完善:將@RequestMapping從修飾函數(shù)改成修飾類,代碼如下:

package org.test.spittr.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/")
public class HomeController {
    @RequestMapping(method = RequestMethod.GET)
    public String home() {
        return "home";
    }
}

在新的HomeController中,"/"被移動到類級別的@RequestMapping中,而定義HTTP方法的@RequestMapping仍然用于修飾home()方法。RequestMapping注解可以接受字符串?dāng)?shù)組,即可以同時映射多個路徑,因此我們還可以按照下面這種方式修改:

@Controller
@RequestMapping({"/", "/homepage"})
public class HomeController {
    }
}
5.2.3 給視圖傳入模型數(shù)據(jù)

對于DispatcherServlet傳來的請求,控制器通常不會實現(xiàn)具體的業(yè)務(wù)邏輯,而是調(diào)用業(yè)務(wù)層的接口,并且將業(yè)務(wù)層服務(wù)返回的數(shù)據(jù)放在模型對象中返回給DispatcherServlet。

在Spittr應(yīng)用中,需要一個頁面顯示最近的spittles列表。首先需要定義數(shù)據(jù)庫存取接口,這里不需要提供具體實現(xiàn),只需要用Mokito框架填充模擬測試數(shù)據(jù)即可。SpittleRepository接口的代碼列舉如下:

package org.test.spittr.data;

import java.util.List;

public interface SpittleRepository {
    List findSpittles(long max, int count);
}

SpittleRepository接口中的findSpittles()方法有兩個參數(shù):max表示要返回的Spittle對象的最大ID;count表示指定需要返回的Spittle對象數(shù)量。為了返回20個最近發(fā)表的Spittle對象,則使用List recent = spittleRepository.findSpittle(Long.MAX_VALUE, 20)這行代碼即可。該接口要處理的實體對象是Spittle,因此還需要定義對應(yīng)的實體類,代碼如下:

package org.test.spittr.data;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import java.util.Date;

public class Spittle {
    private final Long id;
    private final String message;
    private final Date time;
    private Double latitude;
    private Double longitude;

    public Spittle(String message, Date time) {
        this(message, time, null, null);
    }

    public Spittle(String message,Date time, Double latitude, Double longitude) {
        this.id = null;
        this.time = time;
        this.latitude = latitude;
        this.longitude = longitude;
        this.message = message;
    }

    public Long getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }

    public Date getTime() {
        return time;
    }

    public Double getLongitude() {
        return longitude;
    }

    public Double getLatitude() {
        return latitude;
    }

    @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj,
                new String[]{"message","latitude", "longitude"});
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this,
                new String[]{"message", "latitude", "longitude"});
    }
}

Spittle對象還是POJO,并沒什么復(fù)雜的。唯一需要注意的就是,利用Apache Commons Lang庫的接口,用于簡化equals和hashCode方法的實現(xiàn)。參考Apache Commons EqualsBuilder and HashCodeBuilder

首先為新的控制器接口寫一個測試用例,利用Mockito框架模擬repository對象,并模擬出request請求,代碼如下:

package org.test.spittr.web;

import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.servlet.view.InternalResourceView;
import org.test.spittr.data.Spittle;import org.test.spittr.data.SpittleRepository;import java.util.ArrayList;
import java.util.Date;import java.util.List;

import static org.hamcrest.Matchers.hasItems;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;

public class SpittleControllerTest {
    @Test
    public void shouldShowRecentSpittles() throws Exception {
        //step1 準(zhǔn)備測試數(shù)據(jù)
        List expectedSpittles = createSpittleList(20);
        SpittleRepository mockRepository = mock(SpittleRepository.class);
        when(mockRepository.findSpittles(Long.MAX_VALUE, 20))
                .thenReturn(expectedSpittles);
        SpittleController controller = new SpittleController(mockRepository);
        MockMvc mockMvc = standaloneSetup(controller)
                .setSingleView(new InternalResourceView("/WEB-INF/views/spittles.jsp"))
                .build();

        //step2 and step3
        mockMvc.perform(get("/spittles"))
                .andExpect(view().name("spittles"))
                .andExpect(model().attributeExists("spittleList"))
                .andExpect(model().attribute("spittleList",
                        hasItems(expectedSpittles.toArray())));
    }

    private List createSpittleList(int count) {
        List spittles = new ArrayList();
        for (int i = 0; i < count; i++) {
            spittles.add(new Spittle("Spittle " + i, new Date()));
        }
        return spittles;
    }
}

單元測試的基本組成是:準(zhǔn)備測試數(shù)據(jù)、調(diào)用待測試接口、校驗接口的執(zhí)行結(jié)果。對于shouldShowRecentSpittles()這個用例我們也可以這么分割:首先規(guī)定在調(diào)用SpittleRepository接口的findSpittles()方法時將返回20個Spittle對象。

這里選擇獨立測試,跟HomeControllerTest不同的地方在于,這里構(gòu)建MockMvc對象時還調(diào)用了setSingleView()函數(shù),這是為了防止mock框架從控制器解析view名字。在很多情況下并沒有這個必要,但是對于SpittleController控制器來說,視圖名稱和路徑名稱相同,如果使用默認(rèn)的視圖解析器,則MockMvc會混淆這兩者而失敗,報出如下圖所示的錯誤:

在這里其實可以隨意設(shè)置InternalResourceView的路徑,但是為了和WebConfig中的配置相同。

通過get方法構(gòu)造GET請求,訪問"/spittles",并確保返回的視圖名稱是"spittles",返回的model數(shù)據(jù)中包含spittleList屬性,且對應(yīng)的值為我們之前創(chuàng)建的測試數(shù)據(jù)。

最后,為了使用hasItems,需要在pom文件中引入hamcrest庫,代碼如下


    org.hamcrest
    hamcrest-library
    1.3

現(xiàn)在跑單元測試的話,必然會失敗,因為我們還沒有提供SpittleController的對應(yīng)方法,代碼如下:

package org.test.spittr.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.test.spittr.data.SpittleRepository;

@Controller
@RequestMapping("/spittles")
public class SpittleController {
    private SpittleRepository spittleRepository;

    @Autowired
    SpittleController(SpittleRepository spittleRepository) {
        this.spittleRepository = spittleRepository;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String spittles(Model model) {
        model.addAttribute(
                spittleRepository.findSpittles(Long.MAX_VALUE, 20));
        return "spittles";
    }
}

Model對象本質(zhì)上是一個Map,spittles方法負(fù)責(zé)填充數(shù)據(jù),然后跟視圖的邏輯名稱一起回傳給DispatcherServlet。在調(diào)用addAttribute方法的時候,如果不指定key字段,則key字段會從value的類型推導(dǎo)出,在這個例子中默認(rèn)的key字段是spittleList。

如果你希望顯式指定key字段,則可以按照如下方式指定:

@RequestMapping(method = RequestMethod.GET)
public String spittles(Model model) {
    model.addAttribute("spittleList",
            spittleRepository.findSpittles(Long.MAX_VALUE, 20));
    return "spittles";
}

另外,如果你希望盡量少使用Spring規(guī)定的數(shù)據(jù)類型,則可以使用Map代替Model。

還有另一種spittles方法的實現(xiàn),如下所示:

@RequestMapping(method = RequestMethod.GET)
public List spittles() {
    return spittleRepository.findSpittles(Long.MAX_VALUE, 20));
}

這個版本和之前的不同,并沒有返回一個邏輯名稱以及顯式設(shè)置Model對象,這個方法直接返回Spittle列表。在這種情況下,Spring會將返回值直接放入Model對象,并從值類型推導(dǎo)出對應(yīng)的關(guān)鍵字key;然后從路徑推導(dǎo)出視圖邏輯名稱,在這里是spittles。

無論你選擇那種實現(xiàn),最終都需要一個頁面——spittles.jsp。JSP頁面使用JSTL庫的標(biāo)簽獲取model對象中的數(shù)據(jù),如下所示:


  
  • " >
    (, )
  • 盡管SpittleController還是很簡單,但是它比HomeController復(fù)雜了一點,不過,這兩個控制器都沒有實現(xiàn)的一個功能是處理表單輸入。接下來將擴展SpittleController,使其能夠處理表單上輸入。

    5.3 訪問request輸入

    Spring MVC提供了三種方式,可以讓客戶端給控制器的handler傳入?yún)?shù),包括:

    查詢參數(shù)(Query parameters)

    表單參數(shù)(Form parameters)

    路徑參數(shù)(Path parameters)

    5.3.1 獲取查詢參數(shù)

    Spittr應(yīng)用需要一個頁面顯示spittles列表,目前的SpittleController僅能返回最近的所有spittles,還不能提供根據(jù)spittles的生成歷史進(jìn)行查詢。如果你想提供這個功能,首先要提供用戶一個傳入?yún)?shù)的方法,從而可以決定返回歷史spittles的那一個子集。

    spittles列表是按照ID的生成先后倒序排序的:下一頁spittles的第一條spittle的ID應(yīng)正好在當(dāng)前頁的最后一條spittle的ID后面。因此,為了顯示下一頁spttles,應(yīng)該能夠傳入僅僅小于當(dāng)前頁最后一條spittleID的參數(shù);并且提供設(shè)置每頁返回幾個spittles的參數(shù)count。

    before參數(shù),代表某個Spittle的ID,包含該ID的spittles集合中所有的spittles都在當(dāng)前頁的spittles之前發(fā)布;

    count參數(shù),代表希望返回結(jié)果中包含多少條spittles。

    我們將改造5.2.3小節(jié)實現(xiàn)的spittles()方法,來處理上述兩個參數(shù)。首先編寫測試用例:

    @Test
    public void shouldShowRecentSpittles_NORMAL() throws Exception {
        List expectedSpittles = createSpittleList(50);
        SpittleRepository mockRepository = mock(SpittleRepository.class);
        when(mockRepository.findSpittles(238900, 50))
                .thenReturn(expectedSpittles);
        SpittleController controller = new SpittleController(mockRepository);
        MockMvc mockMvc = standaloneSetup(controller)
                .setSingleView(new InternalResourceView("/WEB-INF/views/spittles.jsp"))
                .build();
    
        mockMvc.perform(get("/spittles?max=238900&count=50"))
                .andExpect(view().name("spittles"))
                .andExpect(model().attributeExists("spittleList"))
                .andExpect(model().attribute("spittleList",
                        hasItems(expectedSpittles.toArray())));
    }

    這個測試用例的關(guān)鍵在于:為請求"/spittles"傳入兩個參數(shù),max和count。這個測試用例可以測試提供參數(shù)的情況,兩個測試用例都應(yīng)該提供,這樣可以覆蓋到所有測試條件。改造后的spittles方法列舉如下:

    @RequestMapping(method = RequestMethod.GET)
    public List spittles(
            @RequestParam("max") long max,
            @RequestParam("count") int count) {
        return spittleRepository.findSpittles(max, count);
    }

    如果SpittleController的handle方法需要默認(rèn)處理同時處理兩種情況:提供了max和count參數(shù),或者沒有提供的情況,代碼如下:

    @RequestMapping(method = RequestMethod.GET)
    public List spittles(
            @RequestParam(value = "max", defaultValue = MAX_LONG_AS_STRING) long max,
            @RequestParam(value = "count", defaultValue = "20") int count) {
        return spittleRepository.findSpittles(max, count);
    }

    其中MAX_LONG_AS_STRING是Long的最大值的字符串形式,定義為:private static final String MAX_LONG_AS_STRING = Long.MAX_VALUE + "";,默認(rèn)值都給定字符串形式,不過一旦需要綁定到參數(shù)上時,就會自動轉(zhuǎn)為合適的格式。

    5.3.2 通過路徑參數(shù)獲取輸入

    假設(shè)Spittr應(yīng)用應(yīng)該支持通過指定ID顯示對應(yīng)的Spittle,可以使用@RequestParam給控制器的處理方法傳入?yún)?shù)ID,如下所示:

    @RequestMapping(value = "/show", method = RequestMethod.GET)
    public String showSpittle(
            @RequestParam("spittle_id") long spittleId,
            Model model) {
        model.addAttribute(spittleRepository.findOne(spittleId));
        return "spittle";
    }

    這個方法將處理類似/spittles/show?spittle_id=12345的請求,盡管這可以工作,但是從基于資源管理的角度并不理想。理想情況下,某個指定的資源應(yīng)該可以通過路徑指定,而不是通過查詢參數(shù)指定,因此GET請求最好是這種形式:/spittles/12345。

    首先編寫一個測試用例,代碼如下:

    @Test
    public void testSpittle() throws Exception {
        Spittle expectedSpittle = new Spittle("Hello", new Date());
        SpittleRepository mockRepository = mock(SpittleRepository.class);
        when(mockRepository.findOne(12345)).thenReturn(expectedSpittle);
    
        SpittleController controller = new SpittleController(mockRepository);
        MockMvc mockMvc = standaloneSetup(controller).build();
    
        mockMvc.perform(get("/spittles/12345"))
                .andExpect(view().name("spittle"))
                .andExpect(model().attributeExists("spittle"))
                .andExpect(model().attribute("spittle", expectedSpittle));
    }

    該測試用例首先模擬一個repository、控制器和MockMvc對象,跟之前的幾個測試用例相同。不同之處在于這里構(gòu)造的GET請求——/spittles/12345,并希望返回的視圖邏輯名稱是spittle,返回的模型對象中包含關(guān)鍵字spittle,且與該key對應(yīng)的值為我們創(chuàng)建的測試數(shù)據(jù)。

    為了實現(xiàn)路徑參數(shù),Spring MVC在@RequestMapping注解中提供占位符機制,并在參數(shù)列表中通過@PathVariable("spittleId")獲取路徑參數(shù),完整的處理方法列舉如下:

    @RequestMapping(value = "/{spittleId}", method = RequestMethod.GET)
    public String showSpittle(
            @PathVariable("spittleId") long spittleId,
            Model model) {
        model.addAttribute(spittleRepository.findOne(spittleId));
        return "spittle";
    }

    @PathVariable注解的參數(shù)應(yīng)該和@RequestMapping注解中的占位符名稱完全相同;如果函數(shù)參數(shù)也和占位符名稱相同,則可以省略@PathVariable注解的參數(shù),代碼如下所示:

    @RequestMapping(value = "/{spittleId}", method = RequestMethod.GET)
    public String showSpittle(
            @PathVariable long spittleId,
            Model model) {
        model.addAttribute(spittleRepository.findOne(spittleId));
        return "spittle";
    }

    這么寫確實可以使得代碼更加簡單,不過需要注意:如果要修改函數(shù)參數(shù)名稱,則要同時修改路徑參數(shù)的占位符名稱。

    5.4 處理表單

    Web應(yīng)用通常不僅僅是給用戶顯示數(shù)據(jù),也接受用戶的表單輸入,最典型的例子就是賬號注冊頁面——需要用戶填入相關(guān)信息,應(yīng)用程序按照這些信息為用戶創(chuàng)建一個賬戶。

    關(guān)于表單的處理有兩個方面需要考慮:顯示表單內(nèi)容和處理用戶提交的表單數(shù)據(jù)。在Spittr應(yīng)用中,需要提供一個表單供新用戶注冊使用;需要一個SpitterController控制器顯示注冊信息。

    package org.test.spittr.web;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    @Controller
    @RequestMapping("/spitter")
    public class SpitterController {
        @RequestMapping(value = "/register", method = RequestMethod.GET)
        public String showRegistrationForm() {
            return "registerForm";
        }
    }

    修飾showRegistrationForm()方法的@RequestMapping(value = "/register", method = RequestMethod.GET)注解,和類級別的注解一起,表明該方法需要處理類似"/spitter/register"的GET請求。這個方法非常簡單,沒有輸入,且僅僅返回一個邏輯名稱——"registerForm"。

    即使showRegistrationForm()方法非常簡單,也應(yīng)該寫個單元測試,代碼如下所示:

    @Test
    public void shouldShowRegistrationForm() throws Exception {
        SpitterController controller = new SpitterController();
        MockMvc mockMvc = standaloneSetup(controller).build();
    
        mockMvc.perform(get("/spitter/register"))
                .andExpect(view().name("registerForm"));
    }

    為了接受用戶的輸入,需要提供一個JSP頁面——registerForm.jsp,該頁面的代碼如下所示:

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    
        Spittr
    
    
      

    Register

    First Name:
    Last Name:
    Username:
    Password:

    上述JSP頁面在瀏覽器中渲染圖如下所示:

    因為

    標(biāo)簽并沒有設(shè)置action參數(shù),因此,當(dāng)用戶單擊submit按鈕的時候,將向后臺發(fā)出/spitter/register的POST請求。這就需要我們?yōu)?em>SpitterController編寫對應(yīng)的處理方法。

    5.4.1 編寫表單控制器

    在處理來自注冊表單的POST請求時,控制器需要接收表單數(shù)據(jù),然后構(gòu)造Spitter對象,并保存在數(shù)據(jù)庫中。為了避免重復(fù)提交,應(yīng)該重定向到另一個頁面——用戶信息頁。

    按照慣例,首先編寫測試用例,如下所示:

    @Test
    public void shouldProcessRegistration() throws Exception {
        SpitterRepository mockRepository = mock(SpitterRepository.class);
        Spitter unsaved = new Spitter("Jack", "Bauer", "jbauer", "24hours");
        Spitter saved = new Spitter(24L, "Jack", "Bauer", "jbauer", "24hours");
        when(mockRepository.save(unsaved)).thenReturn(saved);
    
        SpitterController controller = new SpitterController(mockRepository);
        MockMvc mockMvc = standaloneSetup(controller).build();
    
        mockMvc.perform(post("/spitter/register")
                .param("firstName", "Jack")
                .param("lastName", "Bauer")
                .param("username", "jbauer")
                .param("password", "24hours"))
                .andExpect(redirectedUrl("/spitter/jbauer"));
    
        //Verified save(unsaved) is called atleast once
        verify(mockRepository, atLeastOnce()).save(unsaved);
    }

    顯然,這個測試比之前驗證顯示注冊頁面的測試更加豐富。首先設(shè)置好SpitterRepository對象、控制器和MockMvc對象,然后構(gòu)建一個POST請求——/spitter/register,且該請求會攜帶四個參數(shù),用于模擬submit的提交動作。

    在處理POST請求的最后一般需要利用重定向到一個新的頁面,以防瀏覽器刷新引來的重復(fù)提交。在這個例子中我們重定向到/spitter/jbaure,即新添加的用戶的個人信息頁面。

    最后,該測試用例還需要驗證模擬對象mockRepository確實用于保存表單提交的數(shù)據(jù)了,即save()方法之上調(diào)用了一次。

    SpitterController中添加處理表單的方法,代碼如下:

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String processRegistration(Spitter spitter) {
        spitterRepository.save(spitter);
        return "redirect:/spitter/" + spitter.getUsername();
    }

    shouldShowRegistrationForm()這個方法還在,新加的處理方法processRegistration()以Spitter對象為參數(shù),Spring利用POST請求所攜帶的參數(shù)初始化Spitter對象。

    現(xiàn)在執(zhí)行之前的測試用例,發(fā)現(xiàn)一個錯誤如下所示:

    我分析了這個錯誤,原因是測試用例的寫法有問題:verify(mockRepository, atLeastOnce()).save(unsaved);這行代碼表示,希望調(diào)用至少保存unsave這個對象一次,而實際上在控制器中執(zhí)行save的時候,參數(shù)對象的ID是另一個——根據(jù)參數(shù)新創(chuàng)建的?;仡櫸覀儗戇@行代碼的初衷:確保save方法至少被調(diào)用一次,而保存哪個對象則無所謂,因此,這行語句改成verify(mockRepository, atLeastOnce());后,再次執(zhí)行測試用例就可以通過了。

    注意:無論使用哪個框架,請盡量不要使用verify,也就是傳說中的Mock模式,那是把代碼拉入泥潭的開始。參見你應(yīng)該更新的Java知識之常用程序庫

    當(dāng)InternalResourceViewResolver看到這個函數(shù)返回的重定向URL是以view標(biāo)志開頭,就知道需要把該URL當(dāng)做重定向URL處理,而不是按照視圖邏輯名稱處理。在這個例子中,頁面將被重定向至用戶的個人信息頁面。因此,我們還需要給SpitterController添加一個處理方法,用于顯示個人信息,showSpitterProfile()方法代碼如下:

    @RequestMapping(value = "/{username}", method = RequestMethod.GET)
    public String showSpitterProfile(
        @PathVariable String username, Model model) {
        Spitter spitter = spitterRepository.findByUsername(username);
        model.addAttribute(spitter);
        return "profile";
    }

    showSpitterProfile()方法根據(jù)username從SpitterRepository中查詢Spitter對象,然后將該對象存放在model對象中,并返回視圖的邏輯名稱profile。

    profile.jsp的頁面代碼如下所示:

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    
        Your Profile
    
    
        

    Your Profile




    上述代碼的渲染圖如下圖所示:

    5.4.2 表單驗證

    如果用戶忘記輸入username或者password就點了提交,則可能創(chuàng)建一個這兩個字段為空字符串的Spitter對象。往小了說,這是丑陋的開發(fā)習(xí)慣,往大了說這是會應(yīng)發(fā)安全問題,因為用戶可以通過提交一個空的表單來登錄系統(tǒng)。

    綜上所述,需要對用戶的輸入進(jìn)行有效性驗證,一種驗證方法是為processRegistration()方法添加校驗輸入?yún)?shù)的代碼,因為這個函數(shù)本身非常簡單,參數(shù)也不多,因此在開頭加入一些If判斷語句還可以接受。

    除了使用這種方法,換可以利用Spring提供的Java驗證支持(a.k.a JSR-303)。從Spring 3.0開始,Spring支持在Spring MVC項目中使用Java Validation API。

    首先需要在pom文件中添加依賴:

    
        javax.validation
        validation-api
    

    然后就可以使用各類具體的注解,進(jìn)行參數(shù)驗證了,以Spitter類的實現(xiàn)為例:

    package org.test.spittr.data;
    
    import javax.validation.constraints.NotNull;
    import javax.validation.constraints.Size;
    
    public class Spitter {
        private Long id;
    
        @NotNull
        @Size(min = 5, max = 16)
        private String username;
    
        @NotNull
        @Size(min = 5, max = 25)
        private String password;
    
        @NotNull
        @Size(min = 2, max = 30)
        private String firstName;
    
        @NotNull
        @Size(min = 2, max = 30)
        private String lastName;
    
        ....
    }

    @NotNull注解表示被它修飾的字段不能為空;@Size字段用于限制指定字段的長度范圍。在Spittr應(yīng)用的含義是:用戶必須填寫表單中的所有字段,并且滿足一定的長度限制,才可以注冊成功。

    除了上述兩個注解,Java Validation API提供了很多不同功能的注解,都定義在javax.validation.constraints包種,下表列舉出這些注解:

    Spittr類的定義中規(guī)定驗證條件后,需要在控制器的處理方法中應(yīng)用驗證條件。

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String processRegistration(
            @Valid Spitter spitter,
            Errors errors) {
        if (errors.hasErrors()) {
            return "registerForm";
        }
        spitterRepository.save(spitter);
        return "redirect:/spitter/" + spitter.getUsername();
    }

    如果用戶輸入的參數(shù)有誤,則返回registerForm這個邏輯名稱,瀏覽器將返回到表單填寫頁面,以便用戶重新輸入。當(dāng)然,為了更好的用戶體驗,還需要提示用戶具體哪個字段寫錯了,應(yīng)該怎么改;最好是在用戶填寫之前就做出提示,這就需要前端工程師做很多工作了。

    5.5 總結(jié)

    這一章比較適合Spring MVC的入門學(xué)習(xí)資料。涵蓋了Spring MVC處理web請求的處理過程、如何寫簡單的控制器和控制器方法來處理Http請求、如何使用mockito框架測試控制器方法。

    基于Spring MVC的應(yīng)用有三種方式讀取數(shù)據(jù):查詢參數(shù)、路徑參數(shù)和表單輸入。本章用兩節(jié)介紹了這些內(nèi)容,并給出了類似錯誤處理和參數(shù)驗證等關(guān)鍵知識點。

    文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

    轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/65383.html

    相關(guān)文章

    • Spring Security

      摘要:框架具有輕便,開源的優(yōu)點,所以本譯見構(gòu)建用戶管理微服務(wù)五使用令牌和來實現(xiàn)身份驗證往期譯見系列文章在賬號分享中持續(xù)連載,敬請查看在往期譯見系列的文章中,我們已經(jīng)建立了業(yè)務(wù)邏輯數(shù)據(jù)訪問層和前端控制器但是忽略了對身份進(jìn)行驗證。 重拾后端之Spring Boot(四):使用JWT和Spring Security保護(hù)REST API 重拾后端之Spring Boot(一):REST API的搭建...

      keelii 評論0 收藏0
    • Spring Boot 2 快速教程:WebFlux 快速入門(二)

      摘要:響應(yīng)式編程是基于異步和事件驅(qū)動的非阻塞程序,只是垂直通過在內(nèi)啟動少量線程擴展,而不是水平通過集群擴展。三特性常用的生產(chǎn)的特性如下響應(yīng)式編程模型適用性內(nèi)嵌容器組件還有對日志消息測試及擴展等支持。 摘要: 原創(chuàng)出處 https://www.bysocket.com 「公眾號:泥瓦匠BYSocket 」歡迎關(guān)注和轉(zhuǎn)載,保留摘要,謝謝! 02:WebFlux 快速入門實踐 文章工程: JDK...

      gaara 評論0 收藏0
    • Spring Web

      摘要:認(rèn)證鑒權(quán)與權(quán)限控制在微服務(wù)架構(gòu)中的設(shè)計與實現(xiàn)一引言本文系認(rèn)證鑒權(quán)與權(quán)限控制在微服務(wù)架構(gòu)中的設(shè)計與實現(xiàn)系列的第一篇,本系列預(yù)計四篇文章講解微服務(wù)下的認(rèn)證鑒權(quán)與權(quán)限控制的實現(xiàn)。 java 開源項目收集 平時收藏的 java 項目和工具 某小公司RESTful、共用接口、前后端分離、接口約定的實踐 隨著互聯(lián)網(wǎng)高速發(fā)展,公司對項目開發(fā)周期不斷縮短,我們面對各種需求,使用原有對接方式,各端已經(jīng)很...

      Kosmos 評論0 收藏0
    • Spring實戰(zhàn)》讀書筆記——Spring簡介

      摘要:如何降低開發(fā)的復(fù)雜性最小侵入編程通過面向接口和依賴注入實現(xiàn)松耦合基于編程慣例和切面進(jìn)行聲明式編程通過模板減少樣板式代碼容器在應(yīng)用中,不再由對象自行創(chuàng)建或管理它們之間的依賴關(guān)系容器負(fù)責(zé)創(chuàng)建對象裝配對象配置它們并管理它們的整個生命周期。 歡迎大家關(guān)注我的微信公眾號,一起探討Java相關(guān)技術(shù) showImg(https://segmentfault.com/img/bVboaBO?w=129...

      CKJOKER 評論0 收藏0

    發(fā)表評論

    0條評論

    最新活動
    閱讀需要支付1元查看
    <