記事のディレクトリ
1.転送とリダイレクト
転送:URLの変更(フロントエンドのデータクエリの固定テンプレート)は発生しません
@RequestMapping("/hello1")
public String hello1(Model model){
model.addAttribute("msg","Spring01");
return "hello"; //普通返回
}
リダイレクト:(ビジネスのログイン時に、ジャンプページ)のURLが変更されます
@RequestMapping("/hello2")
public String hello2(Model model){
model.addAttribute("msg","Spring02");
return "redirect:/index.jsp";
}
データ処理要求の前記前端
2.1通常の文字列
@Controller
@RequestMapping("/user")
public class HelloController {
//处理前端请求的数据:普通字符串
@RequestMapping("receive1")
public String receive(String name,String password,Model model){
System.out.println("接收到了name=>"+name+" pwd:"+password);
String str="name:"+name+"pwd:"+password;
model.addAttribute("msg",str);
return "hello";
}
}
テストの開始をクリックしてください:フロントエンド出力のユーザー名とパスワードを
使用すると、中国は、web.xmlにフィルタを追加することができます文字化け、文字化け入力した場合
このようなindex.jspのページでフォームを作成するなど
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="/login" method="post">
<p>用户名:
<input type="text" name="username">
</p>
<p>密码:
<input type="password" name="password">
</p>
<input type="submit">
</form>
</body>
</html>
制御層コントローラディレクトリの下LoginControllerクラスを作成します
package com.zz.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
@RequestMapping("/login")
public String login(String username, String password, Model model){
System.out.println("接收到了name=>"+username+" pwd:"+password);
model.addAttribute("msg",username);
return "hello";
}
}
テストの開始をクリックしてください:中国の名前を入力し、フォームが送信されます
文字化け現象:
解決策:web.xmlに文字化けフィルタを追加
<!--SpringMVC 给我们提供了一个乱码过滤器-->
<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>
テストを再起動した後や現象が文字化けしていないことがわかった
いくつかの極端な例では、文字化けフィルタSpringMVCは、ゴミ問題を解決することができない私たちを提供し、そしてあなたは、フィルタをカスタマイズすることができます
package com.zz.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* 解决get和post请求 全部乱码的过滤器
*/
public class GenericEncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//处理response的字符编码
HttpServletResponse myResponse=(HttpServletResponse) response;
myResponse.setContentType("text/html;charset=UTF-8");
// 转型为与协议相关对象
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
// 对request包装增强
HttpServletRequest myrequest = new MyRequest(httpServletRequest);
chain.doFilter(myrequest, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
//自定义request对象,HttpServletRequest的包装类
class MyRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
//是否编码的标记
private boolean hasEncode;
//定义一个可以传入HttpServletRequest对象的构造函数,以便对其进行装饰
public MyRequest(HttpServletRequest request) {
super(request);// super必须写
this.request = request;
}
// 对需要增强方法 进行覆盖
@Override
public Map getParameterMap() {
// 先获得请求方式
String method = request.getMethod();
if (method.equalsIgnoreCase("post")) {
// post请求
try {
// 处理post乱码
request.setCharacterEncoding("utf-8");
return request.getParameterMap();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else if (method.equalsIgnoreCase("get")) {
// get请求
Map<String, String[]> parameterMap = request.getParameterMap();
if (!hasEncode) { // 确保get手动编码逻辑只运行一次
for (String parameterName : parameterMap.keySet()) {
String[] values = parameterMap.get(parameterName);
if (values != null) {
for (int i = 0; i < values.length; i++) {
try {
// 处理get乱码
values[i] = new String(values[i]
.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
hasEncode = true;
}
return parameterMap;
}
return super.getParameterMap();
}
//取一个值
@Override
public String getParameter(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
if (values == null) {
return null;
}
return values[0]; // 取回参数的第一个值
}
//取所有值
@Override
public String[] getParameterValues(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
return values;
}
}
すると、ちょうどweb.xmlに、ここではフィルタの自己定義されたディレクトリの場所に置き換えることができます!
フォームフロントエンドにおけるプロパティ名と制御層は、矛盾している場合、フォームのユーザーに、ユーザー名として、および制御層はユーザ名であり、試験結果は次の通りである:
パラメータ制御層の方法では、この問題を解決するために、名前がnull見つけます注釈@RequestParamを追加する前に、(「ユーザー」)
@RequestMapping("/login")
public String login(@RequestParam("user") String username, String password, Model model){
System.out.println("接收到了name=>"+username+" pwd:"+password);
model.addAttribute("msg",username);
return "hello";
}
再びテスト結果:
2.2オブジェクト
我々は、オブジェクトを受け取った場合は、限り、フロントエンドの送信パラメータ名と私たちのオブジェクトの属性と同じにすることができます!
ユーザークラスを作成します。
package com.zz.pojo;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private String pwd;
}
@RequestMapping("/login2")
public String login(User user, Model model){
model.addAttribute("msg",user.getId());
System.out.println(user.getName());
System.out.println(user.getPwd());
return "hello";
}
LoginControllerは、制御層コントローラディレクトリの下のクラスに書きます
@RequestMapping("/login2")
public String login(User user, Model model){
model.addAttribute("msg",user.getId());
System.out.println(user.getName());
System.out.println(user.getPwd());
return "hello";
}
テスト開始:idがページに表示され、コンソールの表示名とPWD