SpringMvc的簡單入門(一)

一.什麼是Springmvc

SpringMVC屬於SpringFrameWork的後續產品。Spring 框架提供了構建 Web 應用程序的全功能 MVC 模塊。使用 Spring 可插入的 MVC架構,從而在使用Spring進行WEB開發時,可以選擇使用Spring的SpringMVC框架或集成其他MVC開發框架,如Struts1,Struts2等.

二.springmvc的框架結構


三.springmvc的簡單應用

創建maven項目,在pom.xml中配置架包

<!-- 配置springmvc的架包 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.3.12.RELEASE</version>
		</dependency>

在web.xml中配置springmvc的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">
	
	
	
	<!-- 解決亂碼問題 -->
  <filter>
		<filter-name>myFilterone</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	<init-param>
		<!-- encoding只是設計request -->
		<param-name>encoding</param-name>
		<param-value>UTF-8</param-value>
	</init-param>
	<!-- request和response都設計 -->
	<init-param>
		<param-name>forceEncoding</param-name>
		<param-value>true</param-value>
	</init-param>
	</filter>
	<filter-mapping>
		<filter-name>myFilterone</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- 在使用springmvc的標籤或者國際化 都需要spring的支持 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:/spring.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
		<!-- 請求method支持put和delete必須添加過濾器 -->
	<filter>
		<filter-name>myFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	
	<filter-mapping>
		<filter-name>myFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- springmvc配置 -->
 <servlet>
  	<servlet-name>mvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<load-on-startup>1</load-on-startup>
  </servlet>	
  <servlet-mapping>
  	<servlet-name>mvc</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
	
	<!-- freemarker配置 -->
  <servlet>
  <servlet-name>freemarker</servlet-name>
  <servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
    
  <!-- 模板的查找路徑  從上下文根路徑查找 模板 ftl-->
  <init-param>
    <param-name>TemplatePath</param-name>
    <param-value>/</param-value>
  </init-param>
  <!-- 是否不需要緩存 -->
  <init-param>
    <param-name>NoCache</param-name>
    <param-value>true</param-value>
  </init-param>
  <!-- 最終顯示是html -->
  <init-param>
    <param-name>ContentType</param-name>
    <param-value>text/html;charset=UTF-8</param-value>
  </init-param>
    
  <!-- FreeMarker settings: -->
  <init-param>
    <param-name>template_update_delay</param-name>
    <param-value>0</param-value> <!-- 0 is for development only! Use higher value otherwise. -->
  </init-param>
  <init-param>
    <param-name>default_encoding</param-name>
    <param-value>UTF-8</param-value>
  </init-param>
  <!-- 數字的格式 -->
  <init-param>
    <param-name>number_format</param-name>
    <param-value>0.##</param-value>
  </init-param>
  <!-- servlet 容器啓動時實例化 -->
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>freemarker</servlet-name>
  <url-pattern>*.ftl</url-pattern>
</servlet-mapping> 
 
 
 
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  </web-app>



在WEB-INF下必須有個mvc-servlet.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
	http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
	http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
	http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
	">
	<!-- 掃描bean -->
  <context:component-scan base-package="springmvc"></context:component-scan>
  <!-- springmvc 配置攔截  / 所有資源都被攔截 圖片無法展示  將除控制層以外的資源交回給servlet處理 -->
  <mvc:default-servlet-handler/>
  <!-- 將springmvc註解的action交給springmvc處理 -->
  
  <mvc:annotation-driven  validator="localValidatorFactoryBean">
  	<mvc:message-converters>
  	<!-- 配置json消息轉換器 -->
  		<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
  			<property name="supportedMediaTypes">
  				<list>
  					<value>text/html</value>
  					<value>application/x-www-form-urlencoded</value>
  				</list>
  			</property>
  		</bean>
  	</mvc:message-converters>
  </mvc:annotation-driven>
  <bean id="localValidatorFactoryBean" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
  	<property name="validationMessageSource" ref="messageSource"></property>
  </bean>

   
  
  <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  	<property name="prefix" value="/"></property>
  	<property name="suffix" value=".jsp"></property>
  </bean>
  <!-- 該攔截器用於攔截URL上參數 -->
  <mvc:interceptors>
  	<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
  	<!-- 沒傳就讀瀏覽器的 -->
  	<property name="paramName" value="a"></property>
  	</bean>
  	<mvc:interceptor>
  		<mvc:mapping path="/tm"/>
  		<bean class="springmvc.less05.controller.MyInterController"></bean>
  	</mvc:interceptor>
  </mvc:interceptors>
  <!-- 參數需要被臨時存儲在某個地方 當用戶再次訪問使用之前設置的參數 -->
  <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
  </bean>
  
  <!-- 啓用文件上傳 -->
  <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     <!-- 限制上傳文件大小 5M -->
  	 <property name="maxUploadSize" value="5242880"></property>
  </bean>
  <context:property-placeholder location="classpath:/jdbc.properties"/>
   <bean id="dataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
     <property name="url" value="${url}" ></property>
     <property name="username" value="${userName1}" ></property>
     <property name="password" value="${password}" ></property>
     <property name="driverClassName" value="${driverClassName}" ></property>
   </bean>
   <!-- 事務管理器  不再使用jdbc的commit和rollback 必須由事務管理器提供 -->
   <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     <property name="dataSource" ref="dataSource"></property> 
   </bean>
   <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
   	   <property name="dataSource" ref="dataSource"></property> 
   </bean>
   <!-- 定義通知  通知的代碼 spring已經實現  -->
   <tx:advice id="myAdvise"  transaction-manager="transactionManager">
	   	<tx:attributes>
	   		<tx:method name="update*"/>
	   		<tx:method name="save*"/>
	   		<tx:method name="delete*"/>
	   		<tx:method name="select*" read-only="true"/>
	   	</tx:attributes>
   </tx:advice>
   
   <aop:config>
   	<aop:pointcut expression="execution(* springmvc.*.*.*.*(..))  " id="myPoint"/>
    <aop:advisor advice-ref="myAdvise" pointcut-ref="myPoint"/>
   </aop:config>
</beans>

簡單的應用

package springmvc.less01.hellow;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * springmvc中一個路徑和方法的映射叫做一個action(動作)
 */
@Controller
public class HelloController {
	@RequestMapping("/text")
	public String add(HttpServletResponse response,HttpServletRequest request) throws IOException{
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().println("你好 springmvc="+request.getParameter("id"));
		return null;
	}
	@RequestMapping("/param")
	public String updete(User user,HttpServletResponse response) throws IOException{
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().println(user.getId()+"--"+user.getName());
		return null;
	}
	@RequestMapping("/mvc")
	public String mvc(HttpServletRequest request) throws IOException{
		request.setAttribute("name", "zs");
		return "/index.jsp";
	}
}

四.Restful風格設計概念

      REST,即RepresentationalState Transfer的縮寫。"表現層狀態轉化"。研究計算機科學兩大前沿----軟件和網絡----的交叉點

    "表現層"其實指的是"資源"(Resources)的"表現層"。所謂"資源",就是網絡上的一個實體,或者說是網絡上的一個具體信息。它可以是一段文本、一張圖片、一首歌曲、一種服務,總之就是一個具體的實在。你可以用一個URI(統一資源定位符)指向它,每種資源對應一個特定的URI。要獲取這個資源,訪問它的URI就可以,因此URI就成了每一個資源的地址或獨一無二的識別符。

    restful URI的設計不該包含動詞。因爲"資源"表示一種實體,所以應該是名詞,URI不應該有動詞,動詞應該放在HTTP協議中。

舉例來說,某個URI是/arcticle/show/1,其中show是動詞,這個URI就設計錯了,正確的寫法應該是/arcticle/1,然後用GET方法表示show。

  優質Web架構五條關鍵原則列舉如下:

Ø爲所有“事物”定義ID
Ø將所有事物鏈接在一起 (超鏈接)
Ø使用標準方法 (Get Post Delete Put)
Ø資源多重表述 (針對不同的需求提供資源多重表述 arcticle/1 )
Ø無狀態通信 (節省服務器內存)

對資源的操作就是一個動作(GET(查) | POST(新增) | PUT(修改) | DELETE (刪除) )

rest是一種設計風格 設計資源的標識符

http://localhost:8080/s/deleteUser?id=1(標準http協議 資源定義方式)

http://localhost:8080/s/user/1(rest風格)

rest風格的controller

package springmvc.less01.hellow;

import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 瀏覽器的提交方式必須和@RequestMapping指定的資源動作必須一致
 * 否則拋出405
 * @author Administrator
 *
 */
@Controller
public class RestController {
	/**
	 * /user/2==/user/{userid=2}
	 * @return
	 */
	@RequestMapping(value="/user/{id}",method=RequestMethod.GET)
	public String index(@PathVariable(value="id") String userid){
		
		return "/less01/user.jsp";
	}
	@RequestMapping(value="/user/{id}",method=RequestMethod.PUT)
	public String updateUser(@PathVariable(value="id") String userid,String name,HttpServletResponse response) throws IOException{
		response.getWriter().println(userid+name+"update");
		return null;
	}
	
	@RequestMapping(value="/user",method=RequestMethod.POST)
	public String aauser(String name,HttpServletResponse response) throws IOException{
		response.getWriter().println(name+"add");
		return null;
	}
	
	@RequestMapping(value="/user/{id}",method=RequestMethod.DELETE)
	public String deleteUser(@PathVariable(value="id") String userid,HttpServletResponse response) throws IOException{
		response.getWriter().println(userid+"delete");
		return null;
	}
}

jsp頁面

  <body algin="centet">
  <form action="${pageContext.request.contextPath}/user/1" method="post">
  	<input type="hidden" name="_method" value="put">
 	<input type="text" name="name">
 	<input type="submit" value="上傳"/> 
  </form>



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