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

使用注解开发Spring mvc

2017-04-09 16:26 302 查看

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>springmvc_annocatotion</display-name>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc.xml</param-value>
意味着mvc.xml在类路径下,

mvc.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:p="http://www.springframework.org/schema/p"
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">
<!-- 配置视图渲染器 -->
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<!-- 将视图名 渲染后视图的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 渲染后视图的后缀 -->
<property name="suffix" value=".jsp" />
<!-- 例:视图名为:hello 渲染后:/WEB-INF/jsp/hello.jsp 该页面 -->
</bean>
<!-- 注解扫描 -->
<context:component-scan base-package="springmvc.annocation.controller"/>
</beans>

HelloController.java

不再实现接口,用注解的方法
@RequestMapping("/hello")


package springmvc.annotation.controller;

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

//使用注解开发
@Controller
public class HelloController {
@RequestMapping("/hello")
public ModelAndView hello(HttpServletRequest req, HttpServletResponse resp) {
ModelAndView mv = new ModelAndView();
// 封装要显示到视图中的数据
mv.addObject("msg", "hello springmvc annocation");
// 视图名
mv.setViewName("hello");
return mv;

}

}

Hello.jsp

<br> EL表达式:${msg}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: