基于注解的Spring MVC应用

1.创建Web项目,引入Jar包

2.在配置文件中添加注解扫描配置springmvc-config.xml,并定义视图解析器(这个代码在eclipse会报错,但是不影响程序运行)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation=" 
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-4.3.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"
 default-autowire="byName">
        <context:component-scan base-package = "com.itheima.controller"/>
        <bean id = "viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name = "prefix" value = "/WEB-INF/jsp/"/>
        <property name = "suffix" value = ".jsp"/>
        
        </bean>
        </beans>

3.编写FirstController类,在类和方法上添加相应注解

package com.itheima.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping(value = "/hello")
public class FirstController {
	@RequestMapping(value = "/firstController")
	public String handleRequest(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{
		
		model.addAttribute("msg", "This is my second programe");
		return "first";
	}

}

4.部署并启动项目,访问地址http://localhost:8080/chapter12/hello/firstController

如果页面报错,则关闭eclipse,在打开eclipse,重新运行即可。

发布了376 篇原创文章 · 获赞 172 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/Eider1998/article/details/104179293