SpringMVC简介
SpringMVC 是一套功能强大,性能强悍,使用方便的优秀的 MVC 框架
SpringMVC 版 HelloWorld实现
项目结构
web.xml
配置分发servlet、spring-mvc配置文件
<?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"
id="WebApp_ID" version="2.5">
<display-name>SpringMvc01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springmvc</servlet-name>
<!-- DispatcherServlet是Spring核心的Servlet类、处理所有请求并分发 -->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value><!-- spring-mvc.xml用来定义一些视图解析 -->
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern><!-- 拦截所有以 .do 结尾的东西 -->
</servlet-mapping>
</web-app>
spring-mvc.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 使用注解的包,包括子集 -->
<context:component-scan base-package="com.java1234"/>
<!-- 视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
HelloWorldController
写上注解“@Controller”、配置请求
package com.java1234.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;//给视图定义的Model,可以放数据让视图取到、
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorldController {
//RequestMapping设置请求路径
@RequestMapping("/helloWorld")
public String helloWorld(Model model){
model.addAttribute("message", "StringMvc大爷你好!");//添加的数据是键值对的形式
return "helloWorld"; //交给spring-mvc.xml中的视图解析器,去请求helloWorld.jsp
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="helloWorld.do">问候SpringMvc他大爷</a>
</body>
</html>
helloWorld.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}
</body>
</html>