Spring MVC的实现包括 实现Controller类和基于注解的Controller RequstMapping方式

依赖:

  1. <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-webmvc</artifactId>
  5. <version>4.3.1.RELEASE</version>
  6. </dependency>
  7. <!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
  8. <dependency>
  9. <groupId>org.springframework</groupId>
  10. <artifactId>spring-context-support</artifactId>
  11. <version>4.3.1.RELEASE</version>
  12. </dependency>
  13.  
  14. <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
  15. <dependency>
  16. <groupId>javax.servlet</groupId>
  17. <artifactId>javax.servlet-api</artifactId>
  18. <version>3.1.0</version>
  19. </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;

实现:

  1. public class ProductInputController2 implements Controller {
  2.  
  3. // GET 方法 返回表单
  4. /// 这里返回ModelAndView的示例 参数代表JSP的名字
  5. public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
  6. return new ModelAndView("ProductForm");
  7. }
  8. }
  9.  
  10. public class ProductSaveController2 implements Controller {
  11.  
  12. public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
  13. productForm form = new productForm(0,httpServletRequest.getParameter("name"), Float.parseFloat(httpServletRequest.getParameter("price")));
  14. product p = new product(form.get_id(),form.get_name(),form.get_price());
  15.  
  16. // 这里设置request的对象参数。 将来会在ProductDetails的view中用于显示对象属性
  17. return new ModelAndView("ProductDetails","product",p);
  18. }
  19. }

2. 配置文件:

上面定义了两个controller的行为和数据,那么下一步就是定义请求uri和Controler的对应。这里在配置文件中的bean定义来实现

配置文件:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5.   /// 对应的Controller此处定义为Bean 对应的Name为path. 
  6. <bean name="/product_input.action" class="controller.ProductInputController2"></bean>
  7. <bean name="/product_save.action" class="controller.ProductSaveController2"></bean>
  8. /// View Resolver使的我们在定义ModelAndview()实例的时候不用再指定path和后缀
  9. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  10. <property name="prefix" value="/WEB-INF/jsp/"></property>
  11. <property name="suffix" value=".jsp"></property>
  12. </bean>
  13. </beans>

3. 配置文件的加载:

通过Web.xml 中自定义DispatcherServlet的方式来实现。

Servlet: org.springframework.web.servlet.DispatcherServlet 专门用来处理根请求的分发

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  5. version="3.1">
  6.  
  7. <servlet>
  8. <servlet-name>controllerServlet</servlet-name>
  9. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10.  
  11. <init-param>
  12. <param-name>contextConfigLocation</param-name>
  13. <param-value>classpath:spring-web.xml</param-value>
  14. </init-param>
  15.  
  16. <load-on-startup>1</load-on-startup>
  17. </servlet>
  18. <servlet-mapping>
  19. <servlet-name>controllerServlet</servlet-name>
  20. <url-pattern>/</url-pattern>
  21. </servlet-mapping>
  22.  
  23. </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 的绑定)

  1. public class productForm {
  2. private int id;
  3. private String name;
  4. private float price;
  5.  
  6. public float getPrice() {
  7. return price;
  8. }
  9.  
  10. public void setPrice(float price) {
  11. this.price = price;
  12. }
  13.  
  14. public int getId() {
  15. return id;
  16. }
  17.  
  18. public void setId(int id) {
  19. this.id = id;
  20. }
  21.  
  22. public String getName() {
  23. return name;
  24. }
  25.  
  26. public void setName(String name) {
  27. this.name = name;
  28. }
  29.  
  30. public productForm(int id, String name, float price){
  31. this.id =id;
  32. this.name =name;
  33. this.price =price;
  34.  
  35. }
  36.  
  37. public productForm(){}
  38. }

2. View: 输入jsp 页面定义了上面Model对应的组建(通过Name属性)。这样在POST 方法提交后可以在Controller方法的参数中获取对象

用于输入的表单

  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title>Add Product Form</title>
  5. <style type="text/css">@import url(css/main.css);</style>
  6. </head>
  7. <body>
  8.  
  9. <div id="global">
  10. <form action="product_save.action" method="post">
  11. <fieldset>
  12. <legend>Add a product</legend>
  13. <p>
  14. <label for="name">Product Name: </label>
  15. <input type="text" id="name" name="name"
  16. tabindex="1">
  17. </p>
  18. <p>
  19. <label for="description">Description: </label>
  20. <input type="text" id="description"
  21. name="description" tabindex="2">
  22. </p>
  23. <p>
  24. <label for="price">Price: </label>
  25. <input type="text" id="price" name="price"
  26. tabindex="3">
  27. </p>
  28. <p id="buttons">
  29. <input id="reset" type="reset" tabindex="4">
  30. <input id="submit" type="submit" tabindex="5"
  31. value="Add Product">
  32. </p>
  33. </fieldset>
  34. </form>
  35. </div>
  36. </body>
  37. </html>

原码

用于确认信息的表单

  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title>Save Product</title>
  5. </head>
  6. <body>
  7. <div id="global">
  8. <h4>The product has been saved.</h4>
  9. <p>
  10. <h5>Details:</h5>
  11. Product Name: ${product.name}<br/>
  12. Price: $${product.price}
  13. </p>
  14. </div>
  15. </body>
  16. </html>

Source

3. Controller:@Contoller注解用于定义Controller bean, 这个属性用于在配置文件的 <context: component-scan />

@RequestMapping()用于定义请求地址和handler之间匹配。 Value=""用于标示请求的uri. Method用于标示请求的方式

GET and POST

  1. import model.product;
  2. import model.productForm;
  3.  
  4. import org.apache.commons.logging.Log;
  5. import org.apache.commons.logging.LogFactory;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestMethod;
  10.  
  11. /**
  12. * Created by ygshen on 7/18/16.
  13. */
  14. @Controller
  15. public class ProductController {
  16.  
  17. private static Log logger = LogFactory.getLog(ProductController.class);
  18.  
  19. // http://localhost:8080/springmvc/product_form2.action的时候将访问到这个method
  20. @RequestMapping(value = "/product_form2.action")
  21. public String productForm(){
  22.  
  23. logger.info("Request the product input form ");
  24. return "ProductForm";
  25. }
  26. // http://localhost:8080/springmvc/product_save.action的时候将访问到这个method
  27. // 这里的参数 productForm能够自动根据输入表丹的属性初始化对象。 Model用于传递对象给下一个View。 类似与Request.setAttribute("product",p).
  28. @RequestMapping(value = "/product_save.action", method = {RequestMethod.POST, RequestMethod.PUT})
  29. public String saveForm(productForm form, Model model){
  30. logger.info("request the product save post method");
  31. logger.info("Product Name: "+ form.getName()+ ". Product price: "+ form.getPrice());
  32.  
  33. product p = new product(form.getId(),form.getName(),form.getPrice());
  34. model.addAttribute("product",p);
  35. return "ProductDetails";
  36. }
  37. }

4. Controller的发现:

之前使用的<bean></bean>定义一个类是bean ,这里因为有@Controller 的存在已经证明是bean了,需要作的是扫描到他。
<context:component-scan /> 就是这个作用。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:p="http://www.springframework.org/schema/p"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xmlns:context="http://www.springframework.org/schema/context"
  7. xsi:schemaLocation="
  8. http://www.springframework.org/schema/beans
  9. http://www.springframework.org/schema/beans/spring-beans.xsd
  10. http://www.springframework.org/schema/mvc
  11. http://www.springframework.org/schema/mvc/spring-mvc.xsd
  12. http://www.springframework.org/schema/context
  13. http://www.springframework.org/schema/context/spring-context.xsd">
  14.  
  15. <context:component-scan base-package="web.controller" />
  16.  
  17. <mvc:annotation-driven></mvc:annotation-driven>
  18. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  19. <property name="prefix" value="/WEB-INF/jsp/"></property>
  20. <property name="suffix" value=".jsp"></property>
  21. </bean>
  22. </beans>

4. Controelr配置文件的定义:

web.xml中定义DispactcherServlet处理所有请求,并且Servlet中指定配置文件。 内容就是3中指定的。

Formatter、Converter

1. Converter接口

  1. public interface Converter<S, T> {
  2. T convert(S var1);
  3. }

S是原数据类型,T是转换目标

如 日期输入框输入的都是字符串类型,Converter可以负责自动转换成日期类型 而不必在Controller里用代码判断和转换

  1. public class StringToDateConverter implements Converter<String, Date> {
  2. public Date convert(String dateString) {
  3. try {
  4. SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
  5. simpleDateFormat.setLenient(false);
  6. return simpleDateFormat.parse(dateString);
  7. }
  8. catch (ParseException exception){
  9. throw new IllegalArgumentException("Invalid date formate"+ datePattern);
  10. }
  11. }
  12.  
  13. private String datePattern;
  14.  
  15. public StringToDateConverter(String _datePattern) {
  16. datePattern=_datePattern;
  17. }
  18. }
  1. <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文件中注册了

  1. <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
  2. <property name="converters">
  3. <set>
  4. <bean class="Formatters.StringToDateConverter">
  5. <constructor-arg type="java.lang.String" value="MM-dd-yyyy"></constructor-arg>
  6. </bean>
  7. </set>
  8. </property>
  9. </bean>
  10. <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

2. Formatter: 作用和Converter相同,但是 元数据类型只能是String.

  1. public interface Formatter<T> extends Printer<T>, Parser<T> {
  2. }

另外 Formatter的注册方式如下

  1. <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
  2. <property name="formatters">
  3. <set>
  4. <bean class="Formatters.StringToDateConverter">
  5. <constructor-arg type="java.lang.String" value="MM-dd-yyyy"></constructor-arg>
  6. </bean>
  7. </set>
  8. </property>
  9. </bean>
  10. <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

Java Spring MVC的更多相关文章

  1. 支持Java Spring MVC

    Java Spring MVC能很方便在后台返回JSON数据,所以与MiniUI进行数据交互非常简单. 1)后台处理: 在MVC控制器中,可以通过方法参数接收数据,也可以通过Request接收更复杂的 ...

  2. Java spring mvc多数据源配置

    1.首先配置两个数据库<bean id="dataSourceA" class="org.apache.commons.dbcp.BasicDataSource&q ...

  3. Java Spring mvc 操作 Redis 及 Redis 集群

    本文原创,转载请注明:http://www.cnblogs.com/fengzheng/p/5941953.html 关于 Redis 集群搭建可以参考我的另一篇文章 Redis集群搭建与简单使用 R ...

  4. java spring mvc restful 上传文件

    spring mvc 配置文件 <bean class="com.baiyyy.yfz.core.RestfulHandlerMethodMapping" />     ...

  5. [Java] Spring MVC 知识点

    云图: @Service 用于标注业务层组件. 在 Spring-servlet 配置xml中,component-scan 标签默认情况下自动扫描指定路径下的包(含所有子包),将带有@Compone ...

  6. 从零开始学 Java - Spring MVC 实现跨域资源 CORS 请求

    论职业的重要性 问:为什么所有家长都希望自己的孩子成为公务员? 答:体面.有权.有钱又悠闲. 问:为什么所有家长都希望自己的孩子成为律师或医生? 答:体面.有钱.有技能. 问:为什么所有家长都不怎么知 ...

  7. Java Spring MVC项目搭建(二)——项目配置

    1.站点配置文件web.xml 每一个Spring MVC 项目都必须有一个站点配置文件web.xml,他的主要功能吗....有一位大哥已经整理的很好,我借来了,大家看看: 引用博客地址: http: ...

  8. Java Spring MVC项目搭建(一)——Spring MVC框架集成

    1.Java JDK及Tomcat安装 我这里安装的是JDK 1.8 及 Tomcat 8,安装步骤详见:http://www.cnblogs.com/eczhou/p/6285248.html 2. ...

  9. java spring mvc 全注解

    本人苦逼学生一枚,马上就要毕业,面临找工作,实在是不想离开学校.在老师的教导下学习了spring mvc ,配置文件实在繁琐,因此网上百度学习了spring mvc 全注解方式完成spring的装配工 ...

随机推荐

  1. TinyURL缩短网址服务 - Blog透视镜

    TinyURL是个缩短网址服务的网站,提供1个短网址转向指定到长网址,像是杂志书籍中若有网址太长,也都会用TinyURL来缩短网址,例如本篇文章:http://blog.openyu.org/2014 ...

  2. Android 设置让EditText不自动获取焦点

    在EditText所在的父控件中设置如下属性: android:focusable="true" android:focusableInTouchMode="true&q ...

  3. Codeforces 486D D. Valid Sets

    http://codeforces.com/contest/486/problem/D 题意:给定一棵树,点上有权值,以及d,要求有多少种联通块满足最大值减最小值小于等于d. 思路:枚举i作为最大的点 ...

  4. Win8/Win8.1都有哪些版本?我该选择哪个?(二)

    Windows版本分类比较复杂,下文主要为大家理清Win8/Win8.1的版本种类.如果想了解更多,可以结合<Win7/Win8/Win8.1众多版本,我该选择哪个?>一文来了解. 细数W ...

  5. Keil C51里关于堆栈指针的处理

    Keil C是非常优秀的C51编译器,可能是最好的C51编译器,提供各种优化模式,对变量的优化和地址安排做得非常好.这是用C语言写代码的好处之一,如果用汇编写,得费一大番功夫给各个变量安排内存物理地址 ...

  6. ANSIC程序到KeilC51的移植心得

    摘要:本文讲述了将ANSIC程序移植到KeilC51上应该注意的事项.文章讲述了存储类型.指针类型.重入函数.根据目标系统RAM的分布的段定位和仿真栈设置.函数指针.NULL指针问题.字节顺序.交叉汇 ...

  7. 《Programming WPF》翻译 第6章 5.我们进行到哪里了?

    原文:<Programming WPF>翻译 第6章 5.我们进行到哪里了? WPF提供了资源工具,让我们运用在用户界面中,动态并具有一致性.我们可以在资源字典中存储任意资源,并且可以遍及 ...

  8. BLOB二进制对象(blob.c/h)

    BLOB二进制对象(blob.c/h) 数据结构 struct blob_attr { uint32_t id_len; /** 高1位为extend标志,高7位存储id, * 低24位存储data的 ...

  9. hihoCoder 1092 : Have Lunch Together

    题目大意:小hi和小ho去咖啡厅喝咖啡,咖啡厅可以看作是n * m的矩阵,每个点要么为空,要么被人.障碍物.椅子所占据,小hi和小ho想要找两个相邻的椅子.起初两个人都在同一个点,求两人到达满足要求的 ...

  10. Find Median from Data Stream 解答

    Question Median is the middle value in an ordered integer list. If the size of the list is even, the ...