Spring MVC学习记录2

Spring MVC注解方式

  • 注解方式依赖于Spring的AOP包
  1. 复制chapter11并重命名为chapter12
  2. 编写Spring MVC的配置文件springmvc-config.xml,在其中添加注解扫描配置,并定义视图解析器。
  • 使用context:component-scan元素指定需要扫描的包。
  • 视图解析器:当Handler返回ModelAndView对象后,DispatcherServlet会去寻找视图解析器进行解析。自定义视图解析器可以简化逻辑视图名。在方法中返回的view路径只需要设置为“first”,视图解析器会自动的添加前缀和后缀形成完整路径“/WEB-INF/jsp/first.jsp”。
<?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-4.3.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-4.3.xsd
	">

	<!-- 制定需要扫描的包 -->
	<context:component-scan
		base-package="cn.edu.dgut.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>
  1. 编写Controller类
  • Controller不需要再实现Controller接口,只需在类上添加==@Controller==注释,Spring可以通过扫描找到该控制器类。
  • 找到该控制器类后,还需要知道控制器内部对每一个请求是如何处理的。@RequestMapping注释用于映射到一个请求(类)或者一个方法。
  • 请求处理方法可以有不同的返回类型,如:ModelAndView,String,viod等等
    • ModelAndView:可以添加Model数据,并指定视图。
    • String:可以跳转视图,但不能携带数据。
    • void:主要用在异步请求时,它只返回数据,不跳转视图。
  • 由于,ModelAndView未能实现视图和数据之间的解耦,所以在企业级开发中,方法的返回类型通常为String,通过Model参数携带数据。
package cn.edu.dgut.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

/**
 * 控制器类
 */
@Controller
//使请求路径添加一层“/hello”
@RequestMapping(value = "/hello")
public class FirstController {

	@RequestMapping(value = "/firstController")
	public String handleRequest(HttpServletRequest request, HttpServletResponse response,Model model) throws Exception {
		//向模型对象model中添加数据
		model.addAttribute("msg", "这是注解方式的Spring MVC!");
		//返回视图
		return "first";
	}

}

  1. 将该项目发布到Tomcat上,启动Tomcat,在浏览器中访问地址http://localhost:8080/chapter12/hello/firstController。
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值