栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringMVC04:数据处理及跳转

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringMVC04:数据处理及跳转

页面跳转的方式 一、ModelAndView<.h3>

设置ModelAndView对象 , 根据view的名称 , 和视图解析器跳到指定的页面 .

页面 : {视图解析器前缀} + viewName +{视图解析器后缀}

二、ServletAPI<.h3>

通过设置ServletAPI , 不需要视图解析器 .

注意: Tomcat启动后确定加载出index.jsp页面

1、通过HttpServletResponse进行输出

    @RequestMapping("m1/t1")
    public void test(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.getWriter().println("hello");
    }

2、通过HttpServletResponse实现重定向

  @RequestMapping("m1/t2")
    public void test01(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.sendRedirect("/index.jsp");
    }
	//重定向下不能访问WEB-INF下的资源

3、通过HttpServletResponse和HttpServletRequest实现转发

    @RequestMapping("m1/t3")
    public void test02(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("msg","test you");
        req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req,resp);
    }
三、SpringMVC实现转发和重定向(无需视图解析器)

通过返回的字符串路径来说明是转发还是重定位
重定位不能访问WEB-INF下的资源

1.隐示请求转发

  @RequestMapping("/m2/t1")
    public String test(Model model){
        //输出到页面
        model.addAttribute("msg","ControllerTest");
        return "/WEB-INF/jsp/hello.jsp";
    }

2.显示请求转发 forward:

    @RequestMapping("/m2/t2")
    public String test01(Model model)
    {
        model.addAttribute("msg","NoVI2");
        return "forward:/WEB-INF/jsp/hello.jsp";
    }

3.重定向 redirect:

    @RequestMapping("m2/t3")
    public String test02(Model model)
    {
        model.addAttribute("msg","NoVI3");
        //重定向实现
        return "redirect:/index.jsp";
    }
三、SpringMVC实现转发和重定向(需视图解析器)

//开启视图解析器
1.转发

   @RequestMapping("m3/t1")
    public String t1(Model model) {
        model.addAttribute("msg", "加油");
        return "hello";
    }

2.重定向 redirect:

 @RequestMapping("m3/t2")
    public String t2()
    {
        return "redirect:/index.jsp";
    }
数据处理

处理提交数据

1.提交的域名称和处理方法的参数名一致

提交数据:提交数据 : http://localhost:8080/user/t1?name=Liang

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/t1")
    public String test1(String name, Model model)
    {
        System.out.println("接受到的参数为:"+name);
        model.addAttribute("msg",name);
        return  "hello";
    }

}

2.提交的域名称和处理方法的参数名不一致

提交数据:http://localhost:8080/user/t2?username=Liang

    //@RequestParam 给提交的域名称换参数名
    @GetMapping("/t2")
    public String test2(@RequestParam("username")String name, Model model)
    {
        //1.接收前端参数
        System.out.println("接收的前端参数为:"+name);
        //2.将返回的结果传递给前端,Model
        model.addAttribute("msg",name);
        return "hello";
    }

@RequestParam 给提交的域名称换参数名

3.提交的是一个对象

提交数据:http://localhost:8080/user/t3?id=1&name=Liang&age=18

要求提交的表单域和对象的属性名一致 , 参数使用对象即可

   @RequestMapping("/t3")
    public String test3(User user,Model model)
    {
        System.out.println(user);
        model.addAttribute("msg",user);
        return "hello";
    }
    
数据显示到前端

第一种:通过ModelView

第二种: 通过Model

第三种: 通过ModelMap

前面两种我们都用过了,看看第三种

@RequestMapping("/t4")
public String test4(ModelMap map){
    // 封装要显示到视图中的数据
   	// 相当于req.setAttribute("msg","hello");
    map.addAttribute("msg","hello");
    return "test";
}

对比:

Model 只有寥寥几个方法只适合用于储存数据,简化了新手对于Model对象的操作和理解;

ModelMap 继承了 linkedHashMap ,除了实现了自身的一些方法,同样的继承 linkedHashMap 的方法和特性;

ModelAndView 可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的跳转。

乱码问题

出现乱码:表单中输入中文前端页面出现乱码

测试步骤:

1.表单页面

  

2.Controller类

@Controller

public class ControllerTest {
    @PostMapping("/e/t")
    public String test(String name, Model model)
    {
        model.addAttribute("msg",name);
        return "test";
    }
}

3.中文测试:出现乱码

乱码是一个常见的问题,SpringMVC给我们提供了一个过滤器,在web.xml中配置

解决办法:

1.在web.xml配置SpringMVC过滤器
配置代码如下:



    
        encoding
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            utf-8
        
    

    
        encoding
        
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 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 parameterMap = getParameterMap();
       String[] values = parameterMap.get(name);
       if (values == null) {
           return null;
      }
       return values[0]; // 取回参数的第一个值
  }

web.xml配置

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/736773.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号