In the first blog is mainly explained how to build and run the sample project framework spring; simplify the development in this article mainly on how to use the notes the way!
First, prepare papers ready -jar package
Not described in detail here on refer to a blog entry --spring3.1.1 explain a (non-annotated chapter) to prepare papers explain in
Second, the environment to build articles
1, added to the web.xml configuration file to keep up with a configuration code as a direct copy in the past on the line.
2, the configuration spring-mvc.xml, the focus is here
Key configuration is as follows:
1), if we use as a non-annotated way to create and access controller controller, we need to add the following configuration file in a spring-mvc.xml
<span style="white-space:pre"> </span><bean name="/hello" class="com.spring.mvc.HelloWorldController"/> <span style="font-family: Arial, Helvetica, sans-serif;">
2), so if we annotate the way you create and control access controller, we do not need to configure it spring-mvc.xml bean; however need to add the following configuration spring-mvc.xml:
<!-- 在com.spring.mvc包下寻找控制器组件 -->
<context:component-scan base-package="com.spring.mvc"></context:component-scan>
The role of the above configuration is to allow spring to automatically scan com.spring.mvc package following controller class (of course, when we create @Controller controller also need to add annotations to mark).
3. Create a package in the src com.spring.mvc below, then add the controller class: HelloWorldAnnocationController.java
package com.spring.mvc;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* 页面控制器
*
* @version 1.0 2015-02-11 下午05:39:25
*/
//使用注解@Controller声明该类是一个控制器
@Controller
@RequestMapping(value="helloWorldAnnocationController")
public class HelloWorldAnnocationController{
//使用注解@RequestMapping声明这个控制器处理index.html的请求
@RequestMapping("/hello")
public ModelAndView helloAnotherWorld( final HttpServletRequest request){
ModelAndView mv = new ModelAndView();
// 添加模型数据,可以是任意的POJO对象
mv.addObject("message", "Hello World!");
// 设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页面,然后就自动从WebContent/view/下面查找hello.jsp视图页面
mv.setViewName("hello");
//将model的数据交给文件名为helloSpringMVC,后缀名为vm(在applicationContext.xml里面设置)的文件显示
return mv;
}
}
4, add the following hello.jsp page view / directory
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
${message}
</body>
</html>
5, annotated version of the controller Access Controller:
Reproduced in: https: //my.oschina.net/mapsh/blog/598142