SpringMVC学习笔记5----视图解析器实现转发和重定向

6.SprIngMVC实现重定向和转发

1.方式一,无视图解析器的转发和重定向

​ 使用request来转发

//无视图解析器的转发和重定向
@Controller
public class ModelTest1 {
    
    

    //使用request来转发
    @RequestMapping("/m1/t1")
    public String test1(HttpServletRequest request, HttpServletResponse response){
    
    

        HttpSession session=request.getSession();
        System.out.println(session.getId());

        return "/WEB-INF/jsp/test.jsp";
    }

}

转发:

return “/index.jsp”

return “forward:/index.jsp”

//无视图解析器的转发和重定向
@Controller
public class ModelTest1 {
    
    

    @RequestMapping("/m1/t1")
    public String test1(Model model){
    
    

       model.addAttribute("msg","转发过来的");
        return "/WEB-INF/jsp/test.jsp";
    }

}

重定向:

return “redirect:/index.jsp”

//无视图解析器的转发和重定向
@Controller
public class ModelTest1 {
    
    

    @RequestMapping("/m1/t1")
    public String test1(Model model){
    
    

       model.addAttribute("msg","重定向");
        return "redirect:/index.jsp";
    }

}

2.方式二,有视图解析器的转发和重定向

还视图解析器为:

<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>

有视图解析器的转发

@Controller
public class ModelTest1 {
    
    

    @RequestMapping("/m1/t1")
    public String test1(Model model){
    
    

       model.addAttribute("msg","有视图解析器的转发");
        return "test";
    }

}

有视图解析器的重定向:

@Controller
public class ModelTest1 {
    
    

    @RequestMapping("/m1")
    public String test1(Model model){
    
    

       //model.addAttribute("msg","有视图解析器的重定向");
        return "redirect:/index.jsp";
    }

}

有了视图解析器的重定向,直接写地址就可以了,前提是不能访问web-inf文件夹下的文件。

redirect:后面就是地址。

猜你喜欢

转载自blog.csdn.net/weixin_45263852/article/details/115101529