Java Spring MVC
Spring MVC的實(shí)現(xiàn)包括 實(shí)現(xiàn)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
這里用到了一個(gè)通用接口Controller, Controller的實(shí)現(xiàn)類將作為spring的bean被加載到classpath中,在配置文件中定義uri 和bean之間的對應(yīng)關(guān)系。 配置文件的加載在Web.xml中指定 同時(shí)Web.xml還負(fù)責(zé)定義全局的Dispatcher Servlet來接受根 /的 所有請求。
依賴:
1. Controller接口:
Package: org.springframework.web.servlet.mvc;
方法: ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
實(shí)現(xiàn):
?
?
2. 配置文件:
上面定義了兩個(gè)controller的行為和數(shù)據(jù),那么下一步就是定義請求uri和Controler的對應(yīng)。這里在配置文件中的bean定義來實(shí)現(xiàn)
配置文件:
<?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">/// 對應(yīng)的Controller此處定義為Bean 對應(yīng)的Name為path.?<bean name="/product_input.action" class="controller.ProductInputController2"></bean><bean name="/product_save.action" class="controller.ProductSaveController2"></bean> /// View Resolver使的我們在定義ModelAndview()實(shí)例的時(shí)候不用再指定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的方式來實(shí)現(xiàn)。
Servlet: org.springframework.web.servlet.DispatcherServlet 專門用來處理根請求的分發(fā)
<?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主要解決的問題是一個(gè)文件定義一個(gè)controller(@Controller)多個(gè)request uri(@RequestMapping)。
并且uri和handlerRequest的影射關(guān)系不再需要在配置文件中指定。 在Controller的方法中就指定就可以了。
當(dāng)然controller還是作為bean還是要借助配置文件被加載到classpath中的。類似于<context: component-scan />會加載所有controller文件并且是單例的
這里介紹一個(gè)例子:
1. Model: 這里定義一個(gè)將用于UI 上現(xiàn)實(shí)的Model(注意這個(gè) Model的屬性名稱 必須和UI 上的控件Name對應(yīng),這樣能實(shí)現(xiàn)對象與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對應(yīng)的組建(通過Name屬性)。這樣在POST 方法提交后可以在Controller方法的參數(shù)中獲取對象
用于輸入的表單
<!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> 原碼用于確認(rèn)信息的表單
<!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, 這個(gè)屬性用于在配置文件的 <context: component-scan />
@RequestMapping()用于定義請求地址和handler之間匹配。 Value=""用于標(biāo)示請求的uri. Method用于標(biāo)示請求的方式
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的時(shí)候?qū)⒃L問到這個(gè)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的時(shí)候?qū)⒃L問到這個(gè)method // 這里的參數(shù) productForm能夠自動(dòng)根據(jù)輸入表丹的屬性初始化對象。 Model用于傳遞對象給下一個(gè)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的發(fā)現(xiàn):
之前使用的<bean></bean>定義一個(gè)類是bean ,這里因?yàn)橛?#64;Controller 的存在已經(jīng)證明是bean了,需要作的是掃描到他。
<context:component-scan /> 就是這個(gè)作用。
4. Controelr配置文件的定義:
web.xml中定義DispactcherServlet處理所有請求,并且Servlet中指定配置文件。 內(nèi)容就是3中指定的。
?
Formatter、Converter
1. Converter接口
public interface Converter<S, T> {T convert(S var1); }?S是原數(shù)據(jù)類型,T是轉(zhuǎn)換目標(biāo)
如 日期輸入框輸入的都是字符串類型,Converter可以負(fù)責(zé)自動(dòng)轉(zhuǎn)換成日期類型 而不必在Controller里用代碼判斷和轉(zhuǎn)換
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輸入的是字符串,但是因?yàn)镃onverter的存在會自動(dòng)實(shí)現(xiàn)字符串轉(zhuǎn)成目標(biāo)(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相同,但是 元數(shù)據(jù)類型只能是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>?
轉(zhuǎn)載于:https://www.cnblogs.com/ygshen/p/5701442.html
總結(jié)
以上是生活随笔為你收集整理的Java Spring MVC的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: javscript对cookie的操作,
- 下一篇: Java博客集锦