上个笔记的示例中,控制器实现了Controller接口,并且需要在spring配置文件中进行配置才能访问到控制器,这样做显然很麻烦,已经不符合我们现在框架的优势了。下面我们直接通知注解实现控制器,简单高效。
1、修改在WEB-INF下的配置文件springmvc-config.xml
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- spring自动扫描base-package下面的包或子包下面的java文件 -->
<context:component-scan base-package="kshon.controller" />
<!-- 配置annotation类型的处理映射器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<!-- 配置annotation类型的处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>
</beans>
2、编写控制器,在kshon.controller包下新建AnnotationController类,写入代码:
package kshon.controller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/*
* 基于注解的控制器
* 无需实现任何接口,并且可以同时处理多个请求动作
*/
@Controller
public class AnnotationController {
private static final Log logger = LogFactory.getLog(HelloController.class);
@RequestMapping(value="/annotation")
public ModelAndView annotation(){
logger.info("annotation方法被调用");
ModelAndView mav = new ModelAndView();
mav.addObject("message","基于注解的控制器");
mav.setViewName("WEB-INF/content/welcome.jsp");
return mav;
}
}
在这里可以看到,只需要在类前添加一个@Controller就代表此类是一个控制器,在需要访问的方法前面添加注解@RequestMapping(value="name")即可,注意参数name就是你要访问的名称,这里是annotation
3、在WEB-INF/comtent下的welcome.jsp页面视图不变:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
${requestScope.message }
</body>
</html>
现在启动tomcat,在浏览器中输入localhost:8080/SpringMVC/annotation即可访问成功