-
4 数据处理及跳转
4 数据处理及跳转
结果跳转方式
ModelAndView
设置 ModelAndView 对象,根据 View 的名称和视图解析器跳转到指定的页面
页面 : {视图解析器前缀} + viewName +{视图解析器后缀}
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
对应的Controller类
package com.zzb.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
// 创建模型视图
ModelAndView modelAndView = new ModelAndView();
// 调用业务层
String msg = "ControllerTest1";
modelAndView.addObject("msg", msg);
// 设置跳转视图
modelAndView.setViewName("test");
return modelAndView;
}
}
ServletAPI
通过设置ServletAPI,不需要视图解析器
1、通过HttpServletResponse进行输出
2、通过HttpServletResponse实现重定向
3、通过HttpServletRequest实现转发
package com.zzb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
@RequestMapping("/t3")
public class ControllerTest3 {
@RequestMapping("/t1")
public void test1(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.getWriter().println("Hello,Spring BY servlet API");
}
@RequestMapping("/t2")
public void test2(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// 重定向
resp.sendRedirect(req.getContextPath() + "/index.jsp");
}
@RequestMapping("/t3")
public void test3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 转发
req.setAttribute("msg", "/t3/t3");
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req, resp);
}
}
Spring MVC
通过 Spring MVC 来实现转发和重定向——不需要视图解析器。
注意:测试前先将视图解析器注释掉。
package com.zzb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/t4")
public class ControllerTest4 {
@RequestMapping("/t1")
public String test1(){
// 转发
return "/index.jsp";
}
@RequestMapping("/t2")
public String test2(){
// 显示转发
return "forward:/index.jsp";
}
@RequestMapping("/t3")
public String test3(){
// 重定向
return "redirect:/index.jsp";
}
}
通过 Spring MVC 来实现转发和重定向——使用视图解析器。
注意:开启视图解析器。
package com.zzb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/t5")
public class ControllerTest5 {
@RequestMapping("/t1")
public String test1(){
// 转发
return "test";
}
@RequestMapping("/t2")
public String test2(){
// 重定向
return "redirect:/index.jsp";
}
}
数据处理
处理提交数据
1、提交的域名数据名称和处理方法的参数名一致
package com.zzb.controller;
import com.zzb.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/data")
public class DataController {
// 域名参数与控制器参数名一致的情况
@RequestMapping("/t1")
public String test1(String name, Model model){
// 1 接收前端参数
System.out.println(name);
// 2 将数据返回给前端
model.addAttribute("msg", name);
return "test";
}
}
测试结果:
2、提交的域名数据名称和处理方法的参数名不一致
// 域名参数与控制器参数名不一致的情况
@RequestMapping("/t2")
public String test2(@RequestParam("username") String name, Model model){
// 1 接受前端参数
System.out.println(name);
// 2 将参数传递给前端展示
model.addAttribute("msg", name);
return "test";
}
测试结果:
3、参数是一个对象
package com.zzb.pojo;
public class User {
private int id;
private String name;
private int age;
public User() {
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
// 前端提交的参数是一个对象
@RequestMapping("/t3")
public String test3(User user, Model model){
// 1 接收前端传递的参数
System.out.println(user.toString());
// 2 将参数传递给前端页面展示
model.addAttribute("msg", user.toString());
return "test";
}
测试结果:
注意:如果传递参数是对象的话,前端传递的参数名和对象的属性名必须一致,否则为null。
前端展示数据
1、ModelAndView
package com.zzb.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
// 创建模型视图
ModelAndView modelAndView = new ModelAndView();
// 调用业务层
String msg = "ControllerTest1";
modelAndView.addObject("msg", msg);
// 设置跳转视图
modelAndView.setViewName("test");
return modelAndView;
}
}
2、ModelMap
@RequestMapping("/t1")
public String test1(String name, ModelMap modelMap){
// 1 接收前端参数
System.out.println(name);
// 2 将数据返回给前端
modelMap.addAttribute("msg", name);
return "test";
}
3、Model
@RequestMapping("/t1")
public String test1(String name, Model model){
// 1 接收前端参数
System.out.println(name);
// 2 将数据返回给前端
model.addAttribute("msg", name);
return "test";
}
3种方法对比:
-
Model 只有寥寥几个方法只适合用于储存数据,简化了新手对于Model对象的操作和理解;
-
ModelMap 继承了 LinkedMap ,除了实现了自身的一些方法,同样的继承 LinkedMap 的方法和特性;
-
ModelAndView 可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的跳转。
乱码问题
1、在index.jsp页面写一个表单
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action=${pageContext.request.contextPath}/data/t1 method="post">
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
2、后端处理程序
@Controller
@RequestMapping("/data")
public class DataController {
// 域名参数与控制器参数名一致的情况
@RequestMapping("/t1")
public String test1(String name, Model model){
// 1 接收前端参数
System.out.println(name);
// 2 将数据返回给前端
model.addAttribute("msg", name);
return "test";
}
}
3、输入中文 哈哈哈 测试
乱码问题通过过滤器解决,Spring MVC 提供了一个过滤器,需要在web.xml中配置!
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
自定义过滤器:
package com.zzb.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 {
@Override
public void destroy() {
}
@Override
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);
}
@Override
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中配置这个过滤器即可!
来源:https://www.cnblogs.com/zzbstudy/p/14139570.html