SpringMvc作用的是控制器层,取代javaWeb中的Serverlet
所以需要Spring开发web项目的所有jar:
spring-aop.jar
spring-bean.jar
spring-context.jar
spring-core.jar
spring-web.jar
以及下面的:
spring-webmvc.jar
commons-logging.jar
一、编写controller层
@Controller
@RequestMapping("handler")//映射
public class SpringMVCHandler {
@RequestMapping(value="aa",method= RequestMethod.POST,params = {"www=zs","age!=23","!height"})//用于拦截对应的href
public String aa(){
return "success";//会和前缀后缀拼成 view/success.jsp
//默认使用了请求转发的方式
}
}
@RequestMapping 中 method指定请求方式必须是post,params规定了参数的格式:www属性必须是zs,age可以没有,但有的话必须不等于23,以及不能有height属性
二、编写mvc配置文件
类似于Spring:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描有注解的包-->
<context:component-scan base-package="handler"></context:component-scan>
<!--配置视图解析器() 该解析器的作用是将东西渲染成success.jsp页面-->
<!--如果发现jsp中包含了jstl语言,则自动转为JstlView-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
三、编写web.xml进行拦截请求
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!--上面param-value 当xml 命名为servletname的值-servlet.xml 并且放在web-Inf 目录下可以不用配置 -->
<!--拦截一切请求,给DispatcherServlet 让它自己去找@requestMapping-->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
这里的servlet标签和servlet-mapping标签相当于Servlet2.5的写法。
这里需要注意一点,如果mvc配置文件放在Web-Inf目录下,并且名字是servlet-name的值-servlet.xml,就可以不写init-param
测试:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form>
<form action="handler/aa" method="post">
www:<input type="text" name="www" value="zs"/><br/>
age:<input type="text" name="age"/></br>
<input type="submit" value="post"/>
</form>
</body>
</html>
只要age输入的不是23,则点击表单的提交按钮,页面会跳转到view/success.jsp