您的位置:首页 > 编程语言 > Java开发

SpringMVC学习之注解方式的配置及启用

2017-09-13 17:53 447 查看
之前学习SpringMVC写的代码都是用的老的XML配置方式,这次开始用注解方式,SpringMVC从2.5版本就开始支持注解配置方式,3.0之后的版本就基本已经完善了~

环境:

SpringMVC:SpringMVC4(SpringMVC4.3)

IDE:IDEA17

JDK:1.7

Tomcat:7.0

首先,还是创建一个SpringMVC的工程。

我是继续用上次的工程来修改的。

首先修改dispatcher-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: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="Controller" />
<!-- 添加注解驱动 -->
<mvc:annotation-driven />
<!-- 静态资源访问 -->
<mvc:resources location="/img/" mapping="/img/**"/>

<!--所有的访问都统一先由InternalResourceViewResolver类处理-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--定义跳转的文件的前缀(jsp文件所在目录)-->
<property name<
9e77
/span>="prefix" value="/" />
<!-- 定义跳转的文件的后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>


这个是SpringMVC4的注解配置内容

再修改index.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>hello world Controller</title>
</head>
<body>
hello world!
<br>
${zx}
</body>
</html>


然后新建一个NewHello.java文件

package Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
* Created by seekhow on 2017/7/1.
*/
@Controller
public class NewHello  {
@RequestMapping(value = "/NewHello",method = RequestMethod.GET)
public ModelAndView show() {
System.out.println("OK");
return new ModelAndView("index","zx","show");
}
}




图中黄色部分就是注解部分,可以通过注解访问到这个Controller

并且在 @RequestMapping(value = “/NewHello”,method = RequestMethod.GET)中配置了访问路径:/NewHello

我们访问试试:

输入:http://localhost:8888/NewHello



访问成功
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: