Spring MVC 4
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>
applicationContext.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: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.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsdhttp://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.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://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>
hello.java
/** 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.?mapObjectMapper mapper = new ObjectMapper();PrintWriter pWriter = res.getWriter();pWriter.write(mapper.writeValueAsString(map));}/*@RequestMappingRequestMapping是一個用來處理請求地址映射的注解,可用于類或方法上。用于類上,表示類中的所有響應請求的方法都是以該地址作為父路徑。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
post參數轉碼的另一種處理方法
@RequestMapping(value = "/post", method = RequestMethod.POST)public ModelAndView post(@RequestParam("username")String username) {username=StringUtil.encodeStr(username); ModelAndView mv = new ModelAndView();mv.addObject("username", username);mv.setViewName("post");return mv;
}
/*** ISO-8859-1轉UTF-8 主要用于POST數據處理** @param str 需要轉碼的值*/public static String encodeStr(String str) {try {return new String(str.getBytes("ISO-8859-1"), "UTF-8");} catch (UnsupportedEncodingException e) {return null;}}
@RequestBody ?
@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) { // implementation omitted
}
/
參考:
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 等參數綁定注解詳解
總結
以上是生活随笔為你收集整理的Spring MVC 4的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java动态加载一个类的几种方法以及in
- 下一篇: Apache commons-io