SSM-SpringMVC-14:SpringMVC中大话注解式开发基础--呕心沥血版

2023-05-11,,

 ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------

注解的基础我不再多啰嗦,百度一搜很多,很详细啊,我就讲一下SpringMVC中的注解入门

通过注解的方式定义一个处理器,它的命名空间,以及他们的方法访问路径,

@Contorller这个可以让一个普通类不用继承,不用实现任何东西就可以变成处理器,

简单来说@Contorller让你不用继承遗产(extends),不用自己拼搏(implement),就可以处理很多事情了

只需要在类上加上即可


/*注解定义处理器*/
@Controller
public class MyAController { 

}

呀,这个里面怎么没有要实现的东西啊,我该怎么做?

@ResquestMapping("/访问地址")

这个家伙,放在一个普普通通的方法上,没有别人给他的参数,什么他就成了能处理任务的处理方法了?

要不要这么神奇,事实上就是这样

    /*注解定义访问此方法路径*/
@RequestMapping("/dotwo")
public String doSecond() throws Exception { return "second";
} /*注解定义访问此方法路径*/
@RequestMapping("/doindex")
public String doIndex() throws Exception { return "index";
}

哇哦,这样就可以访问了吗?

错它还需要和框架进行交互的一个老家伙,他叫什么呢,就是context:component-scan包资源扫描器

下面我们就配置一道在核心配置文件。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:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--包扫描器-->
<context:component-scan base-package="cn.dawn.day10annotationcontroller"></context:component-scan>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean> </beans>

改web.xml的引用的xml为此xml时候,你的轻装小坦克-----处理器就可以执行了

需要注意的是,我的index.jsp和scond.jsp你有吗?没有的话,搞一个

访问路径我给一下:http://ip地址:tomcat端口号/项目名/方法上@ResquestMapping("/访问地址")这个中填的访问地址

处理器中的处理方法啊,如果多个处理器中的方法上的注解中的访问地址冲突,互相影响了怎么办啊

小兵打架,打出麻烦,自己解决不掉,找自己的领导帮忙啊,所以处理方法解决不掉,处理器来啊

@RequestMapping("/访问地址")

同样也可以用在处理器类上,这样多了一级路径,麻烦解决了

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Created by Dawn on 2018/3/24.
*/
/*注解定义处理器*/
@Controller
/*定义处理器访问路径*/
@RequestMapping("/controller1")
public class MyAController { /*注解定义访问此方法路径*/
@RequestMapping("/dotwo")
public String doSecond() throws Exception { return "second";
} /*注解定义访问此方法路径*/
@RequestMapping("/doindex")
public String doIndex() throws Exception { return "index";
}
}

访问路径我再给一下:http://ip地址:tomcat端口号/项目名/处理器类上@ResquestMapping("/访问地址")这个中填的访问地址/方法上@ResquestMapping("/访问地址")这个中填的访问地址

SSM-SpringMVC-14:SpringMVC中大话注解式开发基础--呕心沥血版的相关教程结束。

《SSM-SpringMVC-14:SpringMVC中大话注解式开发基础--呕心沥血版.doc》

下载本文的Word格式文档,以方便收藏与打印。