结果跳转方式
使用视图解析器
ModelAndView
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//只要实现了Controller接口 即为一个控制器
public class ControllerTest01 implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ModelAndView mv = new ModelAndView();
mv.addObject("msg","Hi,ControllerTest01");
mv.setViewName("test");
return mv;
}
}
不使用视图解析器
需设置ServletAPI
- 通过HttpServletResponse进行输出
- 通过HttpServletResponse实现重定向
- 通过HttpServletResponse实现转发
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ModelTest {
@RequestMapping("/m1/t1")
public String test1(Model model){
model.addAttribute("msg","ModelTest");
//转发
return "test";
}
@RequestMapping("/m1/t2")
public String test2(Model model){
model.addAttribute("msg","ModelTest");
//转发
return "forward:/test";
}
@RequestMapping("/m1/t3")
public String test3(Model model){
model.addAttribute("msg","ModelTest");
//重定向
return "redirect:/test";
}
}
SpringMVC实现转发和重定向
不使用视图解析器
前提:注释掉视图解析器
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ModelTest {
@RequestMapping("/m1/t1")
public String test1(Model model){
model.addAttribute("msg","ModelTest");
//转发
return "test";
}
@RequestMapping("/m1/t2")
public String test2(Model model){
model.addAttribute("msg","ModelTest");
//转发
return "forward:/test";
}
@RequestMapping("/m1/t3")
public String test3(Model model){
model.addAttribute("msg","ModelTest");
//重定向
return "redirect:/test";
}
}
使用视图解析器
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
@Controller
public class ModelTest {
@RequestMapping("/t1")
public String test1(){
//转发
return "test";
}
@RequestMapping("/t2")
public String test2(){
//重定向
return "redirect:/index.jsp";
}
}