spring mvc
一 處理器映射,配置文件
DispatcherServlet是spring mvc的核心,作為spring mvc的前端控制器, 必須在web.xml中聲明如下:
<servlet>
<servlet-name>spitter</servlet-name> //定義了servlet名字,將從于servlet相同名的xml中載入應用上下文,DispatcherServlet試圖從spitter.xml中載入上下文
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spitter</servlet-name>
<url-pattern>/</url-pattern> //DispatcherServlet需要處理所有請求
</servlet-mapping>
ContextLoaderListener 可以加在配置文件到servlet xml中,在web.xml中配置:
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spitter-security.xml
classpath:service-context.xml
classpath:persistence-context.xml
classpath:dataSource-context.xml
</param-value>
</context-param>
對于靜態文件,可以使用
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<mvc:resources mapping="/resources/**" //對于所有以resources開頭的path,servlet會serve到應用程序根目錄的resources下,一般放置圖片,javascrpt等
location="/resources/" />
</beans>
spring有5種方法分配請求到controller
1 BeanNameUrlHandlerMapping 掃描bean,將以”/”開頭的bean的名稱或別名(alias)注冊為可以處理的url
2 ControllerBeanNameHandlerMapping 和第一個類似,但是beanname不要求和url規定一樣
3 ControllerClassNameHandlerMapping controller class name和url關系
4 DefaultAnnotationHandlerMapping 注解<mvc:annotation-driven/>
這個標簽注冊了Spring MVC分發請求到控制器所必須的DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter實例
5 SimpleUrlHandlerMapping 在spring上下文種定義controller和url關系
二 控制器
package com.habuma.spitter.mvc;
import javax.inject.Inject;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.habuma.spitter.service.SpitterService;
@Controller //定義一個controller,在servlet中配置<context:component-scan base-package="com.habuma.spitter.mvc" />,controller自動配置成bean
public class HomeController {
public static final int DEFAULT_SPITTLES_PER_PAGE = 25;
private SpitterService spitterService;
@Inject
public HomeController(SpitterService spitterService) { //注入service
this.spitterService = spitterService;
}
@RequestMapping({"/","/home"}) //處理請求
public String showHomePage(Map<String, Object> model) {//model是controller和view傳送數據
????model.put("spittles", spitterService.getRecentSpittles(
DEFAULT_SPITTLES_PER_PAGE));
?? return "home"; //返回view
}
}
處理input, url:http://localhost:8080/spitter/spitters/spittles?spitter=habuma
@Controller
@RequestMapping("/spitter")
public class SpitterController {
private final SpitterService spitterService;
??@Inject
public SpitterController(SpitterService spitterService) {
this.spitterService = spitterService;
}
@RequestMapping(value="/spittles", method=GET)//Handle GET requests for /spitter/spittles
public String listSpittlesForSpitter(
?? @RequestParam("spitter") String username, Model model) {//第二個參數和前面例子的map類似,map的put方法和model的addattribute方法類似
Spitter spitter = spitterService.getSpitter(username);
model.addAttribute(spitter);
model.addAttribute(spitterService.getSpittlesForSpitter(username));
return "spittles/list";
} }
When adding a Spitter object to the model, addAttribute() gives it the name spitter, a name it arrives at by applying JavaBeans property naming rules to the object’s class name. When adding a List of Spittles, it tacks List to the end the mem- ber type of the List, naming the attribute spittleList.
jsp中這樣調用
<h2>Spittles for ${spitter.username}</h2>
<table cellspacing="15">
<c:forEach items="${spittleList}" var="spittle">
如何測試一個controller
package com.habuma.spitter.mvc;
import static com.habuma.spitter.mvc.HomeController.*;
import static java.util.Arrays.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.HashMap;
import java.util.List;
import org.junit.Test;
import com.habuma.spitter.domain.Spittle;
import com.habuma.spitter.service.SpitterService;
public class HomeControllerTest {
@Test
public void shouldDisplayRecentSpittles() {
List<Spittle> expectedSpittles =
asList(new Spittle(), new Spittle(), new Spittle());
SpitterService spitterService = mock(SpitterService.class);
Mock SpitterService
?when(spitterService.getRecentSpittles(DEFAULT_SPITTLES_PER_PAGE)).
thenReturn(expectedSpittles);
?HomeController controller =
new HomeController(spitterService); //Create controller
HashMap<String, Object> model = new HashMap<String, Object>();
?String viewName = controller.showHomePage(model); //Call handler method
assertEquals("home", viewName);
assertSame(expectedSpittles, model.get("spittles"));
???verify(spitterService).getRecentSpittles(DEFAULT_SPITTLES_PER_PAGE); }
}
三 視圖解析器
具體view可由jsp或者velocity寫,視圖解析器將邏輯viewname轉換為實際的viewpath
view resolver:
BeanNameViewResolver view注冊成bean,id和logic view name一樣
ContentNegotiatingViewResolver
FreeMarkerViewResolver
InternalResourceViewResolver
JasperReportsViewResolver
ResourceBundleViewResolver TilesViewResolver
UrlBasedViewResolver
VelocityLayoutViewResolver
VelocityViewResolver
XmlViewResolver
XsltViewResolver
InternalResourceViewResolver
<bean class= "org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean>
TilesViewResolver
用來組合成一個最終表示用頁面用的,這樣的話,便于對頁面的各個機能的變更及維護。
//in spitter-servlet.xml:
<bean class="org.springframework.web.servlet.view.tiles2.TilesViewResolver"/>//定義TilesViewResolver根據視圖邏輯名找到定義對應的view
<bean class=
"org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">//tiles定義的文件
<list>
<value>/WEB-INF/viewsviews.xml</value>
</list>
</property>
</bean>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"
"http://tiles.apache.org/dtds/tiles-config_2_1.dtd">
?<tiles-definitions>//tiles定義
<definition name="template"
template="/WEB-INF/views/main_template.jsp">
<put-attribute name="top"
value="/WEB-INF/views/tiles/spittleForm.jsp" />
<put-attribute name="side"
value="/WEB-INF/views/tiles/signinsignup.jsp" />
//Define common layout
?</definition>
<definition name="home" extends="template">
//Define home tile
? <put-attribute name="content" value="/WEB-INF/views/home.jsp" />
</definition>
</tiles-definitions>
表單請求
new
@RequestMapping(method=RequestMethod.GET, params="new") //只能處理get請求
public String createSpitterProfile(Model model) {
model.addAttribute(new Spitter());
return "spitters/edit";
}
<definition name="spitters/edit" extends="template">//xml中
<put-attribute name="content"
value="/WEB-INF/views/spitters/edit.jsp" />
</definition>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<div>
<h2>Create a free Spitter account</h2>
<sf:form method="POST" modelAttribute="spitter">
<fieldset>
<table cellspacing="0">
<tr>
? <th><label for="user_full_name">Full name:</label></th>
<td><sf:input path="fullName" size="15" id="user_full_name"/></td>
</tr>
<tr>
<th><label for="user_screen_name">Username:</label></th>
<td><sf:input path="username" size="15" maxlength="15"
id="user_screen_name"/>
<small id="username_msg">No spaces, please.</small>
??</td> </tr>
<tr>
<th><label for="user_password">Password:</label></th>
<td><sf:password path="password" size="30"
showPassword="true"
id="user_password"/>
<small>6 characters or more (be tricky!)</small>
</td> </tr>
??<tr>
<th><label for="user_email">Email Address:</label></th>
<td><sf:input path="email" size="30"
id="user_email"/>
<small>In case you forget something</small>
</td>
</tr> <tr>
??
<th></th>
<td>
<sf:checkbox path="updateByEmail"
id="user_send_email_newsletter"/>
<label for="user_send_email_newsletter"
>Send me email updates!</label>
</td> </tr>
</table>
</fieldset>
</sf:form>
</div>
post
@RequestMapping(method=RequestMethod.POST)
public String addSpitterFromForm(@Valid Spitter spitter,BindingResult bindingResult) {//spitter必須先驗證
if(bindingResult.hasErrors()) {//判斷是否由error
return "spitters/edit";//Check for errors
}
spitterService.saveSpitter(spitter);//Save Spitter
//Redirect after POST
????? return "redirect:/spitters/" + spitter.getUsername();
}
@RequestMapping(value="/{username}", method=RequestMethod.GET)
public String showSpitterProfile(@PathVariable String username,//路徑名稱為參數
Model model) {
model.addAttribute(spitterService.getSpitter(username));
return "spitters/view";
}
驗證@valid
http://static.springsource.org/spring/docs/3.0.0.RC3/reference/html/ch05s07.html
@Pattern(regexp="^[a-zA-Z0-9]+$",
message="Username must be alphanumeric with no spaces")
?private String username;
@Size(min=6, max=20,
message="The password must be at least 6 characters long.")
private String password; //spitter類中
BindingResult’s getFieldError() 可顯示error,也可使用標簽
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<div>
<h2>Create a free Spitter account</h2>
<sf:form method="POST" modelAttribute="spitter"
enctype="multipart/form-data">
<fieldset>
<table cellspacing="0">
<tr>
<th><sf:label path="fullName">Full name:</sf:label></th>
<td><sf:input path="fullName" size="15" /><br/>
<sf:errors path="fullName" cssClass="error" />
</td>
</tr>
...
</table>
</fieldset>
</sf:form>
</div>
<sf:errors path="*" cssClass="error" />可顯示所有的error在同一個地方
資料:
http://blog.csdn.net/walkerjong/article/details/7946109
handler method 參數綁定常用的注解,我們根據他們處理的Request的不同內容部分分為四類:(主要講解常用類型)
A、處理requet uri 部分(這里指uri template中variable,不含queryString部分)的注解: @PathVariable;
B、處理request header部分的注解: @RequestHeader, @CookieValue;
C、處理request body部分的注解:@RequestParam, @RequestBody;
D、處理attribute類型是注解: @SessionAttributes, @ModelAttribute;
總結
以上是生活随笔為你收集整理的spring mvc的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PHP加密JS解密
- 下一篇: rhel加载raid卡驱动安装系统