SpringMVC——Hello world程序的步骤:

创建一个Web工程
在这里插入图片描述
需要导入的jar包
commons-logging-1.1.3.jar
log4j-1.2.17.jar
spring-aop-4.3.18.RELEASE.jar
spring-beans-4.3.18.RELEASE.jar
spring-context-4.3.18.RELEASE.jar
spring-core-4.3.18.RELEASE.jar
spring-expression-4.3.18.RELEASE.jar
spring-web-4.3.18.RELEASE.jar
spring-webmvc-4.3.18.RELEASE.jar

在config源码目录下创建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"
	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.3.xsd">

	<!-- 
		配置包扫描
	 -->
	<context:component-scan base-package="com"></context:component-scan>

</beans>

在config源码目录下创建log4j.properties日记配置文件:

# Global logging configuration
log4j.rootLogger=INFO, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

到web.xml中去配置前端控制器:

<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 
			contextConfigLocation初始化参数,用来配置SpringMVC的配置文件路径
		 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<!-- 
			load-on-startup 标签 配置当Web工程启动的时候。就创建Servlet程序实例。
		 -->
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- 
		servlet-mapping 标签 配置Servlet程序的访问地址
	 -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<!-- 
			/ 表示将所有请求都转交给SpringMVC处理
		 -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>

配置Controller控制器(Controller控制器是用来处理请求的类,里面每个方法处理一个请求)

@Controller
public class HelloController {

	/**
	 * hello方法处理用户的请求<br/>
	 * @RequestMapping("/hello") 表示给当前方法配置一个访问地址。<br/>
	 * 	/hello 表示http://ip:port/工程名/hello <br/>
	 */
	@RequestMapping("/hello")
	public String hello() {
		System.out.println("spring mvc 的 hello world!");
		/**
		 * 返回值表示转发到 http://ip:port/工程名/ok.jsp路径
		 */
		return "/ok.jsp";
	}
	
}

需要的jsp页面:

index.jsp页面

	<body>
		<a href="http://localhost:8080/spring_mvc_hello/hello">hello请求</a>
	</body>

ok.jsp页面

	<body>
		请求完成!!!
	</body>

猜你喜欢

转载自blog.csdn.net/No_mingzi/article/details/92652485