第一个项目——HelloWorld
1、准备步骤:
①新建web项目,复制jar包
②配置Spring
③配置Web应用在启动时自动创建Spring容器
④为第三步的Spring提供配置文件⑤配置web.xml文件,增加DispatcherServlet,这个是SpringMVC的前端控制器。
⑥增加一个对应的【servletName-servlet.xml】文件,这个文件也是Spring配置,但是属于模块专用配置文件,往往只是配置Action(Controller)。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<!-- 扫描Action(控制器)所在的包 -->
<context:component-scan base-package="cony.action"/>
<!-- 激活SpringMVC注解支持 -->
<mvc:annotation-driven/>
</beans>
⑦配置日志记录
⑧写控制器(Controller、Action),接收浏览器的请求
i. 类上面需要使用 @Controller 注解,表示这个是一个控制器,并且之前应在模块的Spring配置文件里面配置扫描。
ii.在方法上面,需要使用 @RequestMapping 注解,表示这个方法,映射到一个URL。请求的时候根据URL找到方法来进行执行@Controller
public class UserAction {
@RequestMapping
public String list(){
return "/test.jsp";
}
}
⑧写一个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>
Hello World!
</body>
</html>
⑨项目架构
2、测试