SpringMVC的HelloWorld實現

1.首先我們需要新建一個webapp項目,在pom.xml中引入相關依賴:

		<!-- junit測試包 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

		<!-- spring基礎包 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.1.6.RELEASE</version>
		</dependency>

		<!-- springMVC的包 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.1.6.RELEASE</version>
		</dependency>

2.在web.xml中配置DispatcherServlet:

	<!-- 配置springmvc的DispatcherServlet處理類 -->
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- 配置springmvc的DispatcherServlet映射處理URL -->
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

3.引入springmvc.xml文件,文件名字隨意,但是要與上面web.xml中配置的classpath名字相同

<?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: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-3.0.xsd   
           http://www.springframework.org/schema/context   
           http://www.springframework.org/schema/context/spring-context-3.0.xsd  
           http://www.springframework.org/schema/mvc   
           http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<!-- 自己掃描bean -->
	<context:component-scan base-package="com.yc" />

	<!-- jsp頁面解析器,當Controller返回XXX字符串時,先通過攔截器,然後該類就會在/views/目錄下,查找XXX.jsp文件 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/views/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>


4.發出請求

<a href="mvc/hello">Hello</a>

5.編寫請求處理類Controller

package com.yc.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller //標識爲請求處理類
@RequestMapping("/mvc") //攔截/mvc的請求
public class HelloController {
	
	@RequestMapping("/hello") //攔截/hello的請求
	public String hello(){
		return "show"; //跳轉到show.jsp頁面
	}
}
 

6.運行結果



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