springMVC初学简单例子

新建web项目,保留web.xml.

配置web.xml文件(/WEB-INF/下):

<?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">

<servlet>
<servlet-name>springMVCTest</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>springMVCTest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

 

配置springmvc.xml文件(在/src下 classpath即为/src)

<?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">

<!-- 自动扫描controller包下的所有类,扫描指定的包中的类上的注解使其认为是spring mvc的控制器 路径即为类路径 -->
<context:component-scan base-package="com.test.springmvc"></context:component-scan>
<!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 根据控制器返回的字符串拼接成jsp路径:/WEB-INF/jsp/xx.jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value="/WEB-INF/jsp/"></property>
<property name = "suffix" value = ".jsp"></property>
</bean>
</beans>

导入jar包

编写控制器

package com.test.springmvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
//@Controller表示在tomcat启动的时候,把这个类作为一个控制器加载到Spring的Bean工厂,如果不加,就是一个普通的类,和Spring没有半毛钱关系。
//这也是为什么,我们只是写了Controller,但是从来没有在一个地方new这个Controller的原因,因为在Web容器启动的时候,这个Controller已经被Spring加载到自己的Bean工厂里面去了。
public class Show {
@RequestMapping("/welcome")
public String welcome() {

}
}

 

编写welcome.jsp页面(在/WEB-INF/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>
欢迎!
</body>
</html>

 

启动:

http://localhost:8080/springMVCTest/welcome

 return "welcome"这里的welcome指的是welcome.jsp,只不过省略了扩展名

 

https://www.cnblogs.com/admol/articles/4199546.html

posted on 2018-07-16 15:44  IT初学者骂蕾  阅读(210)  评论(0)    收藏  举报

导航