forword
一、目录结构
web.xml
springmvc.xml
二、forword
@Controller
@RequestMapping("/forword")
public class HelloByForwordController {
/*
* 转向 by servlet
* */
@RequestMapping(value = "/hellowen",method = RequestMethod.GET)
public void sayHelloWen(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Hello wen by servlet");
request.getRequestDispatcher("/pages2/hellowen.jsp").forward(request, response);
}
/*
* 转向 by springmvc
* */
@RequestMapping(value = "/byewen")
public String sayHelloWen1(){
System.out.println("bye wen by springmvc");
return "byewen";
}
}
运行效果:
三、redirect
@Controller
@RequestMapping("/redirect")
public class HelloByRedirectController {
/*
* 重定向 by servlet
* */
@RequestMapping("/helloemma")
public void sayHelloEmma(HttpServletResponse response) throws IOException {
System.out.println("Hello emma");
response.sendRedirect("/springmvc_demo_war/pages2/helloemma.jsp");
}
@RequestMapping("/byeemma")
public String sayByeEmma(RedirectAttributes attributes) throws IOException {
System.out.println("bye emma");
attributes.addAttribute("age", 22);
return "redirect:/redirect/helloagainemma";
}
/*
* 另一种方法:
* @RequestMapping("/helloagainemma")
* public String sayHelloAgainEmma(@RequestParam(required=false, defaultValue="22") Integer age, HttpServletRequest request)
* */
@RequestMapping(value = "/helloagainemma", method = RequestMethod.GET)
public ModelAndView sayHelloAgainEmma(Integer age, HttpServletRequest request) throws IOException {
//Integer age = request.getParameter("age");
System.out.println("hello again emma");
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("age", age);
modelAndView.setViewName("/byeemma");
return modelAndView;
}
}
运行效果
请求如果为:http://localhost:8080/springmvc_demo_war/redirect/byeemma
效果:
四、补充
Spring MVC前台使用html页面作为视图,配置静态资源后Controller控制器不起作用的解决办法:
https://www.cnblogs.com/gavinsp/p/5536183.html