新建並配置 web.xml,web.xml提供路徑與servlet的映射關係html
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> </servlet> <servlet-mapping> <!--這裏將 / 即任意路徑映射到 DispatcherServlet --> <servlet-name>springmvc</servlet-name> <!--這裏的name要和上面的springmvc保持一致--> <url-pattern>/</url-pattern> <!-- 這裏表示映射的路徑,/表示任意路徑--> </servlet-mapping>
建立springmvc-servlet.xml並配置,這是Spring MVC的 映射配置文件,表示訪問路徑/index會交給id=indexController的bean處理;id=indexController的bean配置爲類:dexControllerjava
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="simpleUrlHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/index">indexController</prop> </props> </property> </bean> <bean id="indexController" class="controller.IndexController"></bean> </beans>
控制類要實現接口controller,並提供方法handleRequest處理請求web
package controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; public class IndexController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav = new ModelAndView("index.jsp"); //ModelAndView 將視圖層和模型層聯繫在一塊兒,new ModelAndView("index.jsp")表示視圖是index.jsp mav.addObject("message", "Hello Spring MVC"); //向視圖層傳遞數據,數據的名字是message,內容是 Hello Spring MVC return mav;
} }
準備index.jspspring
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<h1>${message}</h1> //這裏的message與controller中的message相對應,是變量名
原理圖:session
package controller; 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 //註解,表示該類是一個控制器,這樣不用再實現controller接口 public class IndexController { @RequestMapping("/index") //再handleRequest方法前加註解,表示 /index 路徑慧映射到該函數上 public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav = new ModelAndView("index"); mav.addObject("message", "Hello Spring MVC"); return mav; } @RequestMapping("/jump") //同理將 /jump路徑映射到該函數 public ModelAndView jump() { ModelAndView mav = new ModelAndView("redirect:/index"); // redirect:/index 表示服務端跳轉,跳轉到index return mav; } }
使用sessionmvc
@RequestMapping("/check") public ModelAndView check(HttpSession session) { Integer i = (Integer) session.getAttribute("count"); if (i == null) i = 0; i++; session.setAttribute("count", i); ModelAndView mav = new ModelAndView("check"); return mav; }