springmvc簡單入門

作爲當前最火的mvc框架,優點:性能快,開發簡單,能很方便的支持restfull風格,可以直接返回json和xml格式。

一:簡單入門

先建一個maven工程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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.julyday</groupId>
	<artifactId>spring_mvc</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring_mvc Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<commons-lang.version>2.6</commons-lang.version>
		<slf4j.version>1.7.6</slf4j.version>
		<spring.version>4.1.3.RELEASE</spring.version>
		<jackson.version>2.5.4</jackson.version>
	</properties>


	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-framework-bom</artifactId>
				<version>${spring.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
		</dependency>

		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>${commons-lang.version}</version>
		</dependency>


		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
			<exclusions>
				<exclusion>
					<artifactId>slf4j-api</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.version}</version>
		</dependency>

		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.3</version>
		</dependency>
		
		<!-- xml格式輸出 -->
		<dependency>
		    <groupId>com.thoughtworks.xstream</groupId>
		    <artifactId>xstream</artifactId>
		    <version>1.4.7</version>
		</dependency>


	</dependencies>
</project>


<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">
  	<display-name>spring_mvc</display-name>
  	
  	<!-- spring上下文 -->
  	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- 編碼utf-8 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter
		</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- Spring MVC的核心  DispatcherServlet-->
  	<servlet>
  		<servlet-name>mvc-dispatcher</servlet-name>
  		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  		<init-param>
        	<param-name>contextConfigLocation</param-name>
        	<param-value>classpath:spring-mvc.xml</param-value>
  		</init-param>
  		<load-on-startup>1</load-on-startup>
  	</servlet>
  	<servlet-mapping>
  		<servlet-name>mvc-dispatcher</servlet-name>
  		<url-pattern>/</url-pattern>
  	</servlet-mapping>
</web-app>
這裏我們還是用到了spring,雖然我們這個項目可以不整合spring,但是在實際的開發中不運用spring幾乎是不可能的。這裏我們把controller層交給springmvc處理,service層交給spring來處理,我們接下來的service層也是模擬出來的,不是真正的經過數據庫的
spring配置文件:applicationContext.xml
<?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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
	
	
	<!-- 使用@ Resource 、@ PostConstruct、@ PreDestroy -->
	<!-- context:component-scan 會一併掃描,如果註解在base-package下使用可以去掉該註解 -->
	<context:annotation-config />
	
	<!-- 自動掃描 -->  
	<context:component-scan base-package="com.julyday">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	 <!--<context:component-scan base-package="com.julyday.service.impl"/>-->
</beans>
這裏我們只模擬了service層,所有註釋的自動掃描也是可以的,但是最後還是用沒註釋的,以後我們如果是和數據庫相連的話是不會錯的。
springmvc配置文件:spring-mvc.xml:
<?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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
	
	<!-- 啓用Spring基於annotation的DI, 使用戶可以在Spring MVC中使用Spring的強大功能。 激活 @Required 
		@Autowired,JSR 250's @PostConstruct, @PreDestroy and @Resource 等標註 -->
	<context:annotation-config />
	
	<!-- DispatcherServlet上下文, 只管理@Controller類型的bean, 忽略其他型的bean, 如@Service -->
	<context:component-scan base-package="com.julyday">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	<!-- <context:component-scan base-package="com.julyday.controller"/> -->
	
	<!-- 擴充了註解驅動,可以將請求參數綁定到控制器參數 -->
	<mvc:annotation-driven />
	
	<!-- 靜態資源處理,resources, css, js, imgs -->
	<!--<mvc:resources mapping="/resources/**" location="/resources/" />
	<mvc:resources mapping="/js/**" location="/js/" />
    <mvc:resources mapping="/images/**" location="/images/" />
    <mvc:resources mapping="/css/**" location="/css/" />	-->
    
    <!-- 容器默認的DefaultServletHandler處理 所有靜態內容與無RequestMapping處理的URL -->
  	<mvc:default-servlet-handler/>
  	
  	
  	<!-- 配置ViewResolver。 可以用多個ViewResolver。 使用order屬性排序。 InternalResourceViewResolver放在最後。 -->
	<bean
		class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
		<property name="order" value="1"/>
		<!-- 在沒有擴展名時即: "/user/1" 時的默認展現形式 -->
		<!-- 以json作爲默認返回,方便調用,省去後綴.json -->
		<!--  <property name="defaultContentType" value="application/json"></property>-->
		<!-- 擴展名至mimeType的映射,即 /user.json => application/json -->
		<property name="mediaTypes">
			<map>
				<!-- 告訴視圖解析器,返回的類型 /user/123.xml 將返回xml格式數據 
					/user/123.json 將返回json格式數據 
					/user/123.html 將返回html格式數據 
					favorParameter = false 
					/user/123?format=xml //將返回xml數據 
					/user/123?format=json //將返回json數據 -->
				<entry key="json" value="application/json" />
				<entry key="html" value="text/html" />
				<entry key="xml" value="application/xml" />
			</map>
		</property>
		<!-- 用於開啓 /userinfo/123?format=json 的支持 -->
		<property name="favorParameter" value="true" />
		<property name="defaultViews">
			<list>
				<!-- for application/json -->
				<bean
					class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
				</bean>
				<!-- for application/xml -->
				<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
					<property name="marshaller">
						<bean class="org.springframework.oxm.xstream.XStreamMarshaller" />
					</property>
				</bean>
			</list>
		</property>
		<property name="ignoreAcceptHeader" value="true" />
	</bean>
	
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
	
	<!--200*1024*1024即200M resolveLazily屬性啓用是爲了推遲文件解析,以便捕獲文件大小異常 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="209715200" />
		<property name="defaultEncoding" value="UTF-8" />
		<property name="resolveLazily" value="true" />
	</bean>
		
</beans>
在看springmvc配置之前,大家可以參考springmvc流程這篇文章,文章很詳細的講解了springmvc的流程,大家會知道HandlerMapping,HandlerAdapter,Controller,ViewResolver,View。HandlerMapping,HandlerAdapter 這個springmvc有默認的,我們不需要配置,Controller我們自己寫的邏輯,交給springmvc管理,ViewResolver這個就是需要我們配置的,在上文中,View視圖我們自己寫的,最後只要在controller裏面告訴springmvc,我們返回哪個視圖即可。
package com.julyday.entity;

public class User {
	private int id;
	private String name;
	private int age;

	//getter setter
}

</pre><pre name="code" class="java">@Service("userService")
public class UserServiceImpl implements UserService{

	@Override
	public User findByid(Integer id) {
		System.out.println("UserServiceImpl findByid"+id);
		User u = new User("julyday",18);
		u.setId(1);
		return u;
	}

	@Override
	public List<User> findAll() {
		User u1 = new User("julyday",18);
		u1.setId(1);
		User u2 = new User("zhangsan",28);
		u2.setId(2);
		List<User> list = new ArrayList<User>();
		list.add(u1);
		list.add(u2);
		return list;
	}
	
}
@Controller
@RequestMapping("/user")
public class UserController {
	private static Logger log = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	// 本方法將處理/user/hello
	@RequestMapping(value = "hello")
	public String hello() {
		return "hello";
	}
}
@Controller:告訴springmvc,管理這個controller。
@Autowired:注入service。
@RequestMapping:這個可以在類和方法上,訪問的時候是類上值+方法上值,他還可以攔截指定的請求方式,請求參數等。
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>hello.jsp</title>
</head>
<body>
	this is julyday hello.jsp
</body>
</html>
return "hello";springmvc會更具我們的配置信息InternalResourceViewResolver,返回我們需要的實體hello.jsp。

二:restfull風格的支持

@RequestMapping("/restful/{userId}")
	public String restful(@PathVariable("userId") Integer id,
			Map<String, Object> model) {
		log.debug("UserController restful {}", id);
		User user = userService.findByid(id);
		model.put("user", user);
		return "user/view";
	}
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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=utf-8">
<title>view.jsp</title>
</head>
<body>
	歡迎您:${user.name}
</body>
</html>
@PathVariable:獲取url請求上的動態參數,這個讓springmvc很簡單就支持restfull風格,註解的value必須要在@RequestMapping中用{}表示出來,並且名稱一致。
當然我們還可以這樣:
@RequestMapping("/restful2/{userId:[0-9]+}/{param}")
	public String restful2(@PathVariable("userId") Integer id,@PathVariable("param")String param,
			Map<String, Object> model){
		log.debug("UserController restful id: {} and param: {}",id,param);
		User user = userService.findByid(id);
		model.put("user", user);
		return "user/view";
	}
userId我們用了正則的方式,我們還可以是多個參數的restfull。

三:返回格式及文件下載

@RequestMapping("request")
	public String request(HttpServletRequest request){
		Integer id = Integer.valueOf(request.getParameter("userId"));
		log.debug("UserController request {}",id);
		User user = userService.findByid(id);
		request.setAttribute("user", user);
		return "user/view";
	}
我們可以在參數中加入HttpServletRequest這樣,直接訪問request,response,session等servlet參數。
@RequestMapping("all")
	public @ResponseBody String findAll(){
		List<User> list = userService.findAll();
		return JSON.toJSONString(list);
	}
	
	@RequestMapping("all2")
	public ResponseEntity<List<User>> findAll2(){
		List<User> list = userService.findAll();
		return new ResponseEntity<List<User>>(list, HttpStatus.OK);
	}
@ResponseBody:通過適當的HttpMessageConverter轉換爲指定格式後,寫入到Response對象的body數據區。
這裏@ResponseBody和ResponseEntity效果都是一樣的。
細心發朋友發現我們參數用過Model和Map來存放參數,除了這兩種之外還有ModelAndView,他們最後都會被springmvc封裝成ModelAndView。

@RequestMapping(value="/upload", method=RequestMethod.GET)
	public ModelAndView showUploadPage(ModelAndView model){	
		model.setViewName("upload");
		return model;		
	}
	
	@RequestMapping(value="/doUpload", method=RequestMethod.POST)
	public String doUploadFile(@RequestParam("file") MultipartFile file) throws IOException{
		if(!file.isEmpty()){
			log.debug("doUpload file: {}", file.getOriginalFilename());
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File("c:\\temp\\", System.currentTimeMillis()+ file.getOriginalFilename()));
		}
		return "success";
	}

@RequestParam:請求參數,默認是必須要的,可以修改required=false,來設置非必輸,需要注意的是,如果是false,基本類型的話,如果沒有傳值,會有異常出現,所有最好用包裝類來接收參數。

四:過濾器

springmvc過濾器可以有兩種接口去實現:HandlerInterceptor,WebRequestInterceptor,兩種方式差不多
public class MyInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		System.out.println("MyInterceptor preHandle...");
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if("/spring_mvc/user/upload/".equals(request.getRequestURI())){
			modelAndView.setViewName("user/add");
		}
		System.out.println("MyInterceptor postHandle..."+handler.toString());
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("MyInterceptor afterCompletion...");
	}

}

public class WebInterceptor implements WebRequestInterceptor {

	@Override
	public void preHandle(WebRequest request) throws Exception {
		System.out.println("WebInterceptor preHandle ...");
	}

	@Override
	public void postHandle(WebRequest request, ModelMap model) throws Exception {
		System.out.println("WebInterceptor postHandle ...");
	}

	@Override
	public void afterCompletion(WebRequest request, Exception ex)
			throws Exception {
		System.out.println("WebInterceptor afterCompletion ...");
	}

}

HandlerInterceptor中preHandle方法:返回false後面就不再執行,包括controller。
而WebRequestInterceptor的preHandle是沒有返回值的。當然不是我們寫了一個類springmvc就知道要走這個過濾器。
<mvc:interceptors>
    	<bean class="com.julyday.interceptor.MyInterceptor"></bean>
    	<mvc:interceptor>
    		<mvc:mapping path="/user/upload2"/>
    		<bean class="com.julyday.interceptor.WebInterceptor"></bean>
    	</mvc:interceptor>
    </mvc:interceptors>
springmvc配置文件加上如上信息。
MyInterceptor我們沒有配置mapping,他是過濾所有的controller的,而WebInterceptor我們是配置了mapping的,他是過濾指定url的。
這裏說明下,我們的MyInterceptor過濾/spring_mvc/user/upload/時會指定到另一個視圖,其中最後的“/”也是必須的。
upload2通過控制檯我們可以看到MyInterceptor的preHandle方法先執行,WebInterceptorpreHandle後執行,後面依次是controller,WebInterceptor postHandle ,MyInterceptor postHandle,WebInterceptor afterCompletion ,MyInterceptor afterCompletion,這個是怎麼理解的呢。
我們用過年開車回家的例子來說明:比如上海到安徽,經過江蘇高速MyInterceptor,安徽高速WebInterceptor,然後到家controller,回來我們先是安徽高速,再是江蘇高速,回去上班由於我們生產上出現問題,一路超速行駛,然後收到了安徽高速的罰單,後面又收到了江蘇高速的罰單。

最後放上全部的代碼:代碼下載




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章