声明:此博文为个人学习总结,如有错误疏漏之处,欢迎各位批评指正!
本文主要介绍springmvc的简单搭建,即实现一个简单的hello world
- 新建一个web项目(也可以是maven项目)
导入springmvc的最小依赖包
在web.xml文件中配置springmvc
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>springmvcSourceAnalysis</display-name>
<servlet>
<servlet-name>SourceAnalysis</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置springmvc配置文件的位置 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 设置启动加载 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SourceAnalysis</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
4.创建springmvc的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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<mvc:annotation-driven/>
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="net.csdn.handler"/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
5.创建Controller
package net.csdn.handler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
private final Log logger = LogFactory.getLog(HelloController.class);
@RequestMapping("hello")
public String hello(Model model){
logger.info("hello method had executed .");
model.addAttribute("message","hello springmvc !!!");
return "hello";
}
}
6.创建视图
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'hello.jsp' starting page</title>
</head>
<body>
${message}
</body>
</html>
7.部署、启动服务器
8.访问
至此,一个简单点的springmvc环境已经搭建成功。
项目结构如下图:
搭建此环境的目的仅仅是为了之后的源码解析,所以内容不免有纰漏疏忽之处,望海涵。