JavaEE框架——Springmvc入门(注解URL核心类详解、文件上传和下载)、和Spring的整合

来源:互联网 发布:云计算怎么开公司啊 编辑:程序博客网 时间:2024/06/03 22:37

一、简介:

Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,从而在使用Spring进行WEB开发时,可以选择使用Spring的SpringMVC框架或集成其他MVC开发框架,如Struts1,Struts2等

优点:它是一个典型的教科书式的mvc构架,而不像struts等都是变种或者不是完全基于mvc系统的框架,对于初学者或者想了解mvc的人来说我觉得 spring是最好的,它的实现就是教科书!第二它和tapestry一样是一个纯正的servlet系统,这也是它和tapestry相比 struts所没有的优势。而且框架本身有代码,看起来容易理解。


二、SpringMVC几个核心类:

  • 控制器核心类:org.springframework.web.servlet.DispatcherServlet - 配置web.xml
  • 加载配置文件核心类:org.springframework.web.context.ContextLoaderListener – spring的配置文件
  • 处理url影射核心类:org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping-根据bean的名称请求一个bean. spring的配置文件- /abc
  • 处理视图资源核心类:org.springframework.web.servlet.view.ResourceBundleViewResolver  returnhello – 决定返回的字符串由哪一个页面来显示。
  • 处理注解URL核心类:org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping- 用于识别@RequestMapping注解。使用了上面的类,Controller还是需要配置的。<context:component-scan package=“cn.itcast”/>用于替代上面的类。
  • 方法动态调用核心类org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver
  • 文件上传核心类:org.springframework.web.multipart.commons.CommonsMultipartResolver

三:用Spring处理Web请求-Spring的MVC



四、几个核心类演示

            1.DispatcherServlet详解:

  •  DispatcherServletSpringMVC的核心类,它就是一个Servlet.此类默认读取WEBINF/[servlet-name]-servlet.xml配置文件。
  • 重要说明:DispatcherServlet可以多次配置到web.xml中,它们将会读取自己的配置文件,但不会共享Bean.如果希望设置一些共享的Bean应该配置ContextLoaderListener来读取Spring的配置文件。

配置DispatcherServlet

1.在web.xml中加入servlet,namespac e默认可以不写,如果写了,就可以随便改名字,不一定要写出servlet-name]-servlet.xml,这里只是为了规范

        <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>            classpath:beans.xml,             </param-value>    </context-param>    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <servlet>        <servlet-name>springmvc</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>namespace</param-name>            <param-value>springmvc-servlet</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>springmvc</servlet-name>        <url-pattern>/sp/*</url-pattern>    </servlet-mapping>

2.在WEB-INF目录下写上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"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"><!-- Cotroller-bean配置在当前文件,可以不用配映射bean<bean name="/hello" class="cn.hncu.one.HelloControler"></bean> --></beans>

2.DispatcherServlet

DispatcherServlet会在WEB-INF目录下默认加载一个资源文件,名为:springmvc-servlet.xml文件。
如果配置信息有很多,此文件将会变得非常笨重。原则上,我们反倒是建议你将应用上下文分散到多个配置文件中去。
为此,我们必须要载入:上下文载入器ContextLoaderListener,如下:
(需要说明的是:在DispatcherServlet的加载的配置文件与通过ContextLoaderListener加载的配置文件,将不会拥有互相的访问权限

因此在web.xml要加入它

<context-param><param-name>contextConfigLocation</param-name><param-value>    classpath:beans.xml, </param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

3.BeanNameUrlHandlerMapping

根据bean的名称请求一个bean. spring的配置文件

在配置文件springmvc-servlet.xml配置请求bean则不需要导入BeanNameUrlHandlerMapping这个类

而在spring的配置文件beans.xml则要导入

<!--  Cotroller-bean配置在当前文件,必须要配映射bean(处理url影射核心类) 处理url影射核心类: org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping      

4.声明视图解析器:viewResolver

  • Springview层是通过视图解析器来完成的。
  • Spring中包含很多视图解析器,以下是经常使用,且比较灵活的一个解析器:
  • ResourceBundleViewResolver,是通过加载外部的资源文件来解析目录视图的解析器。


<!--转发时必须要配: 处理视图资源核心类 --><bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver"><property name="basenames"><!-- 配置文件为: classpath: springmvc.properties --><value>springmvc</value></property><property name="defaultParentView" value="hncu"></property></bean>

默认会在classpath目录下查找springmvc.properties资源文件

springmvc.properties

#配置一个字符串指向一个页面,配置文件中至少应该包括两项内容:#1.指定返回的是什么页面(jstlJSP,pdf,doc)#2.指定包装页面路径##如果一个字符串页面没有配置class,则它直接使用父View的hncu.(class)=org.springframework.web.servlet.view.JstlViewhncu.url=/jsps/hello.jsp

5.节点调用:ParameterMethodNameResolver

beans.xml加入

<!-- 多方法动态调用核心类(现在过时了,建议采用注解)  --><bean id="methodResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver"><property name="defaultMethodName" value="excute"></property><property name="paramName" value="method"></property></bean><!-- 访问时地址为http://localhost:8080/springmvcWeb/sp/multi?method=? --><bean name="/multi" class="cn.hncu.two.MultiController"><property name="methodNameResolver" ref="methodResolver"></property></bean>

MulitiController.java
package cn.hncu.two;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.mvc.multiaction.MultiActionController;import cn.domain.User;//API中建议采用注解的方式调用多方法Controllerpublic class MultiController extends MultiActionController {//空参方法是不行的---反模式public void one(){System.out.println("这是第一个方法...");}//必须至少带参数request和reponse,方法的返回值类型可以任意public void two(HttpServletRequest request,HttpServletResponse response) throws Exception{System.out.println("这是第二个方法...");}public String three(HttpServletRequest request,HttpServletResponse response){System.out.println("这是第三个方法...");return "hncu";}public  ModelAndView four(HttpServletRequest request,HttpServletResponse response, User user){ModelAndView mv = new ModelAndView();mv.setViewName("hncu");mv.addObject("user", user);return mv;}}


6.实现处理多请求的处理类MultiActionController

因为注解的引入,现在已经不建议使用了

beans.xml配置

<!-- 多方法动态调用核心类(现在过时了,建议采用注解)  -->    <bean id="methodResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">        <property name="defaultMethodName" value="excute"></property>        <property name="paramName" value="method"></property>    </bean><!-- 访问时地址为http://localhost:8080/springmvcWeb/sp/multi?method=? --><bean name="/multi" class="cn.hncu.two.MultiController"><property name="methodNameResolver" ref="methodResolver"></property></bean>

这里面的方法可以任意的书写,但必须接收Request,resp两个参数。同时必须注入,接收由什么方法处理请求!

MultiController.java

package cn.hncu.two;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.mvc.multiaction.MultiActionController;import cn.domain.User;//API中建议采用注解的方式调用多方法Controllerpublic class MultiController extends MultiActionController {//空参方法是不行的---反模式public void one(){System.out.println("这是第一个方法...");}//必须至少带参数request和reponse,方法的返回值类型可以任意public void two(HttpServletRequest request,HttpServletResponse response) throws Exception{System.out.println("这是第二个方法...");}public String three(HttpServletRequest request,HttpServletResponse response){System.out.println("这是第三个方法...");return "hncu";}public  ModelAndView four(HttpServletRequest request,HttpServletResponse response, User user){ModelAndView mv = new ModelAndView();mv.setViewName("hncu");mv.addObject("user", user);return mv;}}





6.处理注解URL核心类DefaultAnnotationHandlerMapping

首先在beans.xml配置springmvc的注解bean(Controller)

 <context:component-scan base-package="cn.hncu"></context:component-scan>

标签会实现自动扫描“cn.hncu”包中含注解的Controller,这样我们以后写的含注解的Controller-bean就不需要在配置文件中配置了
  


<?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"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"><!--  Cotroller-bean配置在当前文件,必须要配映射bean(处理url影射核心类) --><bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>    <!--转发时必须要配: 处理视图资源核心类 --><bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver"><property name="basenames"><list><!-- 配置文件为: classpath: hncu.properties --><value>hncu</value></list></property><property name="defaultParentView" value="hncu"></property></bean><!-- 以下讲解处理注解URL核心类,该类的配置是为了能够识别基于注解的Controller类  --><bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean><!--下面这个标签会实现自动扫描“cn.hncu”包中含注解的Controller,这样我们以后写的含注解的Controller-bean就不需要在配置文件中配置了  --><context:component-scan base-package="cn.hncu"></context:component-scan></beans>


类注解

  1. @Controller//告诉SpringMVC控制器,当前类是一个Controller
  2. @RequestMapping(value="/anno")//加该项后,访问路径的方法名前得加上“/anno”这段路径

方法注解@RequestMapping(value="/one")

                                指定访问路径为: http://localhost:8080/springmvcWeb/sp/one(没加@RequestMapping(value="/anno"))
                                指定访问路径为: http://localhost:8080/springmvcWeb/sp/anno/one(没加@RequestMapping(value="/anno"))


写了@RequestMapping注解的方法必须有返回值


详细演示:

  • 方法:sayhi
@RequestMapping(value="/sayhi",method={RequestMethod.GET})//默认是post和get两种方式都行    //指定访问路径为:localhost:8080/springmvcWeb2/sp/sayhi?name=Jack&age=23,必须加上name和age属性(要想不加,则要加上value="",required=false)    public String sayhi(@RequestParam("name") String name,@RequestParam(value="age",required=false) Integer age){//        System.out.println("name:"+name+"   age:"+age);        return "hncu";    }

index.jsp

 <form action='<c:url value="/sp/sayhi"></c:url>' method="post">   姓名:<input type="text" name="name"><br/>         年龄:<input type="text" name="age"><br/>   <input type="submit" value="提交">   </form>

  • 方法:sayhi2//从路径上给变量
@RequestMapping(value="/sayhi2/{name}/{age}")//指定访问路径为:localhost:8080/springmvcWeb2/sp/sayhi2/{?}/{?}必须加上name和age属性public String sayhi2(@PathVariable(value="name") String name,@PathVariable(value="age") Integer age){//System.out.println("name:"+name+"   age:"+age);return "hncu";}

  • 方法:s1

下面的params限定请求路径中必须带参数name但不能带参数age,还可用“age!=0”。参数“headers”可以限定请求头信息,
    如下面的referer可以防盗链,请求头中还可写如:content-type=application以限制表单提交可以但地址栏提交不行

@RequestMapping(value="/s1",params={"name","!age"},headers={"referer=http://localhost:8080/springmvcWeb2/","content-type=application/x-www-form-urlencoded"})public ModelAndView s1(){System.out.println("s111111");ModelAndView mv=new ModelAndView("hncu");mv.addObject("name", "张三");return mv;}
index.jsp
<a href="<c:url value='/sp/s1?name=abc'/>" >请求s1()方法</a>   <form action='<c:url value="/sp/s1"></c:url>' method="post">   姓名:<input type="text" name="name"><br/>     <!-- 年龄:<input type="text" name="age"><br/> -->   <input type="submit" value="提交">   </form>
方法:s2

&可以使用原装的HttpServletRequest和HttpServletResponse对象

@RequestMapping(value="/s2")public String s2(HttpServletRequest request,HttpServletResponse response) throws Exception{System.out.println("request"+request);//拿到的和tomcat的一样System.out.println("response"+response);return "hncu";}

方法:s3

可以直接帮我们把请求参数封装成JavaBean

    @RequestMapping(value="/s3")    public String s3(User user){        System.out.println(user);        return "hncu";    }
index.jsp
<form action='<c:url value="/sp/s3"></c:url>' method="post">       姓名:<input type="text" name="name"><br/>         年龄:<input type="text" name="age"><br/>         地址 :<input type="text" name="addr.city"><br/>   <input type="submit" value="提交">   </form>
因为有乱码在web.xml中配置一个字符过滤器

web.xml

 <!-- 配一个如下过滤器以解决(SprngMVC的)中文乱码 --><filter><filter-name>charset</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param></filter><filter-mapping><filter-name>charset</filter-name><!-- 拦截指定的Spring分配器 --><servlet-name>springmvc</servlet-name></filter-mapping>



方法:s4

修改post请求方法为put

@RequestMapping(value="/s4/{name}",method=RequestMethod.PUT)public String s4(@PathVariable(value="name") String name,@RequestParam(value="age") Integer age){System.out.println("name:"+name+",age:"+age);return "hncu";}

index.jsp
  <form action='<c:url value="/sp/s4/wja"></c:url>' method="post">   <input type="hidden" name="_method" value="PUT"/><!-- 后台接收的是put方法因此要转 -->   姓名:<input type="text" name="name"><br/>         年龄:<input type="text" name="age"><br/>          地址 :<input type="text" name="addr.city"><br/>    <input type="submit" value="提交">   </form>

web.xml
<!-- 配一个如下过滤器以帮且我们把浏览器请求转化成PUT方式的请求 -->     <filter>         <filter-name>method</filter-name>         <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>     </filter>     <filter-mapping>         <filter-name>method</filter-name>         <!-- 拦截指定的Spring分配器 -->         <servlet-name>springmvc</servlet-name>     </filter-mapping>




方法:s5

可以绑定其他数据

@RequestMapping(value="/s5")//请求路径:http://localhost:8080/springmvcWeb2/sp/s5?name=jack&age=30public String s5(HttpSession s,@RequestHeader(value="accept") String accept,@CookieValue("JSESSIONID") String sessionId, User user){System.out.println("s:"+s);System.out.println("accept:"+accept);System.out.println("sessionId:" + sessionId);System.out.println("user: "+ user);return "hncu";}

方法:s6

可以绑定数组、集合等类型的请求参数

@RequestMapping(value="/s6")    public String s6(@RequestParam("h") String[] hobys, @RequestParam("l") List<String> l){        System.out.println(Arrays.toString(hobys));        System.out.println("l:" + l);        return "hncu";    }

index.jsp
<form action='<c:url value="/sp/s6"></c:url>' method="post">   爱好:   <input type="checkbox" name="h"  value="basketball">篮球<br/>   <input type="checkbox" name="h" value="swing">游泳<br/>   <input type="checkbox" name="h" value="Tennis">网球<br/>           喜爱程度:   <input type="checkbox" name="l"  value="70">篮球<br/>   <input type="checkbox" name="l" value="20">游泳<br/>   <input type="checkbox" name="l" value="10">网球<br/>           <input type="submit" value="提交">   </form>

 相关配置文件
 
<?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></display-name><context-param><param-name>contextConfigLocation</param-name><param-value>    classpath:beans.xml, </param-value></context-param> <!-- 配一个如下过滤器以解决(SprngMVC的)中文乱码 --><filter><filter-name>charset</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param></filter><filter-mapping><filter-name>charset</filter-name><!-- 拦截指定的Spring分配器 --><servlet-name>springmvc</servlet-name></filter-mapping> <!-- 配一个如下过滤器以帮且我们把浏览器请求转化成PUT方式的请求 --> <filter> <filter-name>method</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>method</filter-name> <!-- 拦截指定的Spring分配器 --> <servlet-name>springmvc</servlet-name> </filter-mapping><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>namespace</param-name><param-value>springmvc-servlet</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>/sp/*</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app><span style="font-size:12px;"></span>
beans.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"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"><!-- Cotroller-bean配置在当前文件,必须要配映射bean(处理url影射核心类) 处理url影射核心类: org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping --><beanclass="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean><!--转发时必须要配: 处理视图资源核心类 --><bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver"><property name="basenames"><!-- 配置文件为: classpath: springmvc.properties --><value>springmvc</value></property><property name="defaultParentView" value="hncu"></property></bean><!-- 以下讲解处理注解URL核心类,该类的配置是为了能够识别基于注解的Controller类 --><bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean><!-- <bean class="cn.hncu.anno.AnnoOneController"></bean> --><!--下面这个标签会实现自动扫描“cn.hncu”包中含注解的Controller,这样我们以后写的含注解的Controller-bean就不需要在配置文件中配置了  --><context:component-scan base-package="cn.hncu"></context:component-scan></beans>



springmvc.properties
hncu.(class)=org.springframework.web.servlet.view.JstlViewhncu.url=/jsps/hello.jspabc.url=/jsps/hello.jsp
springmvc-servlet.xml因为跟beans.xml都是spring的产品,共有工作空间,所有我把bean都写到beans.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"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"><!-- Cotroller-bean配置在当前文件,可以不用配映射bean<bean name="/hello" class="cn.hncu.one.HelloControler"></bean> --></beans>


7.文件上传核心类:org.springframework.web.multipart.commons.CommonsMultipartResolver
需要的jar包:spring-web-4.3.2.RELEASE.jar,commons-io.jar,commons-fileupload.jar
beans.xml配置
<span style="font-size:12px;"><!-- 文件上传核心类: 用于文件上传的解析(把file类型参数自动封装成MultipartFile对象), 坑:必须配id --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean></span>

文件下载

//演示文件下载@RequestMapping(value="/download")public void download(OutputStream out,HttpServletResponse resp,HttpSession session) throws IOException{resp.setContentType("application/force-download");//设响应头: 告诉浏览器用下载程序来读取当前的流数据resp.setHeader("Content-Disposition","attachment;filename=你.txt");Streams.copy(new FileInputStream(session.getServletContext().getRealPath("/download/a.txt")), out, true);//true为关流}

index.jsp
 <a href="<c:url value='/sp/download'/>" >文件下载</a>

文件上传

//演示文件上传(单个)@RequestMapping(value="/upload")public String upload(@RequestParam(value="file") MultipartFile file,HttpServletRequest req) throws IOException{//利用Streams//不能用req.getInputStream()Streams.copy(file.getInputStream(), new FileOutputStream(req.getServletContext().getRealPath("/upload/"+file.getOriginalFilename())), true);//true为关流return "hncu";}//演示文件上传(单个)@RequestMapping(value="/upload2")public String upload2(@RequestParam(value="file") List<MultipartFile> files,HttpServletRequest req) throws IOException{for(MultipartFile file:files){Streams.copy(file.getInputStream(), new FileOutputStream(req.getServletContext().getRealPath("/upload/"+file.getOriginalFilename())), true);//true为关流}return "hncu";}


index.jsp


<form action='<c:url value="/sp/upload"></c:url>' method="post" enctype="multipart/form-data">   文件:<input type="file" name="file">   <input type="submit" value="提交">   </form>   <form action='<c:url value="/sp/upload2"></c:url>' method="post" enctype="multipart/form-data">   文件1:<input type="file" name="file">   文件2:<input type="file" name="file">   文件3:<input type="file" name="file">   <input type="submit" value="提交">   </form>






如果想要把SpringMvc和spring整合起来使用
那么在前面的基础上,利用注解功能就可以解决,也就是说Controller中不中需要在理由bean去注入(IOC),直接通过注解功能就可以实现控制反转,前提是使用SpringMvc框架

使用如下
StudController.java
package cn.hncu.stud.controller;import javax.annotation.Resource;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import cn.hncu.domain.User;import cn.hncu.stud.service.IStudService;@Controllerpublic class StudController {@Resource(name="studService")private IStudService service=null;@RequestMapping(value="studSave",params={"name"})private String save(User user){System.out.println("come");service.save(user);return "hncu";}}


StudServiceImpl.java

package cn.hncu.stud.service;import javax.annotation.Resource;import org.springframework.stereotype.Service;import cn.hncu.domain.User;import cn.hncu.stud.dao.StudDAO;@Service(value="studService")//用注解来注入资源,资源名称为:studServicepublic class StudServiceImpl implements IStudService {    @Resource(name="studDao")    private StudDAO dao=null;    @Override    public void save(User user) {        dao.save(user);    }}

StudDaoJdbc.java
package cn.hncu.stud.dao;import org.springframework.stereotype.Repository;import cn.hncu.domain.User;@Repository(value="studDao")public class StudDaoJdbc implements StudDAO {@Overridepublic void save(User user) {System.out.println("dao-user:"+user);}}







0 0
原创粉丝点击