Spring MVC 4
项目文件结构
pom.xml依赖
<properties> <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.5.RELEASE</version> </dependency> <!-- JSTL --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> </dependencies>
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"> </beans>
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 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-3.0.xsd"> <!-- springmvc 注解驱动 --> <!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射--> <mvc:annotation-driven/> <!-- 扫描器 --> <!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean --> <context:component-scan base-package="com"/> <!-- 配置视图解析器 --> <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/view/"></property> <!-- 后缀 --> <property name="suffix" value=".jsp"></property> </bean> </beans>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- POST中文乱码过滤器 Servlet 3.0 新特性@WebFilter,@WebFilter是过滤器的注解,不需要在web.xml进行配置,不过话说还是配置好用 <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>--> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.me.www; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.ResponseBody; import org.springframework.web.servlet.ModelAndView; /* @Scope("##") : spring默认的Scope是单列模式(singleton),顾名思义,肯定是线程不安全的. 而@Scope("prototype") 可以保证每个请求都会创建一个新的实例, 还有几个参数: session request @Scope("session")的意思就是,只要用户不退出,实例就一直存在, request : 就是作用域换成了request @Controller : 不多做解释 , 标注它为Controller @RequestMapping :是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是 以该地址作为父路径。 比如现在访问getProducts方法的地址就是 : http://localhost:8080/项目名/上面web.xml配置(api)/products/list */ @Scope("prototype") @Controller @RequestMapping("/hello") public class Hello { //使用HttpServletRequest获取 @RequestMapping(value = "/listRequest") public String listRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute("message", "helloWord>>>HttpServletRequest方式 by http://blog.csdn.net/unix21/"); return "hello"; } //http://localhost:8080/www/hello/testRequestParameter?name=admin&pass=123 @RequestMapping(value = "/listRequestParameter") public String listRequestParameter(HttpServletRequest request, HttpServletResponse response) throws Exception { String name = request.getParameter("name"); String pass = request.getParameter("pass"); request.setAttribute("message", "helloWord>>>HttpServletRequestParameter方式 参数是name=" + name + " pass=" + pass + " by http://blog.csdn.net/unix21/"); return "hello"; } @RequestMapping(value = "/listModel") public String listModel(Model model) { model.addAttribute("message", "Hello World>>>Model方式 by http://blog.csdn.net/unix21/"); return "hello"; } @RequestMapping(value = "/list/{id}", method = RequestMethod.GET) public String listId(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute("message", "helloWord>>>HttpServletRequest方式 id=" + id + " by http://blog.csdn.net/unix21/"); return "hello"; } //需要注意参数名要和bean对应 @RequestMapping(value = "/list/{id}/{name}", method = RequestMethod.GET) public String listIdName(Product pro, HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute("message", "Hello World>>> 多参数" + pro.getId() + "___" + pro.getName() + " by http://blog.csdn.net/unix21/"); return "/product/info"; } @RequestMapping(value = "/listModelAndView") //@RequestMapping(value="/list",method=RequestMethod.GET) public ModelAndView listModelAndView() { //1、收集参数 //2、绑定参数到命令对象 //3、调用业务对象 //4、选择下一个页面 ModelAndView mv = new ModelAndView(); //添加模型数据 可以是任意的POJO对象 mv.addObject("message", "Hello World>>>ModelAndView方式 by http://blog.csdn.net/unix21/"); //设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页面 mv.setViewName("hello"); return mv; } @RequestMapping(value = "/post", method = RequestMethod.POST) public String postData(Product pro, HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute("message", "Hello World>>> POST参数" + pro.getId() + "___" + pro.getName() + " by http://blog.csdn.net/unix21/"); return "hello"; } //将内容或对象作为 HTTP 响应正文返回,使用@ResponseBody将会跳过视图处理部分,而是调用适合HttpMessageConverter,将返回值写入输出流。 @ResponseBody @RequestMapping("/1.json") public void getJSON(HttpServletRequest req, HttpServletResponse res) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); Product p1 = new Product(); p1.setId(123); p1.setName("abc"); Product p2 = new Product(); p2.setId(456); p2.setName("def"); map.put("p1", p1); map.put("p2", p2); //org.codehaus.jackson.map ObjectMapper mapper = new ObjectMapper(); PrintWriter pWriter = res.getWriter(); pWriter.write(mapper.writeValueAsString(map)); } /* @RequestMapping RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。 RequestMapping注解有六个属性,下面我们把她分成三类进行说明。 1、 value, method; value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明); method: 指定请求的method类型, GET、POST、PUT、DELETE等; 2、 consumes,produces; consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html; produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回; 3、 params,headers; params: 指定request中必须包含某些参数值是,才让该方法处理。 headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。 */ }
Product.java
package com.me.www; public class Product { private String name; private int id; /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } }
hello.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Hello World</title> </head> <body> <h1>Spring MVC加载成功</h1> ${message} </body> </html>
例如:http://localhost:8080/www/hello/list/123/abc
Post数据
<html> <head> <title>POST数据提交</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form action="http://localhost:8080/www/hello/post" method="post"> <input type="text" name="id"/> <input type="text" name="name"/> <input type="submit"/> </form> </body> </html>
输出json
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
参考:
SpringMVC简单构造restful, 并返回json
@Scope("##") : spring默认的Scope是单列模式(singleton),顾名思义,肯定是线程不安全的. 而@Scope("prototype")
可以保证每个请求都会创建一个新的实例, 还有几个参数: session request
@Scope("session")的意思就是,只要用户不退出,实例就一直存在,
request : 就是作用域换成了request
@Controller : 不多做解释 , 标注它为Controller
@RequestMapping :是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是 以该地址作为父路径。 比如现在访问getProducts方法的地址就是 :
http://localhost:8080/项目名/上面web.xml配置(api)/products/list/
@RequestMapping 用法详解之地址映射
@RequestMapping
RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
RequestMapping注解有六个属性,下面我们把她分成三类进行说明。
1、 value, method;
value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);
method: 指定请求的method类型, GET、POST、PUT、DELETE等;
2、 consumes,produces;
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
3、 params,headers;
params: 指定request中必须包含某些参数值是,才让该方法处理。
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。
@RequestParam @RequestBody @PathVariable 等参数绑定注解详解