工欲善其事,必先利其器,要想使用SpringMVC自然要先把配置文件写好。
1.web.xml文件
新建web项目之后webRoot目录下面会有一个web.xml文件,我们先来对其进行配置。
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc-servlet.xml
1
springmvc
/
这里定义了一个servlet,servlet名自己取后面要用到,class固定的,不可改变。
然后就是初始化init后要加载的xml文件,默认名为servlet名-servlet.xml,这个是要加载到
webroot-webinf-classes下的,我们将其放到项目目录下的src目录,它会自动加载到classes目录。
于是我们在src下新建一个xxx-servlet.xml文件
2.springmvc-servlet.xml
这里配置上面所提到的servlet名-servlet.xml文件,放在项目目录下的src目录!!!
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
鉴于annotation开发的高效率,这里一致使用annotation。
上面视图渲染器定义,如果要访问项目名/hello实际上就是访问项目名/WEB-INF/jsp/hello.jsp,这样是符合
编程开发的“约定优于配置”原则。就像数据库有个表student,那么它的持久化类就应该是Student,我想在
浏览器访问项目下的hello页面,你就应该帮我指向项目名/WEB-INF/jsp/目录下的hello.jsp页面。
3.创建JSP页面
WEB-INF/jsp/目录下创建hello.jsp页面,随便在body中添加几句话。
4.创建Controller类
@Controllerpublic classController {
@RequestMapping("/eco")publicString hello(){return "hello";
}
@RequestMapping("/hi")publicModelAndView show(){
ModelAndView mv=newModelAndView();
mv.addObject("msg", "world");
mv.setViewName("hi");returnmv;
}
}
类名自定义,下面看注解的意思
@Controller注解,声明这个类是一个控制器Controller,
@RequestMapping("/hello") 这个注解当浏览器访问项目名/eco时,跳转到(return)到hello.jsp这个页
面,也可以是其他页面。下面一个Mapping注解呢,不仅实现了页面跳转(hi.jsp),还设置了一个msg
变量,可以在hi.jsp中用el表达式来调用它的值;hello ${msg} 输出 hello world。
5.测试
接下来在浏览器输入localhost:8080/webmvc/hi
------------------------------------------------------------------------------------------------------------------------------------------------------------------