Java Spring MVC
Spring MVC的實現包括 實現Controller類和基于注解的Controller RequstMapping方式
依賴:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>4.3.1.RELEASE</version></dependency><!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support --><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>4.3.1.RELEASE</version></dependency><!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency> Source?
基于Controller接口的MVC
這里用到了一個通用接口Controller, Controller的實現類將作為spring的bean被加載到classpath中,在配置文件中定義uri 和bean之間的對應關系。 配置文件的加載在Web.xml中指定 同時Web.xml還負責定義全局的Dispatcher Servlet來接受根 /的 所有請求。
依賴:
1. Controller接口:
Package: org.springframework.web.servlet.mvc;
方法: ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
實現:
?
?
2. 配置文件:
上面定義了兩個controller的行為和數據,那么下一步就是定義請求uri和Controler的對應。這里在配置文件中的bean定義來實現
配置文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">/// 對應的Controller此處定義為Bean 對應的Name為path.?<bean name="/product_input.action" class="controller.ProductInputController2"></bean><bean name="/product_save.action" class="controller.ProductSaveController2"></bean> /// View Resolver使的我們在定義ModelAndview()實例的時候不用再指定path和后綴<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/"></property><property name="suffix" value=".jsp"></property></bean> </beans>?
3. 配置文件的加載:
通過Web.xml 中自定義DispatcherServlet的方式來實現。
Servlet: org.springframework.web.servlet.DispatcherServlet 專門用來處理根請求的分發
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1"><servlet><servlet-name>controllerServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-web.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>controllerServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app>?
?
?
基于注解的MVC
基于注解的MVC主要解決的問題是一個文件定義一個controller(@Controller)多個request uri(@RequestMapping)。
并且uri和handlerRequest的影射關系不再需要在配置文件中指定。 在Controller的方法中就指定就可以了。
當然controller還是作為bean還是要借助配置文件被加載到classpath中的。類似于<context: component-scan />會加載所有controller文件并且是單例的
這里介紹一個例子:
1. Model: 這里定義一個將用于UI 上現實的Model(注意這個 Model的屬性名稱 必須和UI 上的控件Name對應,這樣能實現對象與UI 的綁定)
public class productForm {private int id;private String name;private float price;public float getPrice() {return price;}public void setPrice(float price) {this.price = price;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public productForm(int id, String name, float price){this.id =id;this.name =name;this.price =price;}public productForm(){} }?2. View: 輸入jsp 頁面定義了上面Model對應的組建(通過Name屬性)。這樣在POST 方法提交后可以在Controller方法的參數中獲取對象
用于輸入的表單
<!DOCTYPE HTML> <html> <head> <title>Add Product Form</title> <style type="text/css">@import url(css/main.css);</style> </head> <body><div id="global"> <form action="product_save.action" method="post"><fieldset><legend>Add a product</legend><p><label for="name">Product Name: </label><input type="text" id="name" name="name" tabindex="1"></p><p><label for="description">Description: </label><input type="text" id="description" name="description" tabindex="2"></p><p><label for="price">Price: </label><input type="text" id="price" name="price" tabindex="3"></p><p id="buttons"><input id="reset" type="reset" tabindex="4"><input id="submit" type="submit" tabindex="5" value="Add Product"></p></fieldset> </form> </div> </body> </html> 原碼用于確認信息的表單
<!DOCTYPE HTML> <html> <head> <title>Save Product</title> </head> <body> <div id="global"><h4>The product has been saved.</h4><p><h5>Details:</h5>Product Name: ${product.name}<br/>Price: $${product.price}</p> </div> </body> </html> Source?
3. Controller:@Contoller注解用于定義Controller bean, 這個屬性用于在配置文件的 <context: component-scan />
@RequestMapping()用于定義請求地址和handler之間匹配。 Value=""用于標示請求的uri. Method用于標示請求的方式
GET and POST
import model.product; import model.productForm;import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;/*** Created by ygshen on 7/18/16.*/ @Controller public class ProductController {private static Log logger = LogFactory.getLog(ProductController.class);// http://localhost:8080/springmvc/product_form2.action的時候將訪問到這個method@RequestMapping(value = "/product_form2.action")public String productForm(){logger.info("Request the product input form ");return "ProductForm";}// http://localhost:8080/springmvc/product_save.action的時候將訪問到這個method // 這里的參數 productForm能夠自動根據輸入表丹的屬性初始化對象。 Model用于傳遞對象給下一個View。 類似與Request.setAttribute("product",p). @RequestMapping(value = "/product_save.action", method = {RequestMethod.POST, RequestMethod.PUT})public String saveForm(productForm form, Model model){logger.info("request the product save post method");logger.info("Product Name: "+ form.getName()+ ". Product price: "+ form.getPrice());product p = new product(form.getId(),form.getName(),form.getPrice());model.addAttribute("product",p);return "ProductDetails";} }?
4. Controller的發現:
之前使用的<bean></bean>定義一個類是bean ,這里因為有@Controller 的存在已經證明是bean了,需要作的是掃描到他。
<context:component-scan /> 就是這個作用。
4. Controelr配置文件的定義:
web.xml中定義DispactcherServlet處理所有請求,并且Servlet中指定配置文件。 內容就是3中指定的。
?
Formatter、Converter
1. Converter接口
public interface Converter<S, T> {T convert(S var1); }?S是原數據類型,T是轉換目標
如 日期輸入框輸入的都是字符串類型,Converter可以負責自動轉換成日期類型 而不必在Controller里用代碼判斷和轉換
public class StringToDateConverter implements Converter<String, Date> {public Date convert(String dateString) {try {SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);simpleDateFormat.setLenient(false);return simpleDateFormat.parse(dateString);}catch (ParseException exception){throw new IllegalArgumentException("Invalid date formate"+ datePattern);}}private String datePattern;public StringToDateConverter(String _datePattern) {datePattern=_datePattern;} } View Code <form:errors path="publishTime" cssClass="error"></form:errors><label for="publishTime">PublishTime:</label>
<form:input path="publishTime" id="publishTimes" type="text"></form:input>
這里Input輸入的是字符串,但是因為Converter的存在會自動實現字符串轉成目標(Path=publishTime在Model中的屬性被定義成 Date類型)類型。
前提是Converter必須在 configure文件中注冊了
?
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"><property name="converters"><set><bean class="Formatters.StringToDateConverter"><constructor-arg type="java.lang.String" value="MM-dd-yyyy"></constructor-arg></bean></set></property></bean><mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>?
2. Formatter: 作用和Converter相同,但是 元數據類型只能是String.
public interface Formatter<T> extends Printer<T>, Parser<T> { }?另外 Formatter的注冊方式如下
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><property name="formatters"><set><bean class="Formatters.StringToDateConverter"><constructor-arg type="java.lang.String" value="MM-dd-yyyy"></constructor-arg></bean></set></property></bean><mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>?
轉載于:https://www.cnblogs.com/ygshen/p/5701442.html
總結
以上是生活随笔為你收集整理的Java Spring MVC的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: javscript对cookie的操作,
- 下一篇: Java博客集锦