结构:
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.spring</groupId> <artifactId>HelloSpringMVC</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>HelloSpringMVC Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- Servlet Library --> <!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- Spring dependencies --> <!-- http://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- http://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.4.RELEASE</version> </dependency> </dependencies> <build> <finalName>HelloSpringMVC</finalName> <plugins> <!-- Config: Maven Tomcat Plugin --> <!-- http://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat7-maven-plugin --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <!-- Config: contextPath and Port (Default - /HelloSpringMVC : 8080) --> <!-- <configuration> <path>/</path> <port>8899</port> </configuration> --> </plugin> </plugins> </build> </project>
xsi全名:xml schema instance
web-app是web.xml的根节点标签名称
version是版本的意思
xmlns是web.xml文件用到的命名空间
xmlns:xsi是指web.xml遵守xml规范
xsi:schemaLocation是指具体用到的schema资源
参考:http://www.cnblogs.com/zhao1949/p/5652167.html
web.xml:
<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/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>HelloWorldSpring</display-name> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- Other XML Configuration --> <!-- Load by Spring ContextLoaderListener --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/root-context.xml</param-value> </context-param> <!-- Spring ContextLoaderListener --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
DispatcherServlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,Servlet拦截匹配规则要自已定义,把拦截下来的请求,依据相应的规则分发到目标Controller来处理,是配置spring MVC的第一步
spring-mvc-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: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-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <context:component-scan base-package="com.spring.mvc"/> <context:annotation-config/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">//视图名称解析器 <property name="prefix"> <value>/WEB-INF/pages/</value><!-- 前缀 --> </property> <!-- 这里前缀/WEB-INF/pages/+HelloWorldController.java返回的helloworld+后缀.jsp = /WEB-INF/pages/helloworld.jsp -->
<property name="suffix"> <value>.jsp</value><!-- 后缀 --> </property>
</bean>
</beans>
root-context.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Empty --> </beans>
HelloWorldController.java:
package com.spring.mvc; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller //负责注册一个bean 到spring 上下文中 public class HelloWorldController { @RequestMapping("/hello")//注解为控制器指定可以处理哪些 URL 请求 public String hello(Model model) { model.addAttribute("hello", "哈喽 Spring MVC!"); return"helloworld"; } }
index.jsp:
<html> <body> <h2>Hello World!</h2> </body> </html>
- Run As/Maven install
运行配置:
- Run HelloSpringMVC
- ${workspace_loc:/HelloSpringMVC}
- tomcat7:run
然后运行
访问http://localhost:8080/HelloSpringMVC/
访问http://localhost:8080/HelloSpringMVC/hello
--------------------------------完毕-------------------------------
修改HelloWorldController.java
package com.spring.mvc; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloWorldController { @RequestMapping("/hello") public String hello(Model model) { model.addAttribute("hello", "哈喽 Spring MVC!"); return"helloworld"; } //在方法中使用 HttpServletRequest, HttpServletResponse @RequestMapping("/requestResponse") public String requestResponseExample(HttpServletRequest request, HttpServletResponse reponses, Model model) { model.addAttribute("hello", "哈喽 requestResponse"); return "helloworld"; } }
访问http://localhost:8080/HelloSpringMVC/requestResponse
--------------------------------完毕-------------------------------
重定向到另一页面
修改HelloWorldController.java
package com.spring.mvc; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class HelloWorldController { @RequestMapping("/hello") public String hello(Model model) { model.addAttribute("hello", "/hi被redirect到了/hello"); return"helloworld"; } @RequestMapping("/requestResponse") public String requestResponseExample(HttpServletRequest request, HttpServletResponse reponses, Model model) { model.addAttribute("hello", "哈喽 requestResponse"); return "helloworld"; } @RequestMapping(value = "/hi", method = RequestMethod.GET) public String hi(Model model) { return "redirect:/hello"; } }
访问http://localhost:8080/HelloSpringMVC/hi
地址会变成http://localhost:8080/HelloSpringMVC/hello
--------------------------------完毕-------------------------------
新增RequestParamExampleController.java
package com.spring.mvc; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class RequestParamExampleController { @RequestMapping("/user") public String userInfo(Model model, @RequestParam(value = "name", defaultValue = "Guest") String name) { model.addAttribute("name", name); if("admin".equals(name)) { model.addAttribute("age", "18"); } else{ model.addAttribute("age", "0"); } return "userInfo"; } }
新增userInfo.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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=ISO-8859-1"> <title>Insert title here</title> </head> <body> <h2>${name}</h2> Age: ${age} </body> </html>
访问http://localhost:8080/HelloSpringMVC/user:
访问http://localhost:8080/HelloSpringMVC/user?name=admin
--------------------------------完毕-------------------------------
添加PathVariableExampleController.java
package com.spring.mvc; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class PathVariableExampleController { /** * @PathVariable Example: * */ @RequestMapping("/web/fe/{sitePrefix}/{language}/document/{id}/{naturalText}")//URI模板
public String documentView(Model model, @PathVariable(value = "sitePrefix") String sitePrefix, @PathVariable(value = "language") String language, @PathVariable(value = "id") Long id, @PathVariable(value = "naturalText") String naturalText) { model.addAttribute("sitePrefix", sitePrefix); model.addAttribute("language", language); model.addAttribute("id", id); model.addAttribute("naturalText", naturalText); String documentName = "love"; if(id == 888) { documentName = "love888"; } model.addAttribute("documentName", documentName); return "documentView"; } }
添加documentView.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> <h3>${documentName}</h3> Site Prefix: ${sitePrefix} <br> Language: ${language} <br> ID: ${id} <br> Natural Text: ${naturalText} <br> </body> </html>
访问http://localhost:8080/HelloSpringMVC/web/fe/love/you/document/000/spring-mvc
访问http://localhost:8080/HelloSpringMVC/web/fe/love/you/document/888/spring-mvc
--------------------------------完毕-------------------------------
使用@ResponseBody和方法返回字符串
新增ResponseBodyExample1Controller.java
package com.spring.mvc;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class ResponseBodyExample1Controller {
// Simple example, method returns String.
@RequestMapping(value = "/ResponseBody")
@ResponseBody
public String authorInfo(Model model) {
return "I love you";
}
}
访问http://localhost:8080/HelloSpringMVC/ResponseBody
此处不需要“.jsp”文件即可显示
--------------------------------完毕-------------------------------
参考:http://www.cnblogs.com/sunniest/p/4555801.html
-----------------------------------------------------------------------------