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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章