HelloController.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController{
/**
* 1.设置ModelAandView对象。根据View的名称,和视图解析器跳转带指定的页面
* 页面:视图解析器的前缀+view name +视图解析器的后缀
*/
@RequestMapping("hello")
public ModelAndView handleRequest(HttpServletRequest req,
HttpServletResponse resp) throws Exception {
ModelAndView mav=new ModelAndView();
//封装要显示到视图的数据
mav.addObject("msg", "hello springmvc controller");
//视图名
mav.setViewName("hello");
return mav;
}
/**
* 2.通过servletAPI对象来实现。不需要视图解析器的配置
* 1)通过HttpServletResponse来进行输出。
* 2)通过HttpServletResponse实现重定向。
* 3) 通过HttpServletResponse实现转发。
*/
@RequestMapping("/hello1")
public void hello1(HttpServletRequest req,
HttpServletResponse resp) throws Exception{
//1)通过HttpServletResponse来进行输出。
//resp.getWriter().println("hello spring mvc use httpservlet api!");
//2)通过HttpServletResponse实现重定向。
//resp.sendRedirect("index.jsp");
//3)通过HttpServletResponse实现转发
req.setAttribute("msg", "servlet api forward");
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
/**
* 通过Spring mvc 来实现转发和重定向 --- 没有试图解析器
* @return
*/
@RequestMapping("/hello2")
public String hello2(){
//转发1
//return "index.jsp";
//转发2
System.out.println("转发2");
return "forward:index.jsp";
//重定向
//System.out.println("实现重定向");
//return "redirect:index.jsp";
}
/**
* 通过Spring mvc 来实现转发和重定向 --- 有试图解析器
* @return
*/
@RequestMapping("/hello3")
public String hello3(){
//转发1
//return "hello";
//转发2
return "forward:hello.do";
//重定向 不需要视图解析器
//return "redirect:hello.do";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指明配置文件的位置 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
web-inf/jsp/hello.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>hello</title>
</head>
<body>
${msg } <br/>
web-inf/hello.jsp
</body>
</html>