eclipse中完成SpringMVC的第一个程序

一.首先,在eclipse中创建一个web项目

二.然后导入Springweb的依赖包:
在这里插入图片描述
三.在web中配置我们的前端控制器

<?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" version="3.0">
  <display-name>SpringStudy</display-name>
  
  <servlet>
    <servlet-name>springMvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
</web-app>

四.在WEB-INF路径下建立一个Spring Bean Configuration File文件名为:
web.xml配置的servlet名称-servlet
在这里插入图片描述

此文件的作用就是配置控制器的位置以及配置视图解析器:

<?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.yanjiadou.test"></context:component-scan>

<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/view/"></property>
   <property name="suffix" value=".jsp"></property>
</bean>
</beans>

五.然后我们就要编写控制器了:
在com.yanjiadou.test包中编写:

package com.yanjiadou.test;

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

@Controller//表示此类作为控制器
public class TestController {

	@RequestMapping(value="hello")//表示名为hello的请求响应
	public String hello()
	{
		System.out.println("Hello world");
		return "success";
	}
}

六.现在来编写视图:
在这里插入图片描述
index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="hello">hello</a>
</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>welcome to my world</h1>
</body>
</html>

OK完成:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/c1776167012/article/details/106474404