1.SpringMVC注解类型
优点:
1.一个控制器可以控制多个动作
2.请求映射不需要存储在配置文件中
1.1 Controller注解类型
@Controller标识这是一个控制器
1 import org.springframework.stereotype.Controller; 2 3 @Controller 4 public class ProductController { 5 6 }
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 > 8 <context:component-scan base-package="app04a.controller"/> //扫描控制器类基本包 9 10 </beans>
1.2 RequestMapping注解类型
@RequestMapping:代表一个请求和一个方法
1 import org.springframework.stereotype.Controller; 2 import org.springframework.web.bind.annotation.RequestMapping; 3 4 5 6 @Controller 7 public class ProductController { 8 @RequestMapping(value="/product_save") 9 public String saveProduct(ProductForm productForm, Model model) { 10 11 return "ProductDetails"; 12 } 13 }
method属性用来代表处理哪些HTTP方法
1 import org.springframework.stereotype.Controller; 2 3 import org.springframework.web.bind.annotation.RequestMapping; 4 import org.springframework.web.bind.annotation.RequestMethod; 5 6 7 8 @Controller 9 public class ProductController { 10 11 @RequestMapping(value = "/product_save", method = RequestMethod.POST) 12 public String saveProduct(ProductForm productForm, RedirectAttributes redirectAttributes) { 13 return "saveProduct"; 14 } 15 16 }
2.编写请求处理的方法
每个请求的处理方法可以有多个不同类型的参数以及一个多种类型的返回结果
3.应用基于注解的控制器
3.1 部署文件Web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="3.0" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 6 <servlet> 7 <servlet-name>springmvc</servlet-name> 8 <servlet-class> 9 org.springframework.web.servlet.DispatcherServlet 10 </servlet-class> 11 <init-param> 12 <param-name>contextConfigLocation</param-name> 13 <param-value>/WEB-INF/config/springmvc-config.xml</param-value> 14 </init-param> 15 <load-on-startup>1</load-on-startup> 16 </servlet> 17 18 <servlet-mapping> 19 <servlet-name>springmvc</servlet-name> 20 <url-pattern>/</url-pattern> 21 </servlet-mapping> 22 </web-app>
3.2 springmvc配置文件
<context:component-scan base-package="app04a.controller"/>:扫描目标中的类
<mvc:annotation-driven/>:注册基于注解的控制器的请求处理方法的bean对象
<mvc:resources mapping="/css/**" location="/css/"/>:指示哪些静态资源需要单独处理,不通过DispatcherServlet
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 <context:component-scan base-package="app04a.controller"/> 15 <mvc:annotation-driven/> 16 <mvc:resources mapping="/css/**" location="/css/"/> 17 <mvc:resources mapping="/*.html" location="/"/> 18 19 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 20 <property name="prefix" value="/WEB-INF/jsp/"/> 21 <property name="suffix" value=".jsp"/> 22 </bean> 23 </beans>
3.3 Controller
1 package app04a.controller; 2 3 import org.apache.commons.logging.Log; 4 import org.apache.commons.logging.LogFactory; 5 import org.springframework.stereotype.Controller; 6 import org.springframework.ui.Model; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 9 import app04a.domain.Product; 10 import app04a.form.ProductForm; 11 12 @Controller 13 public class ProductController { 14 15 private static final Log logger = LogFactory.getLog(ProductController.class); 16 17 @RequestMapping(value="/product_input") 18 public String inputProduct() { 19 logger.info("inputProduct called"); 20 return "ProductForm"; 21 } 22 23 @RequestMapping(value="/product_save") 24 public String saveProduct(ProductForm productForm, Model model) { 25 logger.info("saveProduct called"); 26 // no need to create and instantiate a ProductForm 27 // create Product 28 Product product = new Product(); 29 product.setName(productForm.getName()); 30 product.setDescription(productForm.getDescription()); 31 try { 32 product.setPrice(Float.parseFloat( 33 productForm.getPrice())); 34 } catch (NumberFormatException e) { 35 } 36 37 // add product 38 39 model.addAttribute("product", product); 40 return "ProductDetails"; 41 } 42 }
Model model:用于增加显示在视图中的属性
model.addAttribute("product",product);
3.4 View
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" 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 <style type="text/css">@import url(css/main.css);</style> 6 </head> 7 <body> 8 <div id="global"> 9 <h4>The product has been saved.</h4> 10 <p> 11 <h5>Details:</h5> 12 Product Name: ${product.name}<br/> 13 Description: ${product.description}<br/> 14 Price: $${product.price} 15 </p> 16 </div> 17 </body> 18 </html>
3.5 测试应用
1 http://localhost:8080/app04a/product_input
4.应用@Autowired和@Service进行依赖注入
通过注解@Autowired到字段或方法,实现依赖注入
为了能依赖注入,类必须要声明@Service
1 <context:component-scan base-package="dependencyPackage"/>
1 package app04b.controller; 2 3 import org.apache.commons.logging.Log; 4 import org.apache.commons.logging.LogFactory; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.ui.Model; 8 import org.springframework.web.bind.annotation.PathVariable; 9 import org.springframework.web.bind.annotation.RequestMapping; 10 import org.springframework.web.bind.annotation.RequestMethod; 11 import org.springframework.web.servlet.mvc.support.RedirectAttributes; 12 13 import app04b.domain.Product; 14 import app04b.form.ProductForm; 15 import app04b.service.ProductService; 16 17 @Controller 18 public class ProductController { 19 20 private static final Log logger = LogFactory 21 .getLog(ProductController.class); 22 23 @Autowired //使productService注入到ProductController里 24 private ProductService productService; 25 26 @RequestMapping(value = "/product_input") 27 public String inputProduct() { 28 logger.info("inputProduct called"); 29 return "ProductForm"; 30 } 31 32 @RequestMapping(value = "/product_save", method = RequestMethod.POST) 33 public String saveProduct(ProductForm productForm, RedirectAttributes redirectAttributes) { 34 logger.info("saveProduct called"); 35 // no need to create and instantiate a ProductForm 36 // create Product 37 Product product = new Product(); 38 product.setName(productForm.getName()); 39 product.setDescription(productForm.getDescription()); 40 try { 41 product.setPrice(Float.parseFloat(productForm.getPrice())); 42 } catch (NumberFormatException e) { 43 } 44 45 // add product 46 Product savedProduct = productService.add(product); 47 48 redirectAttributes.addFlashAttribute("message", "The product was successfully added."); 49 50 return "redirect:/product_view/" + savedProduct.getId(); 51 } 52 53 @RequestMapping(value = "/product_view/{id}") 54 public String viewProduct(@PathVariable Long id, Model model) { 55 Product product = productService.get(id); 56 model.addAttribute("product", product); 57 return "ProductView"; 58 } 59 }
1 package app04b.service; 2 3 import app04b.domain.Product; 4 5 public interface ProductService { 6 Product add(Product product); 7 Product get(long id); 8 }
1 package app04b.service; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 import java.util.concurrent.atomic.AtomicLong; 6 7 import org.springframework.stereotype.Service; 8 9 import app04b.domain.Product; 10 11 @Service 12 public class ProductServiceImpl implements ProductService { 13 14 private Map<Long, Product> products = new HashMap<Long, Product>(); 15 private AtomicLong generator = new AtomicLong(); 16 17 public ProductServiceImpl() { 18 Product product = new Product(); 19 product.setName("JX1 Power Drill"); 20 product.setDescription("Powerful hand drill, made to perfection"); 21 product.setPrice(129.99F); 22 add(product); 23 } 24 25 @Override 26 public Product add(Product product) { 27 long newId = generator.incrementAndGet(); 28 product.setId(newId); 29 products.put(newId, product); 30 return product; 31 } 32 33 @Override 34 public Product get(long id) { 35 return products.get(id); 36 } 37 }
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 <context:component-scan base-package="app04b.controller"/> 15 <context:component-scan base-package="app04b.service"/> 16 <mvc:annotation-driven/> 17 <mvc:resources mapping="/css/**" location="/css/"/> 18 <mvc:resources mapping="/*.html" location="/"/> 19 20 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 21 <property name="prefix" value="/WEB-INF/jsp/"/> 22 <property name="suffix" value=".jsp"/> 23 </bean> 24 </beans>
5.重定向和Flash属性
由于重定向经过客户端,所以Model中的一切都在重定向丢失
通过Flash提供了一种供重定向传值的方法
要使用重定向
1.<annotation-drivem>元素
2.
1 @RequestMapping(value = "/product_save", method = RequestMethod.POST) 2 public String saveProduct(ProductForm productForm, RedirectAttributes redirectAttributes) { 3 4 Product product = new Product(); 5 product.setName(productForm.getName()); 6 product.setDescription(productForm.getDescription()); 7 try { 8 product.setPrice(Float.parseFloat(productForm.getPrice())); 9 } catch (NumberFormatException e) { 10 } 11 12 // add product 13 Product savedProduct = productService.add(product); 14 15 redirectAttributes.addFlashAttribute("message", "The product was successfully added."); 16 17 return "redirect:/product_view/" + savedProduct.getId(); 18 } 19 20 21 }
6.请求参数和路径变量
请求参数和路径变量都可以发送值给服务器
请求参数是key=value ,用&分隔
1 http://localhost:8080/app04b/product_retrieve?productId=3 2 2 3 4 5 public void sendProduct(@RequestParam int productId)
路径变量:
1 @RequestMapping(value = "/product_view/{id}") 2 public String viewProduct(@PathVariable Long id, Model model) { 3 Product product = productService.get(id); 4 model.addAttribute("product", product); 5 return "ProductView"; 6 }
7.@ModelAttribute
可以用@ModelAttribute来注释方法参数或方法
@ModelAttribute注释的方法会将输入的或创建的参数对象添加到Model对象中
1 public String submitOrder(@ModelAttribute("newOrder") Order order)
会使用键值order将Order实例添加到Model对象中
@ModelAttribute第二个用途是标注一个非请求的处理方法
SpringMVC会在调用请求处理方法之前调用带@ModelAttribute注解的方法,
@ModelAttribute注解的方法可以返回一个对象或一个void类型,
如果返回对象,则把对象自动添加到Model中。
1 @ModelAttribute 2 public Product viewProduct(@RequestParam String productId) { 3 return productService.get(productId); 4 5 }
如果返回VOID,自行将实例添加到Model中
1 @ModelAttribute 2 public void viewProduct(@RequestParam String id,Model model) { 3 model。addAttribute(new Account(id)); 4 5 }
4.应用@Autowired和@Service进行依赖注入