这部分接(一)的入门程序,是在入门程序的基础上添加基于注解的开发部分
基于实现接口的开发属于过去常用的了, 现在注解开发要更加方便和快捷
基本注解:@Controller @RequestMapping()
开发步骤:1.配置基础扫描的包,否则注解不会生效
2.在指定的类上加上@Controller 注解
3.添加@RequstMapping()类似(一)中的Controller的名字
一.springmvc-servlet.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.xsd
">
<!--配置一个注解扫描的包-->
<context:component-scan base-package="com.yzy.controller"></context:component-scan>
<!--配置一个视图解析器
常用的内部资源视图解析器
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--1.前缀-->
<property name="prefix" value="/jsp/"></property>
<!--2.后缀-->
<property name="suffix" value=".jsp"></property>
</bean>
<bean class="com.yzy.controller.HelloController" name="/helloController"></bean>
<!--这个bean指向的modelandview的name就充当了请求的url-->
</beans>
与上一部分有出入的在于下边的这三个部分,最后一个是配置扫描的包
二.Controller部分
package com.yzy.controller;/*
@author fishgoudan
@date 2019/9/4 - 11:19
*/
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
//不需要继承任何类或者实现任何的接口
@Controller
public class MyTestController {
@RequestMapping("/test")
public String myTest(Model model){
model.addAttribute("mode","modeler");
// 这里return的就是我们的那个viewName
// 此时去的事/jsp/test.jsp页面
return "test";
}
}
与(一)区别的地方在于:
1.不需要再实现Controller接口,类外加上@Controller,方法外加入@RequestMapping("/")括号中的内容就是访问Contraller的url
2.不再需要ModelAndView了,需要存放数据就在函数的形参处写上Model,框架会自动配置相关内容,不用担心。
3.return的内容实际上就是页面的viewName,这一点比较重要。
tip:实际上的jsp页面的物理路径 = 前缀 + viewName + 后缀
四.jsp显示部分
这里的jsp要记得,名字和Controller最后return的Stirng要一致,因为原因上面的tip写的很清楚,所以在目录下的jsp目录下创建test.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
这是注解我的${mode}
</body>
</html>
五.结果
这是加上了@Controller和@RequestMapping() 两个注解后的入门程序,使用注解以后才有spring的感觉呀!
未完待续