Spring MVC
spring 的 hello world
新建并配置 web.xml,web.xml提供路径与servlet的映射关系
<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配置为类:dexController
<?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处理请求
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.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<h1>${message}</h1> //这里的message与controller中的message相对应,是变量名
原理图:
跳转
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; } }
使用session
@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; }