您的位置:首页 > 编程语言 > Java开发

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

2016-09-20 19:15 971 查看
问题导读:

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-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>




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>




基于注解的控制器

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 



4.2 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: