1. 程式人生 > >spring web mvc 的一個簡單例項

spring web mvc 的一個簡單例項

1.準備開發環境和執行環境

開發工具:eclipse-jee-neon-2-win32-x86_64

執行環境:apache-tomcat-8.0.33

專案工程環境:Maven Project

spring框架及依賴jar包:通過pom.xml配置

在eclipse中建立一個Maven project,並配置環境,圖示如下:


(圖一)


(圖二)


(圖三)


(圖四)


(圖五),圖一至圖五,建立maven專案。


(圖六)


(圖七),圖六至圖七,新增web.xml檔案,解決異常資訊。

在eclipse中新增maven支援,圖示如下:


(圖八)


(圖九)


(圖十)


(圖十一)


(圖十二)


(圖十三)


(圖十四),圖八至圖十四,新增maven,設定本地倉庫和url連結地址。

在settings.xml中的配置:

  <!--配置maven本地倉庫-->
  <localRepository>D:\repo2</localRepository>

  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
    
    <!--使用阿里雲
	  <mirror>
        <id>nexus-aliyun</id>
        <mirrorOf>*</mirrorOf>
        <name>Nexus aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
    </mirror> 
    -->
		
    <!--使用本地私服-->
    <mirror>
        <id>nexus-aliyun</id>
        <mirrorOf>*</mirrorOf>
        <name>Nexus aliyun</name>
        <url>http://10.10.24.210:9988/nexus/content/groups/public/</url>
    </mirror> 
	
  </mirrors>


在pom.xml中配置好要新增的環境,如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>cn.icloudit</groupId>
	<artifactId>maventest1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina -->
		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-catalina</artifactId>
			<version>8.0.33</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/jstl/jstl -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>
</project>

耐心等待配置載入完成,完成後會配置好這些jar檔案到專案環境中,如下:


(圖十五)

建立jsp頁面,新增tomcat執行環境,並執行如下:


(圖十六)

執行結果成功,可見tomcat是可以使用的。如(圖十七):


2.前端控制器的配置,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"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<display-name>maventest1</display-name>
	<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>

	<!-- 前端控制器的配置 -->
	<servlet>
		<!--自此請求已交給 Spring Web MVC 框架處理,因此我們需要配置 Spring 的配置檔案, 預設 DispatcherServlet 
			會載入 WEB-INF/[DispatcherServlet 的 Servlet 名 字 ]-servlet.xml 配 置 文 件 。 本 示 
			例 為 WEB-INF/springmvc-servlet.xml。 -->
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- load-on-startup:表示啟動容器時初始化該 Servlet -->
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<!-- url-pattern:表示哪些請求交給 Spring Web MVC 處理 -->
		<!-- “/” 是用來定義預設 servlet 對映的 -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

3.在spring配置檔案中配置HandlerMappingHandlerAdapter、ViewResolver。

springmvc-servlet.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:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
	">

	<!-- 在 Spring 配置檔案中配置 HandlerMapping、HandlerAdapter -->
	<!--BeanNameUrlHandlerMapping:表示將請求的 URL 和 Bean 名字對映,
		如 URL 為 “上下文/hello” ,則 Spring 配置檔案必須有一個名字為“/hello”的 Bean,上下文預設忽略
	 -->
	<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
	<!--SimpleControllerHandlerAdapter:表示所有實現了 org.springframework.web.servlet.mvc.Controller 介面的 Bean 
		可以作為Spring Web MVC 中的處理器。如果需要其他型別的處理器可以通過實現 HadlerAdapter 來解決 
	-->
	<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
	<!-- 處理器 -->
	<!--name="/component":前邊配置的 BeanNameUrlHandlerMapping,
		表示如過請求的 URL 為 “上下文/component”,則將會交給該 Bean 進行處理。 
	-->
	<bean name="/component" class="cn.icloudit.computer.web.action.ComponentAction"></bean>

	<!-- 在 Spring 配置檔案中配置 ViewResolver -->
	<!-- InternalResourceViewResolver:用於支援 Servlet、JSP 檢視解析 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- viewClass:JstlView 表示 JSP 模板頁面需要使用 JSTL 標籤庫,classpath 中必須包含 jstl 的相關 jar 包 -->
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		<!--prefix 和 suffix:查詢檢視頁面的字首和字尾(字首[邏輯檢視名]字尾) ,
			比如傳進來的邏輯檢視名為 hello,則該該jsp 檢視頁面應該存放在“WEB-INF/content/success.jsp”  
		-->
		<property name="prefix" value="/WEB-INF/content/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>
4.開發處理器/頁面控制器
Component.java
package cn.icloudit.computer.web.action;

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

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

/**
 * 開發處理器/頁面控制器
 * org.springframework.web.servlet.mvc.Controller:頁面控制器/處理器必須實現 Controller 介面,注意別選錯了
 * @author Administrator
 *
 */
public class ComponentAction implements Controller{

	/**
	 *public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) :
	 *功能處理方法,實現相應的功能處理,比如收集引數、驗證引數、繫結引數到命令物件、將命令物件傳入業務物件進行業務處理、最後返回 ModelAndView 物件.
	 *
	 *ModelAndView:包含了檢視要實現的模型資料和邏輯檢視名;
	 *“mv.addObject("message", "Hello World!");”表示新增模型資料,此處可以是任意 POJO 物件;
	 *“mv.setViewName("hello");”表示設定邏輯檢視名為“hello”,檢視解析器會將其解析為具體的檢視,
	 *如前邊的檢視解析器 InternalResourceVi。wResolver 會將其解析為“WEB-INF/jsp/hello.jsp”
	 */
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//1、收集引數、驗證引數
		//2、繫結引數到命令物件
		//3、將命令物件傳入業務物件進行業務處理
		//4、選擇下一個頁面
		String msg = "HELLO SPRINGMVC!";
		ModelAndView mv = new ModelAndView();
		//新增模型資料 可以是任意的POJO物件
		mv.addObject("message",msg);
		//設定邏輯檢視名,檢視解析器會根據該名字解析到具體的檢視頁面
		mv.setViewName("success");
		return mv;
	}
	
}
5.開發檢視頁面 建立/WEB-INF/content/success.jsp檢視頁面
<%@ 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>Insert title here</title>
</head>
<body>
	獲取返回結果:${message}<br>
</body>
</html>

6.啟動伺服器,執行測試
執行步驟:
1、 首先使用者傳送請求 http://localhost:8080/maventest1/component——>web 容器,web 容器根據“/component”路徑對映到
DispatcherServlet(url-pattern 為/)進行處理;
2、 DispatcherServlet——>BeanNameUrlHandlerMapping 進行請求到處理的對映,BeanNameUrlHandlerMapping 將
“/component”路徑直接對映到名字為“/component”的 Bean 進行處理,即 HelloWorldController,BeanNameUrlHandlerMapping
將其包裝為 HandlerExecutionChain(只包括 ComponemtAction 處理器,沒有攔截器) ;
3、 DispatcherServlet——> SimpleControllerHandlerAdapter,SimpleControllerHandlerAdapter 將 HandlerExecutionChain
中的處理器(ComponemtAction)適配為 SimpleControllerHandlerAdapter;
4、 SimpleControllerHandlerAdapter — — > ComponentAction 處 理 器 功 能 處 理 方 法 的 調 用 ,
SimpleControllerHandlerAdapter 將會呼叫處理器的 handleRequest 方法進行功能處理,該處理方法返回一
個 ModelAndView 給 DispatcherServlet;
5、 success(ModelAndView 的邏輯檢視名)——>InternalResourceViewResolver, InternalResourceViewResolver使用
JstlView,具體檢視頁面在/WEB-INF/content/success.jsp;
6、 JstlView(/WEB-INF/conent/success.jsp)——>渲染,將在處理器傳入的模型資料(message=HelloWorld!)在檢視中展示出
來;
7、 返回控制權給 DispatcherServlet,由 DispatcherServlet 返回響應給使用者,到此一個流程結束。
到此 HelloWorld 就完成了,步驟是不是有點多?而且回憶下我們主要進行了如下配置:
1、 前端控制器 DispatcherServlet;
2、 HandlerMapping
3、 HandlerAdapter
4、 ViewResolver
5、 處理器/頁面控制器
6、 檢視




相關推薦

spring web mvc一個簡單例項

1.準備開發環境和執行環境 開發工具:eclipse-jee-neon-2-win32-x86_64 執行環境:apache-tomcat-8.0.33 專案工程環境:Maven Project spring框架及依賴jar包:通過pom.xml配置 在eclipse中建立

Spring Boot學習筆記之使用Spring Boot建立一個簡單web專案(工具使用IntelliJ IDEA)

新建Maven專案 1.File --> New Project --> Maven --> Next 2.填寫專案資訊,完成之後點選Next,然後點選Finish 3.專案建好之後如下圖所示 修改pom檔案中的配置資訊 <?xml version

spring一個簡單例項之對DAO的支援

spring 對 DAO 的支援~~ 1、在 MySQL 中建立 db_spring 資料庫,新建 t_student 表 DROP TABLE IF EXISTS `t_student`; C

spring web mvc第一天

第一個 solver 運行 tco 調用 角色 servlet ret ack spring web mvc 感覺就是高大上啊!啥都是配置文件就能夠了。所以第一步就是弄清楚配置文件使用和總體框架的流程! Spring web mvc最重要的當

springboot 之Spring Web Mvc Framework

fig ftl pathvaria nts bean ddr got del view 1、SpringMvc自動配置 Spring Boot 為SpringMvc提供了自動配置。 自動配置包含Spring的以下特征: (1)視圖解析器ContentNegotiatingV

阿裏微服務專家手寫Spring Boot 實現一個簡單的自動配置模塊

微服務 簡單的 AR AI tps ble 免費 VM 知識體系 為了更好的理解 Spring Boot 的 自動配置和工作原理,我們自己來實現一個簡單的自動配置模塊。 假設,現在項目需要一個功能,需要自動記錄項目發布者的相關信息,我們如何通過 Spring Boot 的

關於Java中timer的一個簡單例項應用

效果展示 核心程式碼: Timer timer = new Timer();//新增定時器 timer.schedule( new TimerTask(){//重寫定時任務 public void run(){ button2.setText("取消"+S

Spring Web MVC 核心元件第二種方法(用註解的方法)

Spring Web MVC 核心元件 Spring Web MVC提供了M、V和C相關的主要實現元件,具體如下: DispatcherServlet(控制器,請求入口) HandlerMapping(控制器,請求派發) Controller(控制器,請求處理流程) ModelA

Spring Web MVC 核心元件第一種方法

Spring Web MVC 核心元件 Spring Web MVC提供了M、V和C相關的主要實現元件,具體如下: DispatcherServlet(控制器,請求入口) HandlerMapping(控制器,請求派發) Controller(控制器,請求處理流程) ModelA

Web API入門 簡單例項

地址:https://blog.csdn.net/zhoukun1008/article/details/52702007。 WebApi怎麼用? 1、 開啟VS2012,新建------>專案     選擇Visual C#   Web 下面的 Visua

GUI使用者介面的一個簡單例項

這篇部落格寫得比較趕,就不贅述了。 內含有設定框架,面板,按鈕怎麼嵌在一起,插入圖片,設定字型和顏色,前景色背景色,位置等。重點在實現功能,介面並不美觀。 私以為,這麼多個東西怎麼看呢?就應該把一些行註釋掉就知道怎麼看了。 image是在src下面的資料夾 package gui; im

繼承與多型的一個簡單例項

程式結構: 父為Person類,Person類個子類Student和Employee,Employee類又有兩個子類,Staff和Faculty。 繼承即子類可以繼承父類的資料域和方法: Student類和Employee類繼承了Person類的資料域name,address pho

spring-cloud 的一個簡單腳手架

easy-cloud 關於 spring-cloud 的一個簡單腳手架 easy-cloud 緣起 版本 和 要求 已實現 TODO 專案地址 緣起

Ajax實現區域性資料互動的一個簡單例項

  想要實現的功能:利用Ajax技術通過點選一個<button>按鈕,然後在指定的文字框中輸出想要的值。 1、使用Jsp建立一個前端頁面。 1 <body> 2 <div style="text-align: center;"> 3 <

Spring AOP簡介及簡單例項

一、SpringAOP 簡介 1.AOP思想: AOP即面向切面程式設計,可以說是OOP的補充和完善。它利用一種稱為"橫切"的技術,剖解開封裝的物件內部,並將那些影響了多個類的公共行為封裝到一個可重用模組,並將其命名為"Aspect",即切面。       &n

Spring系列(六) Spring Web MVC 應用構建分析

DispatcherServlet DispatcherServlet 是Spring MVC的前端控制器名稱, 使用者的請求到達這裡進行集中處理, 在Spring MVC中, 它的作用是為不同請求匹配對應的處理器, 將結果傳遞給檢視解析器最終呈現給客戶端. 前端控制器模式(Front Controller

22 Web MVC framework( 1.1 Spring Web MVC的特徵)

清楚的規則劃分。每一個規則(Role)-控制器,校驗器,命令物件,表單物件,Model物件,DispatcherServlet,繫結對映,檢視解析器等等,都能被專門的物件執行。 強力的並且明確的可配置性。和javabean一樣,框架和應用類的雙方的可配置性。這個可配置性包括了超越內容的簡單對映,就像從web

Spring Web MVC 深入研究

Spring Web MVC如何真正起作用 介紹 這是對Spring Web MVC的強大功能和內部工作的深入研究,它是Spring Framework的一部分。 專案設定 在本文中,我們將使用最新和最好的Spring Framework 5.我們將重點放

Spring Boot整合Thymeleaf簡單例項

1、定義 Thymeleaf是一種用於Web和獨立環境的現代伺服器端的Java模板引擎。 2、簡單例項 (1)目錄結構 (2)MySpringBootApplication.java pa

SQL注入的一個簡單例項

<p>很多Web應用程式都使用資料庫來儲存資訊。SQL命令就是前端Web和後端資料庫之間的介面,使得資料可以傳遞至Web應用程式。很多Web站點都會利用使用者輸入的引數動態地生成SQL查詢要求,攻擊者通過在URL、表單域,或者其他的輸入域中輸入自己的