Previous:SpringMVC_1 Next:SpringMVC_3_实操Binding
************************************************************
Spring MVC起步 http://www.imooc.com/learn/47
spring 3.0 应用springmvc 构造RESTful URL 详细讲解 (转载)http://www.cnblogs.com/zzjjian333/archive/2012/11/14/rest1.html
---4-1 配置文件-------------------------------------------
web.xml
2.4版本以上WEBAPP才默认支持EL表达式
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Study</display-name>
<!-- Spring应用上下文, 理解层次化的ApplicationContext -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/configs/spring/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- DispatcherServlet, Spring MVC的核心 可以有多个DispatcherServlet,来相应不同的请求-->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- DispatcherServlet对应的上下文配置, 默认为/WEB-INF/$servlet-name$-servlet.xml
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/configs/spring/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<!-- mvc-dispatcher拦截所有的请求-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
*****************************
mvc-dispatcher-servlet.xml:
DispatcherServlet, Spring MVC的核心 可以有多个DispatcherServlet,来相应不同的请求
<?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/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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 本配置文件是工名为mvc-dispatcher的DispatcherServlet使用, 提供其相关的Spring MVC配置 --> <!-- 启用Spring基于annotation的DI, 使用户可以在Spring MVC中使用Spring的强大功能。 激活 @Required @Autowired,JSR 250's @PostConstruct, @PreDestroy and @Resource 等标注 --> <context:annotation-config /> <!-- DispatcherServlet上下文, 只管理@Controller类型的bean, 忽略其他型的bean, 如@Service --> <context:component-scan base-package="com.imooc.mvcdemo"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- HandlerMapping, 无需配置, Spring MVC可以默认启动。 DefaultAnnotationHandlerMapping annotation-driven HandlerMapping --> <!-- 扩充了注解驱动,可以将请求参数绑定到控制器参数 --> <mvc:annotation-driven /> <!-- 静态资源处理, css, js, imgs --> <mvc:resources mapping="/resources/**" location="/resources/" /> <!-- 配置ViewResolver。 可以用多个ViewResolver。 使用order属性排序。 InternalResourceViewResolver放在最后。 --> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="order" value="1" /> <property name="mediaTypes"> <map> <entry key="json" value="application/json" /> <entry key="xml" value="application/xml" /> <entry key="htm" value="text/html" /> </map> </property> <property name="defaultViews"> <list> <!-- JSON View --> <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"> </bean> </list> </property> <property name="ignoreAcceptHeader" value="true" /> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsps/" /> <property name="suffix" value=".jsp" /> </bean> <!--200*1024*1024即200M resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="209715200" /> <property name="defaultEncoding" value="UTF-8" /> <property name="resolveLazily" value="true" /> </bean> </beans>
applicationContext:
Spring应用上下文
<?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/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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:annotation-config /> <context:component-scan base-package="com.imooc.mvcdemo"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> </beans>
------------------------------------------------------------
JSP:
1. JSTL
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>)
2.EL表达式
<div class="course-title">${course.title}</div>
*JSTL和EL表达式完成了对象的输出
3.CSS静态文件 (与配置文件中的静态资源处理相对应)
<link rel="stylesheet"
href="<%=request.getContextPath()%>/resources/css/main.css"
type="text/css" />
<%@ page language="java"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>我不是真正的慕课网</title>
<link rel="stylesheet"
href="<%=request.getContextPath()%>/resources/css/main.css"
type="text/css" />
</head>
<body>
<div id="main">
<div class="newcontainer" id="course_intro">
<div class="course-title">${course.title}</div>
<div class="course_info">
<div class="course-embed l">
<div id="js-course-img" class="img-wrap">
<img width="600" height="340" alt=""
src="<%=request.getContextPath()%>/${course.imgPath}"
class="course_video" />
</div>
<div id="js-video-wrap" class="video" style="display: none">
<div class="video_box" id="js-video"></div>
</div>
</div>
<div class="course_state">
<ul>
<li><span>学习人数</span> <em>${course.learningNum }</em></li>
<li class="course_hour"><span>课程时长</span> <em
class="ft-adjust"><span>${course.duration }</span>秒</em></li>
<li><span>课程难度</span> <em>${course.levelDesc }</em></li>
</ul>
</div>
<!--
<div class="course_intro">
<div class="concerned_course add_concerned_course">
<a href="javascript:void(0)" data-id="202"
class="btn-add-follow js-btn-follow"> <i></i> <em
class="concerned-icon">关注此课程</em>
</a>
</div>
<div class="curse_btn">
<a href="#">开始学习</a>
</div>
</div>
-->
</div>
<div class="course_list">
<div class="outline">
<h3 class="chapter_introduces">课程介绍</h3>
<div class="course_shortdecription">${course.descr}</div>
<h3 class="chapter_catalog">课程提纲</h3>
<ul id="couList">
<c:forEach items="${course.chapterList}" var="chapter">
<li class="clearfix open"><a href="#">
<div class="openicon"></div>
<div class="outline_list l">
<!-- <em class="outline_zt"></em> -->
<h5 class="outline_name">${chapter.title }</h5>
<p class="outline_descr">${chapter.descr }</p>
</div>
</a></li>
</c:forEach>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
---------------------------
Congroller:
*1.视图解析器的使用
internalresourceviewresolver http://www.mkyong.com/spring-mvc/spring-mvc-internalresourceviewresolver-example/
mvc-dispatcher-servlet.xml视图解析器配置
---
package com.imooc.mvcdemo.controller;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.imooc.mvcdemo.model.Course;
import com.imooc.mvcdemo.service.CourseService;
@Controller
@RequestMapping("/courses")
// /courses/**
public class CourseController {
/*用来完成日志信息,在依赖管理中添加需要的API( <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>)
*/
private static Logger log = LoggerFactory.getLogger(CourseController.class);
private CourseService courseService;
@Autowired //使用Spring的容器管理了依赖关系
public void setCourseService(CourseService courseService) {
this.courseService = courseService;
}
//传统方式URL:本方法将处理 /courses/view?courseId=123 形式的URL
@RequestMapping(value="/view", method=RequestMethod.GET)
public String viewCourse(Integer courseId,
Model model) {
log.debug("In viewCourse, courseId = {}", courseId);
Course course = courseService.getCoursebyId(courseId);
model.addAttribute(course);//JSP中通过${course.title}获取
//因为使用了SpringMVC的internalViewResolver(*1),配置了前缀后缀,只返回页面名称就可以了
return "course_overview";
}
}
---4-3 Controller-现代方式----------------------------------------------------------------------------
1 通过@Controller 被SPRINGDespatcherServlet进行管理
(org.springframework.stereotype.Controller;)
2.处理controller的根URL,类级别的requestMapping
@RequestMapping("/courses")//
3.方法级别的requestMapping 本方法将处理 /courses/view?courseId=123 形式的URL,通过标签@RequestParam("courseId")取得request的参数
@RequestMapping(value="/view", method=RequestMethod.GET)
public String viewCourse(@RequestParam("courseId")Integer courseId, Model model) {
4.通过日志准确观察到绑定的行为
log.debug("In viewCourse, courseId = {}", courseId);
package com.imooc.mvcdemo.controller; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.imooc.mvcdemo.model.Course; import com.imooc.mvcdemo.service.CourseService; @Controller// @RequestMapping("/courses")//处理controller的根URL,类级别的requestMapping // /courses/** public class CourseController { /*用来完成日志信息,在依赖管理中添加需要的API( <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency>) */ private static Logger log = LoggerFactory.getLogger(CourseController.class); private CourseService courseService; @Autowired //使用Spring的容器管理了依赖关系 public void setCourseService(CourseService courseService) { this.courseService = courseService; } //方法级别的requestMapping 本方法将处理 /courses/view?courseId=123 形式的URL @RequestMapping(value="/view", method=RequestMethod.GET) public String viewCourse(@RequestParam("courseId")Integer courseId, Model model) { log.debug("In viewCourse, courseId = {}", courseId);//通过日志准确观察到绑定的行为 Course course = courseService.getCoursebyId(courseId); model.addAttribute(course);//JSP中通过${course.title}获取 //因为使用了SpringMVC的internalViewResolver(*1),配置了前缀后缀,只返回页面名称就可以了 return "course_overview"; } }
---RESTful URL 本方法将处理 /courses/view2/123 形式的URL----------------------------------------------------
参照:spring 3.0 应用springmvc 构造RESTful URL 详细讲解 转载自http://blog.csdn.net/yczz/article/details/5905893
Spring通过@RequestMapping("/view2/{courseId}")和@PathVariable("courseId")绑定了入参
//RESTful URL 本方法将处理 /courses/view2/123 形式的URL
@RequestMapping("/view2/{courseId}",method=RequestMethod.GET)
public String viewCourse2(@PathVariable("courseId") Integer courseId,
Map<String, Object> model) {
log.debug("In viewCourse2, courseId = {}", courseId);
Course course = courseService.getCoursebyId(courseId);
model.put("course",course);
return "course_overview";
}
---4-4 Controller-传统方式-----------------------------------------------------------
1.spring-mvc-study/pom.xml中引入servlet API
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
2.传统方法HttpServletRequest方式获取
//方法级别的requestMapping,本方法将处理 /courses/view3?courseId=123 形式的URL
@RequestMapping("/view3")
public String viewCourse3(HttpServletRequest request) {
Integer courseId = Integer.valueOf(request.getParameter("courseId"));
Course course = courseService.getCoursebyId(courseId);
request.setAttribute("course",course);
return "course_overview";
}
---总结---
1.@Controller:通过Controller annotation声明一个controller
2.@RequestMapping (通常出现在类级别和方法级别,二者共同组合完成了对URL映射请求的拦截)通过RequestMapping annotation映射了URL和方法
3. URL template(@RequestParam and @PathVariable):将URL路径中的参数绑定到controller method的入参
4.HttpServletRequest and/or HttpSession:也可以获取想要的结果