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

springMVC几种页面跳转方式小结

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

springMVC几种页面跳转方式小结

前面已经了解了Controller的几种配置方式

今天主要写一下响应界面跳转的几种方式

1.在注解的方式中

1.1通过HttpServletResponse的API直接输出(不需要配置渲染器)

controller类的主要代码

@Controller
public class RequestController{
 @RequestMapping("/resp")
  public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {

     resp.getWriter().println("hello HttpServletResponse");

  }

web.xml配置




  
    dispatcher
    org.springframework.web.servlet.DispatcherServlet
    1
  
  
    dispatcher
    /
  

dispatcher-servlet.xml主要代码



  
  


1.2 使用HttpServletResponse 重定向到另一个视图(其他不变 )

  @RequestMapping("/resp")
  public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {

    resp.sendRedirect("index.jsp");

  }
}

1.3 使用HttpServletRequest 转发(默认访问/下的index.jsp页面 不受渲染器的影响)

@RequestMapping("/resp")
  public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    req.setAttribute("message","it's forword ");
    req.getRequestDispatcher("index.jsp").forward(req,resp);
    }

1.4直接返回jsp页面的名称(无渲染器)

其他的配置不变

 @RequestMapping("/nice")
  public String hello1(){
    //转发方式1
    return "home.jsp";
    //转发方式2
    return "forward:index.jsp";
    //重定向方式
    return "redirect:index.jsp";
  }

1.5当有渲染器指定

 @RequestMapping("/nice")
  public String hello1(){
    //转发方式1
    return "home";
    //转发方式2
    return "forward:index";
    //重定向方式 hello指的是requsrmapping
    return "redirect:hello";
  }

2 使用view

2.1 使用modelandview

需要视图解析器 能指定跳转页面

public class HelloController implements Controller {


  @Override
  public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest,
     javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {

    ModelAndView mv = new ModelAndView();
    //封装要显示到视图的数据
    mv.addObject("msg","hello myfirst mvc");
    //视图名
    mv.setViewName("hello");
    return mv;

  }
}

[servlet-name]-servlet.xml


  

  
  
  
  
  
  
  

  

2.2 使用modelview

不需要视图解析器 不能指定跳转页面

 //通过modelmap方式
  @RequestMapping("/modelmap")
  public String modelHello(String name,ModelMap map){
    map.addAttribute("name",name);
    System.out.println(name);

    return "index.jsp";
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

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

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

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