SpringMVC
SpringMVCとStruts2は、どちらもプレゼンテーションレイヤーのフレームワークに属しています。これは、Springフレームワークの一部です。Springの全体的な構造から、次のことがわかります。
b / sシステムでのMVC設計パターンの適用
1.ユーザーがコントローラーへの要求を開始する
ユーザーが受け取ったデータを制御し、処理のためにモデルに委任する
2.コントローラはモデルを通じてデータを処理し、処理結果を取得します
モデルは通常、ビジネスロジックを参照します
3.モデルの処理結果がコントローラーに返されます
4.コントローラはビューにモデルデータを表示します
Webのモデルは、データをビューに直接表示できず、コントローラーで完了する必要があります。モデルがC / Sアプリケーションにある場合、データをビューに表示できます。
5.コントローラーはビュー応答をユーザーに応答します
ビューを介してユーザーにデータまたは処理結果を表示します。
SpringMVCアーキテクチャ図
手順
最初のステップ:フロントコントローラー(DispatcherServlet)へのリクエストを開始します。
2番目のステップ:DispatcherServletは、プロセッサー(ハンドラー)を見つけるためにプロセッサーマッパー(HandlerMapping)を要求します。
XML構成と注釈に従って検索できます
ステップ3:HandlerMappingがハンドラーをDispatcherServletに返す
ステップ4:DispatcherServletはプロセッサアダプタ(Handleradapter)を呼び出してハンドラを実行します
ステップ5:ハンドラーを実行するためのradapterの処理
6番目のステップ:ハンドラーの実行が完了し、HandleradapterがModelAndViewに戻ります。
ステップ7:HandleradapterがModelAndViewをDispatcherServletに返す
ModelAndViewは、モデルとビューを含む、springmvcフレームワークの低レベルオブジェクトです。
ステップ8:DispatcherServletがビューリゾルバー(ビューリゾルバー)にビューの解決を要求する
論理ビュー名に基づいて実際のビュー(jsp)に解決する
ステップ9:ビューリゾルバーがビューをDispatcherServlet(ビュー)に返す
ステップ10:Viewレンダリング用のDispatcherServlet
ビューのレンダリングにより、(ModelAndViewオブジェクト内の)モデルデータがリクエストフィールドに入力されます。
ステップ11:DispatcherServletはユーザーに結果を返します
コンポーネントの説明
1.フロントエンドコントローラーDispatcherServlet(プログラマーの開発は不要)
機能:リピーター、中央処理装置と同等の要求、応答結果を受信します。DispatcherServletを使用すると、他のコンポーネント間の結合が減少します。
2. HandlerMapping(プログラマーの開発は必要ありません)
機能:要求されたURLに従ってハンドラーを検索する
3.ハンドルアダプター
役割:特定のルール(Handleradapterで必要なルール)に従ってハンドラーを実行する
4.プロセッサハンドラ(プログラマ開発が必要)
注:ハンドラーを作成するときは、アダプターがハンドラーを正しく実行できるように、Handleradapterの要件に従ってください。
5.リゾルバーを表示(プログラマーの開発は不要)
機能:ビュー解決を実行し、論理ビュー名に従って実際のビューに解決します
6.表示(プログラマがjspを開発する必要がある)
ビューはインターフェースであり、実装クラスはさまざまなビュータイプ(jsp、freemarker、pdfなど)をサポートします。
エントリーケース
インポートjar
XML構成コンポーネント
1、编写pojo:Items.java
public class Items {
private Integer id;
private String name;
private Float price;
private String pic;
private Date createtime;
private String detail;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic == null ? null : pic.trim();
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail == null ? null : detail.trim();
}
}
2.ビューの書き込み:itemsList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!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>
<form action="${pageContext.request.contextPath }/item/queryItem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询" /></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td>商品价格</td>
<td>生产日期</td>
<td>商品描述</td>
<td>操作</td>
</tr>
<c:forEach items="${itemsList }" var="item">
<tr>
<td>${item.name }</td>
<td>${item.price }</td>
<td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss" /></td>
<td>${item.detail }</td>
<td><a href="${pageContext.request.contextPath }/item/editItem.action?id=${item.id}">修改</a></td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
3、web.xml
<?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/web-app_2_5.xsd"
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">
<display-name>springmvc</display-name>
<!-- springmvc前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--
contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等)
如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml)
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--
第一种:*.action,访问以.action结尾,由DispatcherServlet进行解析
第二种:/,所以访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析,使用此种方式可以实现 RESTful风格的url
第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时,仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到handler,会报错。
-->
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
load-on-startup:サーブレットがサービスで開始することを示します。
url-pattern:* .actionの場合は、DispatcherServletに送信してください。
contextConfigLocation:springmvc構成のロード場所を指定します。指定しない場合、WEB-INF / [DispatcherServletのサーブレット名] -servlet.xmlがデフォルトでロードされます。
4、springmvc.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 配置Handler -->
<bean id="itemsController1" class="org.haiwen.controller.ItemsController1" name="/queryItems_test.action"/>
<!-- 配置另外一个Handler -->
<bean id="itemsController2" class="org.haiwen.controller.ItemsController2"/>
<!-- 非注解映射器一:将bean的name作为url进行查找,需要在配置Handler时指定beanname(就是url),所有的映射器都实现 HandlerMapping接口。-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!-- 非注解映射器二:简单url映射 -->
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<!-- 对itemsController1进行url映射,url是/queryItems1.action -->
<prop key="/queryItems1.action">itemsController1</prop>
<prop key="/queryItems2.action">itemsController2</prop>
</props>
</property>
</bean>
<!-- 所有处理器适配器都实现 HandlerAdapter接口 -->
<!-- 非注解适配器一:要求编写的Handler实现 Controller接口 -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!-- 非注解适配器二:要求编写的Handler实现 HttpRequestHandler接口 -->
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/>
<!-- 视图解析器:解析jsp解析,默认使用jstl标签,classpath下得有jstl的包-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置jsp路径的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 配置jsp路径的后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
5.コントローラーインターフェイスを実装するハンドラーを開発する
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.haiwen.pojo.Items;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class ItemsController1 implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
//调用service查找数据库,查询商品列表,这里使用静态数据模拟
List<Items> itemsList = new ArrayList<>();
//向list中填充静态数据
Items items_1 = new Items();
items_1.setName("联想笔记本");
items_1.setPrice(6000f);
items_1.setCreatetime(new Date());
items_1.setDetail("ThinkPad T430 联想笔记本电脑!");
Items items_2 = new Items();
items_2.setName("苹果手机");
items_2.setPrice(5000f);
items_2.setCreatetime(new Date());
items_2.setDetail("iphone6苹果手机!");
itemsList.add(items_1);
itemsList.add(items_2);
//返回ModelAndView
ModelAndView modelAndView = new ModelAndView();
//相当 于request的setAttribut,在jsp页面中通过itemsList取数据
modelAndView.addObject("itemsList", itemsList);
//指定视图
modelAndView.setViewName("items/itemsList");
return modelAndView;
}
}
6. HttpRequestHandlerインターフェイスを実装する別のハンドラーを開発する
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.haiwen.pojo.Items;
import org.springframework.web.HttpRequestHandler;
public class ItemsController2 implements HttpRequestHandler {
@Override
public void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//调用service查找 数据库,查询商品列表,这里使用静态数据模拟
List<Items> itemsList = new ArrayList<>();
//向list中填充静态数据
Items items_1 = new Items();
items_1.setName("联想笔记本");
items_1.setPrice(6000f);
items_1.setCreatetime(new Date());
items_1.setDetail("ThinkPad T430 联想笔记本电脑!");
Items items_2 = new Items();
items_2.setName("苹果手机");
items_2.setPrice(5000f);
items_2.setCreatetime(new Date());
items_2.setDetail("iphone6苹果手机!");
itemsList.add(items_1);
itemsList.add(items_2);
//设置模型数据
request.setAttribute("itemsList", itemsList);
//设置转发的视图
request.getRequestDispatcher("/WEB-INF/jsp/items/itemsList.jsp").forward(request, response);
//使用此方法可以通过修改response,设置响应的数据格式,比如响应json数据
//response.setCharacterEncoding("utf-8");
//response.setContentType("application/json;charset=utf-8");
//response.getWriter().write("json串");
}
}
注釈コンポーネントモード
1、springmvc.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 对于注解的Handler可以单个配置,实际开发中建议使用组件扫描-->
<!-- <bean class="org.haiwen.controller.ItemsController1" /> -->
<!--
可以扫描controller、service、...
这里让扫描controller,指定controller的包
-->
<context:component-scan base-package="org.haiwen.controller"></context:component-scan>
<!--注解映射器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
<!--注解适配器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
<!--
使用 mvc:annotation-driven代替上边注解映射器和注解适配器配置
mvc:annotation-driven默认加载很多的参数绑定方法,
比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
实际开发时使用mvc:annotation-driven
-->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 视图解析器:解析jsp解析,默认使用jstl标签,classpath下得有jstl的包-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置jsp路径的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 配置jsp路径的后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
注釈プロセッサマッパー
Spring 3.1以前では、org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMappingアノテーションマッパーが使用されていました。
spring3.1以降は、org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMappingアノテーションマッパーを使用します。
注釈プロセッサアダプタ
Spring 3.1以前は、注釈付きアダプターはorg.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapterで使用されていました。
spring3.1以降、org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapterを使用してアダプターに注釈を付けます。
2.ハンドラーを開発する
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.haiwen.pojo.Items;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
//使用Controller标识,它是一个控制器
@Controller
public class ItemsController3 {
//商品查询列表
//@RequestMapping实现 对queryItems方法和url进行映射,一个方法对应一个url
//一般建议将url和方法写成一样
@RequestMapping("/queryItems")
public ModelAndView queryItems() throws Exception {
//调用service查找 数据库,查询商品列表,这里使用静态数据模拟
List<Items> itemsList = new ArrayList<>();
//向list中填充静态数据
Items items_1 = new Items();
items_1.setName("联想笔记本");
items_1.setPrice(6000f);
items_1.setCreatetime(new Date());
items_1.setDetail("ThinkPad T430 联想笔记本电脑!");
Items items_2 = new Items();
items_2.setName("苹果手机");
items_2.setPrice(5000f);
items_2.setCreatetime(new Date());
items_2.setDetail("iphone6苹果手机!");
itemsList.add(items_1);
itemsList.add(items_2);
//返回ModelAndView
ModelAndView modelAndView = new ModelAndView();
//相当 于request的setAttribut,在jsp页面中通过itemsList取数据
modelAndView.addObject("itemsList", itemsList);
//指定视图
modelAndView.setViewName("items/itemsList");
return modelAndView;
}
}