天天看點

Java EE - Spring MVC 入門介紹以及基于注解開發應用

問題導讀:

1. Spring MVC 的入門操作

2. 如何基于注解開發Spring MVC應用?

解決方案:

Spring MVC入門介紹

1. jar

Java EE - Spring MVC 入門介紹以及基于注解開發應用

2.bean(model)

package bean;

public class Product {
  private  String name;
  private  String description;
  private  Float price;
  public  String getName() {
    return this.name;
  }
  public  void setName(String name) {
    this.name = name;
  }
  public  String getDescription() {
    return description;
  }
  public  void setDescription(String description) {
    this.description = description;
  }
  public  Float getPrice() {
    return price;
  }
  public  void setPrice(Float price) {
    this.price = price;
  }
}      

3.form

package form;

public class ProductForm {
  private  String name;
  private  String description;
  private  String price;
  public  String getName() {
    return this.name;
  }
  public  void setName(String name) {
    this.name = name;
  }
  public  String getDescription() {
    return description;
  }
  public  void setDescription(String description) {
    this.description = description;
  }
  public  String getPrice() {
    return price;
  }
  public  void setPrice(String price) {
    this.price = price;
  }

}      

4.controller

4.1 InputProductController

package com.lpl.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/*
 * 這是傳統風格的控制器,實作Controller接口
 */
public class InputProductController implements Controller{

  @Override
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // TODO Auto-generated method stub
    return new ModelAndView("ProductForm");
  }
  
}      

4.2 SaveProductController

package com.lpl.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import bean.Product;
import form.ProductForm;

public class SaveProductController implements Controller{

  @Override
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    /*
     * 沒有過濾器,手動設定request中對象的字元編碼
     */
    request.setCharacterEncoding("UTF-8");
    // 資料綁定(spring MVC 提供了該功能,之後會使用)
    ProductForm productForm = new ProductForm();
    productForm.setName(request.getParameter("name"));
    productForm.setDescription(request.getParameter("description"));
    productForm.setPrice(request.getParameter("price"));
    
    Product product = new Product();
    product.setName(productForm.getName());
    product.setDescription(productForm.getDescription());
    try {
      product.setPrice(Float.parseFloat(productForm.getPrice()));
    } catch (NumberFormatException e) {
      e.printStackTrace();
    }
    /*
     * 1. 視圖(jsp)
     * 2. 模型(名字)
     * 3. 模型(對象)
     */
    return new ModelAndView("ProductDetails","product",product);
  }
  
}      

5. 配置檔案

5.1 springmvc-config

<?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">     
           <!-- 配置bean -->
           <!-- 
            通過配置bean方式得到的controller每一個controller就是一個action
            -->        
           <bean name="/product_input.do" class="com.lpl.controller.InputProductController" />
           <bean name="/product_save.do" class="com.lpl.controller.SaveProductController" />
           <!-- 
            ViewResolver(視圖解析器)
            配置字首和字尾兩個屬性,這樣視圖解析器将會自動增加字首和字尾
            -->
           <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/" />
            <property name="suffix" value=".jsp" />
           </bean>
</beans>      

5.2 web

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <!-- 
      DispatcherServlet
      1. 調用controller中相應的action
      2. 根據請求參數值構造表單bean
      3. 轉向另一個view層(jsp)
     -->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- spring MVC 的配置檔案 位置 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <!-- web application的classpath包含 WEB-INF/lib下的所有jar包和WEB-INF/classes目錄 -->
      <param-value>classpath:conf/springmvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>      

6. view

6.1 ProductForm

<%@ 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>添加商品</title>
</head>
<body>
    <div>
        <form action="product_save.do" method="post">
            <fieldset>
                <legend>添加商品</legend>
                <label for="name">商品名字:</label>
                <input type="text" id="name" name="name" value="" /><br/>
                <label for="description">商品描述:</label>
                <input type="text" id="description" name="description" value="" /><br/>
                <label for="price">商品價格:</label>
                <input type="text" id="price" name="price" value=""/><br/>
                <div>
                    <input id="reset" type="reset" />
                    <input id="submit" type="submit" value="添加商品" />
                </div>
            </fieldset>
        </form>
    </div>
</body>
</html>      
Java EE - Spring MVC 入門介紹以及基于注解開發應用

6.2 ProductForm

<%@ 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>商品詳情</title>
</head>
<body>
    <div>
        <h4>該商品已經儲存</h4>
        <p>
            <h5>詳細資訊</h5>
            商品名稱:${product.name }</br>
            商品描述:${product.description }</br>
            商品價格:${product.price }
        </p>
    </div>
</body>
</html>      
Java EE - Spring MVC 入門介紹以及基于注解開發應用

基于注解的控制器

1. 采用注解開發應用的幾個優點

  • 一個控制器類可以處理多個動作
  • 一個動作對應一個控制器類中的一個方法

2. 配置檔案

2.1 web

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <!-- 
      DispatcherServlet
      1. 調用controller中相應的action
      2. 根據請求參數值構造表單bean
      3. 轉向另一個view層(jsp)
     -->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- spring MVC 的配置檔案 位置 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <!-- web application的classpath包含 WEB-INF/lib下的所有jar包和WEB-INF/classes目錄 -->
      <param-value>classpath:conf/springmvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!-- 
      1. 當URL模式設定為“/” 時,意味着所有請求(包括靜态資源)一同映射到dispatcher servlet
      2. 為了正确處理靜态資源,需要在Spring MVC配置檔案中添加<resources/>元素
     -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- 
    字元過濾器 
    1. 處理資料綁定中文亂碼
  -->
  <filter>
    <filter-name>SpringEncodingFilter</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>SpringEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>      

2.2 springmvc-config

<?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-3.2.xsd">      
           <!-- 
            1. 聲明掃描機制   xmlns:context="http://www.springframework.org/schema/context"
            2. 掃描包要注意不要指定一個太廣泛的基本包
            -->
           <context:component-scan base-package="com.lpl.controller" />
           <!-- 1. 如果沒有<annotation-driven/>,<resources/>元素會阻止任意控制器被調用 
              2. 若不需要使用 resources,則不需要<annotation-driven/>元素
           -->
           <mvc:annotation-driven />
           <!-- 指定.html 資源不通過dispatcher servlet -->
           <mvc:resources mapping="/*.html" location="/" />
           <!-- 
            ViewResolver(視圖解析器)
            配置字首和字尾兩個屬性,這樣視圖解析器将會自動增加字首和字尾
            -->
           <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/" />
            <property name="suffix" value=".jsp" />
           </bean>
</beans>      

3. controller

package com.lpl.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import bean.Product;
import form.ProductForm;

/*
 * 1. 在配置好spring 的掃描機制的前提下,可以使用注解開發應用
 * 2. @RequestMapping("/xxx.do") 與 @RequestMapping(value = "/xxx.do") 相同
 * 3. @RequestMapping 注解總還可以使用其他屬性
 * 4. 在編寫請求處理方法的時候,可以直接在方法參數中添加HttpServletRequest、HttpServletResponse 等
 * 5. 傳回類型可以為ModelAndView、Model、Map 和 String(邏輯視圖名)等
 */
@Controller
public class ProductController {
  
  @RequestMapping(value="/product_input.do")
  public String inputProduct() {
    return "ProductForm";
  }
  
  @RequestMapping(value="/product_save.do", method=RequestMethod.POST)
  public String saveProduct(HttpServletRequest request, ProductForm productForm, Model model) {
    Product product = new Product();
    product.setName(productForm.getName());
    product.setDescription(productForm.getDescription());
    try {
      product.setPrice(Float.parseFloat(productForm.getPrice()));
    } catch (NumberFormatException e) {
      e.printStackTrace();
    }
    //将商品加入 model 中
    model.addAttribute("product", product);
    
    return "ProductDetails";
  }
}      

4. view

4.1 

Java EE - Spring MVC 入門介紹以及基于注解開發應用

4.2