SpringMVC入门之注解式控制器

上面一篇写的是配置式的控制器现在已经不推荐使用了,其实注解式控制器和它的差不多只不过

更简洁而已!

1.还是在web.xml中进行配置DispatcherServlet

   <servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>


<param-name>contextConfigLocation</param-name>


<param-value>/WEB-INF/classes/spring-servlet.xml</param-value>


</init-param>


<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

2.在src下新建spring-servlet.xml并在其中配置注解HandleMapping,HandleAdpater和ViewResolver.

spring-servlet.xml


<?xml version="1.0" encoding="UTF-8"?>
<!-- Bean头部 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
    http://www.springframework.org/schema/tx   
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd  
    http://www.springframework.org/schema/mvc  
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">


<!-- Spring3.2注解HandlerMapping -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />


<!-- Spring3.2注解HandlerAdapter -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />


<!-- ViewResolver视图解析器的配置 -->
<bean
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" />
</bean>
<!--处理器-->
<bean class="com.iss.control.HelloWorldControl"></bean>


</beans>

3.编写控制器

package com.iss.control;


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


@Controller
// 或是@requestMapping 作用是将一个pojo声明为处理器
public class HelloWorldControl {
@RequestMapping(value = "/hello")
// 请求url到处理器功能处理方法的映射
public ModelAndView helloWorld() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg", "hello  world!");// 添加模型数据
modelAndView.setViewName("hello");// 设置逻辑视图名视图解析器会根据该名字解析到具体的页面在此demo中是hello.jsp
return modelAndView;// 返回模型数据和逻辑视图


}


}

4.编写视图

hello.jsp

  <body>
   ${msg }
  </body>

5.测试在浏览器地址栏输入

http://localhost:8080/项目名/hello

出现hello  world!证明你成功了!









SpringMVC入门之注解式控制器,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。