Spring MVC 是 Spring 提供的一个基于 MVC 设计模式的轻量级 Web 开发框架,本质上相当于 Servlet。
需要的jar
web.xml配置SpringMVC
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>spring_mvc_lx01</display-name> <!-- SpringMVC核心配置文件 --> <servlet> <servlet-name>springmvc</servlet-name> <!-- SpringMVC的实现 --> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--Spring MVC 初始化时将在应用程序的 WEB-INF 目录下查找配置文件,该配置文件的命名规则是“servletName-servlet.xml”--> <!--servletName就是web.xml里对应的servlet-name--> <!--例如 springmvc-servlet.xml。 否则执行以下--> <!-- 加载SpringMVC其他的配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:Spring-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> </web-app>
SpringMVC主配置文件
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 开启注解配置 --> <context:annotation-config/> <!-- 扫描指定controller的包(构造扫描) --> <context:component-scan base-package="Controller"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 配置jsp路径的前缀 --> <property name="prefix" value="jsp/"/> <!-- 配置jsp路径的后缀 --> <property name="suffix" value=".jsp"/> </bean> </beans>
javabean(entity)
略Controller
package Controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import entity.User; @Controller public class User_controller { @RequestMapping("login.do") public String login(User user) { System.out.println(user.getUsername()+user.getPassword()); return "redirect:add.do"; } @RequestMapping("add.do") public String add(User user) { return "success"; } }
jsp页面
略面试题:SpringMVC执行流程