注解方式和配置文件方式的步骤一样,所以这里就写了点和配置文件方式不同的地方。
配置文件创建springMVC的连接:传送门
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>springAnno</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/springAnno-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springAnno</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
在编写处理器的时候可以不用实现Controller接口直接在放放上面使用注解@RequestMapping()
处理器代码:
package cn.test.temp;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class Second {
@RequestMapping("/second.action")
public String test(Model model){
model.addAttribute("msg1","hello springMVC");
model.addAttribute("msg2","hello boys....");
return "second";
}
}
注意:使用这个注解需要开启mvc的注解功能,而开启mvc的注解功能需要在核心配置文件中添加:xmlns:mvc="http://www.springframework.org/schema/mvc"的规则
然后核心配置文件的配置如下
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 开启包扫描 -->
<context:component-scan base-package="cn.test.temp"></context:component-scan>
<!-- 开启springMVC注解模式 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
视图解析器second.jsp的代码:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<head>
<title>second</title>
</head>
<body>
${msg1} <br>
${msg2} <br>
<%=new Date().toLocaleString()%>
</body>
</html>
测试结果: