纸上得来终觉浅
1.什么是Spring MVC?
Spring MVC是Spring为展现层提供的基于MVC设计理念的优秀Web框架,可以说它是Spring的一部分,而且它是一个框架。
2.下面通过一个简单的示例来说明:
1)新建动态web工程,加入Jar包:
commons-logging-1.3.jar
spring-aop-4.2.1.RELEASE.jar
spring-beans-4.2.1.RELEASE.jar
spring-context-4.2.1.RELEASE.jar
spring-core-4.2.1.RELEASE.jar
spring-expression-4.2.1.RELEASE.jar
spring-web-4.2.1.RELEASE.jar
spring-webmvc-4.2.1.RELEASE.jar
2)配置Web.xml文件:
roadArchitectWeb
helloworld
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:Spring-MVC.xml
1
helloworld
/
3)创建Spring MVC的配置文件:
4)创建一个Java类,并且添加MVC注解
package roadArchitectWeb.Test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorld {
@RequestMapping("/helloMVC")
public String helloWorld(){
System.out.println("HelloWorld.helloWorld()");
return "view";
}
}
5)WEB-INF下新建文件夹JSP,新建jsp文件view.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
Insert title here
<%
out.println("hello view");
%>
6) 浏览器中输入地址:
1)@RequestMapping
A:指定可以处理那些URL请求,可以使用在 方法处,也可以使用在类定义处; 在类定义是相对于web应用的根目录,而在方法处提供了细分的映射信息。如下:
B:可以写带参数。如下:
C:可以在RequestMapping的URL中使用通配符。如下:
2)@PathVariable
可以将URL中的占位符参数绑定到控制器处理方法的入参中:URL中的{xxx}占位符可以通过@PathVariable(“xxx”)绑定到操作方法的入参中,如下:
@Controller
public class HelloWorld {
@RequestMapping("/helloMVC/{id}")
public String helloWorld(@PathVariable("id") Integer id){
System.out.println("HelloWorld.helloWorld():"+id);
return "view";
}
}
地址栏中输入:http://localhost:8080/roadArchitectWeb/helloMVC/10
可以在控制台看到:HelloWorld.helloWorld():10
3)@RequestParam,绑定请求参数值,如下:
4)@RequestHeader ,绑定请求报头的属性值
5)@CookieValue,绑定请求中的Cookie值,示例如下:
@Controller
public class HelloWorld {
@RequestMapping("/helloMVC")
public String helloWorld(@CookieValue(value="JSESSIONID",required=false) String sessionId){
System.out.println("HelloWorld.helloWorld():"+sessionId);
return "view";
}
}
浏览器输入请求后,控制台打印信息为:
HelloWorld.helloWorld():FA8E89B32A843F912145F260C03DE905
总结:上面就是一个SpringMVC的helloworld示例。