SpringMVC入門教程及其原理講解和實例代碼下載

原文:SpringMVC入門教程及其原理講解和實例代碼下載

源代碼下載地址:http://www.zuidaima.com/share/1751859714182144.htm


SpringMVC框架介紹

Spring框架提供了構造Web應用程序的全能MVC模塊。Spring MVC分離了控制器、模型對象、分派器以及處理程序對象的角色,這種分離讓它們更容易進行制定。是一個標準的MVC框架。

SpringMVC框架圖

 

                   

那你猜一猜哪一部分應該是哪一部分?

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

package com.pb.entity;

public class Account {
	private String cardNo;
	private String password;
	private float balance;
	public String getCardNo() {
		return cardNo;
	}
	public void setCardNo(String cardNo) {
		this.cardNo = cardNo;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public float getBalance() {
		return balance;
	}
	public void setBalance(float balance) {
		this.balance = balance;
	}
	
}

LoginController類:

package com.pb.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.pb.entity.Account;

public class LoginController extends AbstractController {
	private String successView;
	private String failView;//這兩個參數是返回值傳給applicationContext.xml,進行頁面分配
	
	public String getSuccessView() {
		return successView;
	}
	public void setSuccessView(String successView) {
		this.successView = successView;
	}
	public String getFailView() {
		return failView;
	}
	public void setFailView(String failView) {
		this.failView = failView;
	}
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		String cardNo=request.getParameter("cardNo");
		String password=request.getParameter("password");
		Account account =getAccount(cardNo,password);
		Map<String ,Object> model=new HashMap<String,Object>();
		if(account !=null){
			model.put("account", account);
			return new ModelAndView(getSuccessView(),model);
		}else{
			model.put("error", "卡號和密碼不正確");
			return new ModelAndView(getFailView(),model);
		}		
	}//本應該這個方法寫在模型層,這地方直接給放在了邏輯層這個地方偷懶了。
	public Account getAccount(String cardNo,String password){
		if(cardNo.equals("123")&&password.equals("123")){
			Account account =new Account();
			account.setCardNo(cardNo);
			account.setBalance(88.8f);
			return account;
		}else{
			return null;
		}
	}

}

applicationContext.xml

<?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: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-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
	<bean id="loginController" class="com.pb.web.controller.LoginController">
		<property name="successView" value="showAccount"></property>
		<property name="failView" value="login"></property>
	</bean>
	<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<props>
				<prop key="/login.do">loginController</prop>
			</props>
		</property>
	</bean>
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>

Jsp頁面:

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!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=GB18030">
<title>Insert title here</title>
</head>
<body>
	<a href="login.jsp">進入</a>

</body>
</html>

login.jsp

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!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=GB18030">
<title>Insert title here</title>
</head>
<body>
${error }
	<form action="login.do" method="post">
		賬號登陸<br>
		<hr>		
		卡號:<input type="text" name="cardNo"><br>
		密碼:<input type="text" name="password"><br>
		<input type="submit" value="登陸">
	</form>

</body>
</html>

showAccount.jsp

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!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=GB18030">
<title>Insert title here</title>
</head>
<body>
	賬戶信息<br>
	卡號:${account.cardNo }<br>
	密碼:${account.password }<br>
	錢數:${account.balance }<br>
</body>
</html>

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/j2ee" 
			xmlns:javaee="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/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  	<servlet-name>Dispatcher</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:applicationContext.xml</param-value>
  	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>Dispatcher</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>  
</web-app>

工程原碼:原碼

SpringMVC總結

    以上就是我理解的Spring MVC可能不夠深刻。其實對於任何的框架來說,一個框架是一個可複用設計,框架的最大的好處就是複用。每個框架都有存在的理由,那Spring MVC的理由是什麼呢?

    只有各個框架之間彼此瞭解他們之間的優缺點,使用場合,使用原理,才能讓我們的更快的成長。

發佈了183 篇原創文章 · 獲贊 19 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章