---
title: "轻松上手SpringMVC"
author: "com_xpp"
date: "2012-07-23T13:18:37Z"
tags: []
categories: ["编程语言"]
slug: "springmvc"
draft: false
lastmod: "2012-07-23T13:18:37Z"
id: 1604183
url: "https://com-xpp.iteye.com/blog/1604183"
---

# SpringMVC框架介绍

 

> Spring框架提供了构造Web应用程序的全能MVC模块。Spring MVC分离了控制器、模型对象、分派器以及处理程序对象的角色，这种分离让它们更容易进行制定。是一个标准的MVC框架。
> 
>  
> 
> 那你猜一猜哪一部分应该是哪一部分？

# SpringMVC框架图

![](http://my.csdn.net/uploads/201207/22/1342928077_2436.jpg)

# SpringMVC接口解释

> DispatcherServlet接口：
> 
> > Spring提供的前端控制器，所有的请求都有经过它来统一分发。在DispatcherServlet将请求分发给Spring Controller之前，需要借助于Spring提供的HandlerMapping定位到具体的Controller。
> 
>  
> 
> HandlerMapping接口：
> 
> > 能够完成客户请求到Controller映射。
> 
>  
> 
> Controller接口：
> 
> > 需要为并发用户处理上述请求，因此实现Controller接口时，必须保证线程安全并且可重用。Controller将处理用户请求，这和Struts Action扮演的角色是一致的。一旦Controller处理完用户请求，则返回ModelAndView对象给DispatcherServlet前端控制器，ModelAndView中包含了模型（Model）和视图（View）。从宏观角度考虑，DispatcherServlet是整个Web应用的控制器；从微观考虑，Controller是单个Http请求处理过程中的控制器，而ModelAndView是Http请求过程中返回的模型（Model）和视图（View）。
> 
>  
> 
> ViewResolver接口：
> 
> > Spring提供的视图解析器（ViewResolver）在Web应用中查找View对象，从而将相应结果渲染给客户。

 

# SpringMVC运行原理

> 1.客户端请求提交到DispatcherServlet
> 
> 2.由DispatcherServlet控制器查询一个或多个HandlerMapping，找到处理请求的Controller
> 
> 3.DispatcherServlet将请求提交到Controller
> 
> 4.Controller调用业务逻辑处理后，返回ModelAndView
> 
> 5.DispatcherServlet查询一个或多个ViewResoler视图解析器，找到ModelAndView指定的视图
> 
> 6.视图负责将结果显示到客户端

# SpringMVC运行实例

Account类：

 

Java代码 

01. package com.pb.entity;
02. public class Account {
03. private String cardNo;
04. private String password;
05. private float balance;
06. public String getCardNo() {
07. return cardNo;
08. }
09. public void setCardNo(String cardNo) {
10. this.cardNo = cardNo;
11. }
12. public String getPassword() {
13. return password;
14. }
15. public void setPassword(String password) {
16. this.password = password;
17. }
18. public float getBalance() {
19. return balance;
20. }
21. public void setBalance(float balance) {
22. this.balance = balance;
23. }
24. }

 

LoginController类：

 

Java代码 

01. package com.pb.web.controller;
02. import java.util.HashMap;
03. import java.util.Map;
04. import javax.servlet.http.HttpServletRequest;
05. import javax.servlet.http.HttpServletResponse;
06. import org.springframework.web.servlet.ModelAndView;
07. import org.springframework.web.servlet.mvc.AbstractController;
08. import com.pb.entity.Account;
09. public class LoginController extends AbstractController {
10. private String successView;
11. private String failView;//这两个参数是返回值传给applicationContext.xml，进行页面分配
12. public String getSuccessView() {
13. return successView;
14. }
15. public void setSuccessView(String successView) {
16. this.successView = successView;
17. }
18. public String getFailView() {
19. return failView;
20. }
21. public void setFailView(String failView) {
22. this.failView = failView;
23. }
24. @Override
25. protected ModelAndView handleRequestInternal(HttpServletRequest request,
26. HttpServletResponse response) throws Exception {
27. // TODO Auto-generated method stub
28. String cardNo=request.getParameter("cardNo");
29. String password=request.getParameter("password");
30. Account account =getAccount(cardNo,password);
31. Map&lt;String ,Object&gt; model=new HashMap&lt;String,Object&gt;();
32. if(account !=null){
33. model.put("account", account);
34. return new ModelAndView(getSuccessView(),model);
35. }else{
36. model.put("error", "卡号和密码不正确");
37. return new ModelAndView(getFailView(),model);
38. }
39. }//本应该这个方法写在模型层，这地方直接给放在了逻辑层这个地方偷懒了。
40. public Account getAccount(String cardNo,String password){
41. if(cardNo.equals("123")&&password.equals("123")){
42. Account account =new Account();
43. account.setCardNo(cardNo);
44. account.setBalance(88.8f);
45. return account;
46. }else{
47. return null;
48. }
49. }
50. }

applicationContext.xml

 

 

Html代码 

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;beans xmlns="http://www.springframework.org/schema/beans"
03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04. xmlns:aop="http://www.springframework.org/schema/aop"
05. xmlns:tx="http://www.springframework.org/schema/tx"
06. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
07. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
08. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"&gt;
09. &lt;bean id="loginController" class="com.pb.web.controller.LoginController"&gt;
10. &lt;property name="successView" value="showAccount"&gt;&lt;/property&gt;
11. &lt;property name="failView" value="login"&gt;&lt;/property&gt;
12. &lt;/bean&gt;
13. &lt;bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"&gt;
14. &lt;property name="mappings"&gt;
15. &lt;props&gt;
16. &lt;prop key="/login.do"&gt;loginController&lt;/prop&gt;
17. &lt;/props&gt;
18. &lt;/property&gt;
19. &lt;/bean&gt;
20. &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt;
21. &lt;property name="prefix" value="/"&gt;&lt;/property&gt;
22. &lt;property name="suffix" value=".jsp"&gt;&lt;/property&gt;
23. &lt;/bean&gt;
24. &lt;/beans&gt;

Jsp页面：

 

Html代码 

01. &lt;%@ page language="java" contentType="text/html; charset=GB18030"
02. pageEncoding="GB18030"%&gt;
03. &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
04. &lt;html&gt;
05. &lt;head&gt;
06. &lt;meta http-equiv="Content-Type" content="text/html; charset=GB18030"&gt;
07. &lt;title&gt;Insert title here&lt;/title&gt;
08. &lt;/head&gt;
09. &lt;body&gt;
10. &lt;a href="login.jsp"&gt;进入&lt;/a&gt;
11. &lt;/body&gt;
12. &lt;/html&gt;

login.jsp

 

 

Html代码 

01. &lt;%@ page language="java" contentType="text/html; charset=GB18030"
02. pageEncoding="GB18030"%&gt;
03. &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
04. &lt;html&gt;
05. &lt;head&gt;
06. &lt;meta http-equiv="Content-Type" content="text/html; charset=GB18030"&gt;
07. &lt;title&gt;Insert title here&lt;/title&gt;
08. &lt;/head&gt;
09. &lt;body&gt;
10. ${error }
11. &lt;form action="login.do" method="post"&gt;
12. 账号登陆&lt;br&gt;
13. &lt;hr&gt;
14. 卡号：&lt;input type="text" name="cardNo"&gt;&lt;br&gt;
15. 密码：&lt;input type="text" name="password"&gt;&lt;br&gt;
16. &lt;input type="submit" value="登陆"&gt;
17. &lt;/form&gt;
18. &lt;/body&gt;
19. &lt;/html&gt;

showAccount.jsp

 

 

Html代码 

01. &lt;%@ page language="java" contentType="text/html; charset=GB18030"
02. pageEncoding="GB18030"%&gt;
03. &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
04. &lt;html&gt;
05. &lt;head&gt;
06. &lt;meta http-equiv="Content-Type" content="text/html; charset=GB18030"&gt;
07. &lt;title&gt;Insert title here&lt;/title&gt;
08. &lt;/head&gt;
09. &lt;body&gt;
10. 账户信息&lt;br&gt;
11. 卡号：${account.cardNo }&lt;br&gt;
12. 密码：${account.password }&lt;br&gt;
13. 钱数：${account.balance }&lt;br&gt;
14. &lt;/body&gt;
15. &lt;/html&gt;

Web.xml

Html代码 

01. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
02. &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
03. xmlns="http://java.sun.com/xml/ns/j2ee"
04. xmlns:javaee="http://java.sun.com/xml/ns/javaee"
05. xmlns:web="http://java.sun.com/xml/ns/javaee/web-app\_2\_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app\_2\_4.xsd" version="2.4"&gt;
06. &lt;welcome-file-list&gt;
07. &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
08. &lt;/welcome-file-list&gt;
09. &lt;servlet&gt;
10. &lt;servlet-name&gt;Dispatcher&lt;/servlet-name&gt;
11. &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
12. &lt;init-param&gt;
13. &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
14. &lt;param-value&gt;classpath:applicationContext.xml&lt;/param-value&gt;
15. &lt;/init-param&gt;
16. &lt;/servlet&gt;
17. &lt;servlet-mapping&gt;
18. &lt;servlet-name&gt;Dispatcher&lt;/servlet-name&gt;
19. &lt;url-pattern&gt;\*.do&lt;/url-pattern&gt;
20. &lt;/servlet-mapping&gt;
21. &lt;/web-app&gt;

#### 工程原码：[原码](http://download.csdn.net/detail/qiulongtianshi/4444497)

# SpringMVC总结

> 以上就是我理解的Spring MVC可能不够深刻。其实对于任何的框架来说，一个框架是一个可复用设计，框架的最大的好处就是复用。每个框架都有存在的理由，那Spring MVC的理由是什么呢？
> 
> 那么就请看一下这篇文章[Struts和SpringMVC两种MVC框架比较](http://zhaohe162.blog.163.com/blog/static/38216797201123105448118/)，这篇文章总结的我个人认为总结的挺好。
> 
> 只有各个框架之间彼此了解他们之间的优缺点，使用场合，使用原理，才能让我们的更快的成长。

### 想要了解更多Spring请从（[Spring程序员的春天](http://blog.csdn.net/qiulongtianshi/article/details/7741331)）开始