1.SpringMVC是一个基于DispatcherServlet的MVC框架,每一个请求最先访问的都DispatcherServlet
DispatcherServlet负责转发每一个Request请求给相应的Handler,Handler处理以后再返回相应的视图(View)和模型(Model),返回的视图和模型都可以不指定,即可以只返回Model或只返回View或都不返回。
DispatcherServlet是继承自HttpServlet的,既然SpringMVC是基于DispatcherServlet的,那么我们先来配置一下DispatcherServlet,好让它能够管理我.
以下为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_3_0.xsd" id="WebApp_ID" version="3.0">
<servlet-mapping>
</servlet-mapping>
</web-app>
以下为dispatcherServlet-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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
<!-- 自动扫描的包名 -->
<context:component-scan base-package="com.Ace.controller"></context:component-scan>
<!-- 启用springmvc注解 -->
<context:annotation-config />
<!-- 默认的注解映射的支持 -->
<mvc:annotation-driven />
<!-- 视图解释类 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewReso
lver">
<property name="prefix" value="/WEB-INF/Views/" />
<!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 -->
<!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
<property name="suffix" value=".jsp" />
</bean>
<!-- 处理器 -->
</beans>
以下为Controller层:
package com.Ace.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class Test1Controller {
@RequestMapping(value="page/{name}/{age}",method=RequestMethod.GET)
public String getName(ModelMap map,@PathVariable("name")String name,@PathVariable("age") int age){
map.addAttribute("name", name);
map.addAttribute("age", age);
return "name";
}
}
View层:(
WEB-INF/Views/name.jsp下)
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
</html>