請求處理方法簽名
1) Spring MVC 通過分析處理方法的簽名,將HTTP請求信息綁定到處理方法的相應入參中。
2) Spring MVC 對控制器處理方法簽名的限制是很寬鬆的,幾乎可以按喜歡的任何方式對方法進行簽名。
@RequestParam註解
在處理方法入參處使用 @RequestParam 可以把請求參數傳遞給請求方法
- value:參數名
- required:是否必須。默認爲 true, 表示請求參數中必須包含對應的參數,若不存在,將拋出異常
- defaultValue: 默認值,當沒有傳遞參數時使用該值
使用POJO作爲參數
1) 使用 POJO 對象綁定請求參數值
2) Spring MVC 會按請求參數名和 POJO 屬性名進行自動匹配,自動爲該對象填充屬性值。支持級聯屬性。如:dept.deptId、dept.address.tel 等
使用Servlet原生API作爲參數
MVC 的 Handler 方法可以接受哪些 ServletAPI 類型的參數:
- HttpServletRequest
- HttpServletResponse
- HttpSession
- java.security.Principal
- Locale
- InputStream
- OutputStream
- Reader
- Write
代碼示例:
(項目仍是在前兩篇博客中相同的項目)
使用POJO需要的實體類:
Employee:
package com.learn.springmvc.entities;
public class Employee {
private Integer id;
private String lastName;
private String email;
private Department dept;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", dept=" + dept + "]";
}
}
Department:
package com.learn.springmvc.entities;
public class Department {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Department [id=" + id + ", name=" + name + "]";
}
}
index.jsp發送相應的請求:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/hello">Hello SpringMVC</a><br>
<a href="${pageContext.request.contextPath }/testValue2">Test value</a><br>
<a href="${pageContext.request.contextPath }/testMethod">Test method</a><br>
<form action="${pageContext.request.contextPath }/testMethod" method="post">
<input type="submit" value="Test Method">
</form>
<%-- <a href="${pageContext.request.contextPath }/testRequestParam?username=admin&age=18">Test RequestParam</a><br> --%>
<a href="${pageContext.request.contextPath }/testRequestParam?username=admin">Test RequestParam</a><br>
<form action="${pageContext.request.contextPath }/testPOJO" method="post">
員工工號:<input type="text" name="id"><br>
員工姓名:<input type="text" name="lastName"><br>
員工郵箱:<input type="text" name="email"><br>
部門編號:<input type="text" name="dept.id"><br>
部門名稱:<input type="text" name="dept.name"><br>
<input type="submit" value="Test POJO">
</form>
<a href="${pageContext.request.contextPath }/testServletAPI?username=admin">Test ServletAPI</a><br>
</body>
</html>
三種方法都在SpringMVCHandler.java中,以完成index.jsp中的測試請求:
package com.learn.springmvc.helloworld;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.learn.springmvc.entities.Employee;
@Controller
public class SpringMVCHandler {
/*
* @RequestMapping註解中的屬性
* 1.value:用來設置映射的請求地址,值得類型是String類型的數組
* 如果只映射一個請求地址,那麼value的值不需要添加大括號{},value屬性名可以省略不寫
* 2.method:用來設置要映射的請求方式
* 如果沒有設置該屬性,那麼只看映射的請求地址,不管請求方式
*/
@RequestMapping(value= {"/testValue","/testValue2"})
public String testValue() {
System.out.println("測試@RequestMapping註解value屬性");
return "success";
}
// @RequestMapping(value="/testMethod",method=RequestMethod.GET,params="age=18")
@RequestMapping(value="/testMethod",method=RequestMethod.POST)
public String testMethod() {
System.out.println("測試@RequestMapping註解method屬性");
return "success";
}
/*
* @RequestParam註解:
* -用來映射請求參數
* 如果Handler的方法的入參的參數名與請求參數的參數名一致,那麼該該註解可以省略
* -該註解的屬性:
* 1.value:
* 設置請求參數的名字
* 2.required:
* 設置該請求參數是否是必須的,,默認是true
* 3.defaultValue:
* 這隻請求參數的默認值,如果沒有傳入請求參數將使用該值
*/
@RequestMapping("/testRequestParam")
// public String testRequestParam(String username, Integer age) {
public String testRequestParam(@RequestParam(value="username") String user,
@RequestParam(value="age",required=false,defaultValue="0") Integer age) {
System.out.println("用戶名是:"+user);
System.out.println("年齡是:"+age);
return "success";
}
/*
* Spring MVC會按請求參數名和 POJO 屬性名進行自動匹配,自動爲該對象填充屬性值。支持級聯屬性
*/
@RequestMapping("/testPOJO")
public String testPOJO(Employee employee) {
System.out.println("員工信息是:"+employee);
return "success";
}
/*
* MVC 的 Handler 方法可以接受哪些 ServletAPI 類型的參數
1) *HttpServletRequest
2) *HttpServletResponse
3) *HttpSession
4) java.security.Principal
5) Locale
6) InputStream
7) OutputStream
8) Reader
9) Write
*/
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request, HttpServletResponse response) {
//獲取請求參數
String username = request.getParameter("username");
System.out.println(username);
return "success";
}
}
解決POST請求中文亂碼問題
index.jsp頁面中存在的表單,提交時提交到服務器會出現中文亂碼問題,無法正常顯示,此時就需要相應的解決辦法。
我以前的博客中也提到過類似問題的解決辦法,但在Spring MVC中可以使用Spring提供的CharacterEncodingFilter過濾器中的doFilterInternal方法
CharacterEncodingFilter:
public class CharacterEncodingFilter extends OncePerRequestFilter {
private String encoding;
private boolean forceEncoding = false;
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public void setForceEncoding(boolean forceEncoding) {
this.forceEncoding = forceEncoding;
}
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
request.setCharacterEncoding(this.encoding);
if (this.forceEncoding) {
response.setCharacterEncoding(this.encoding);
}
}
filterChain.doFilter(request, response);
}
}
要使用在web.xml中配置過濾器即可
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" 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_2_5.xsd">
<!-- 配置解決POST請求中文亂碼問題的過濾器 -->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置前端控制器:DispatcherServlet
快捷鍵:alt + / 選中倒數第二項
-->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 配置SpringMVC配置文件的路徑 -->
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<!-- 配置映射的請求地址:"/" -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>