国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > web前端 > htmlcss > Java EE - Spring MVC 入门介绍以及基于注解开发应用

Java EE - Spring MVC 入门介绍以及基于注解开发应用

来源:程序员人生   发布时间:2016-11-22 08:59:42 阅读次数:2636次

问题导读:

1. Spring MVC 的入门操作

2. 如何基于注解开发Spring MVC利用?


解决方案:


Spring MVC入门介绍


1. jar





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⑻"); // 数据绑定(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⑻"?> <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就是1个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⑻"?> <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⑻" pageEncoding="UTF⑻"%> <!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⑻"> <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>


6.2 ProductForm


<%@ page language="java" contentType="text/html; charset=UTF⑻" pageEncoding="UTF⑻"%> <!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⑻"> <title>商品详情</title> </head> <body> <div> <h4>该商品已保存</h4> <p> <h5>详细信息</h5> 商品名称:${product.name }</br> 商品描写:${product.description }</br> 商品价格:${product.price } </p> </div> </body> </html>



基于注解的控制器


1. 采取注解开发利用的几个优点

  • 1个控制器类可以处理多个动作
  • 1个动作对应1个控制器类中的1个方法

2. 配置文件


2.1 web


<?xml version="1.0" encoding="UTF⑻"?> <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模式设置为“/” 时,意味着所有要求(包括静态资源)1同映照到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⑻</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⑻"?> <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⑶.2.xsd"> <!-- 1. 声明扫描机制 xmlns:context="http://www.springframework.org/schema/context" 2. 扫描包要注意不要指定1个太广泛的基本包 --> <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 



4.2 




生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生