zoukankan      html  css  js  c++  java
  • Spring MVC学习总结。

     公司项目用的Spring MVC。顺便学习学习。

    其实框架并没有想象中的复杂。尤其对于初学者,总觉得SSH是一些很复杂的东西似的。其实对初学者来说能够用这些框架就足够了。在公司里也是,基本功能会用了就可以了。管他框架有多高深。尤其是Spring MVC 用起来比Struts2简单多了。不用多少配置文件。几个注解就搞定了。

    首先,大家只要理解了MVC。其实所有的MVC 框架都是大同小异的。

    无非是用户页面通过HttpServletRequest向后台传值。框架的配置文件会通过Request中的URL格式和参数找到相对应的Action(Spring mvc中叫Controller)。Action执行完成后或者返回一个新的页面或者只返回一些数据。可以放在Request中或者Session中在页面中取得。然后页面继续其他功能。(个人理解!)

    先看一下Spring MVC 的处理流程:

    1.客户发出请求request,DispatchServlet(Spring 的前端控制器)负责统一分发请求到Spring控制器(Controller)。
    2.统一分发之前,需要借助于handlermapping对象定位到具体的Spring控制器(Controller)。
    3.Spring控制器处理DispatchServlet分发过来的的请求,执行业务逻辑或调用业务逻辑组件。
    4.一旦控制器处理完客户请求,则返回一个ModelAndView 对象给DispatchServlet前端控制器.,ModelAndView 对象包含数据模型和视图信息(很明显Model和View)。

    5.DispatchServlet询问视图解析器,查找相应视图。

    6.由某具体视图为用户显示页面。


    还是很容易理解的吧。就开始试试吧。

    首先在web.xml中配置上DispatchServlet(Spring 的前端控制器)

    添加上<!-- Spring配置 -->
      <servlet>
        <servlet-name>spring-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/config/spring/spring-dispather.xml</param-value> <!-- 指明Spring mvc的配置文件地址 -->
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>

      <servlet-mapping>
        <servlet-name>spring-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>


    配置好这个就在相应的目录下建立spring的配置文件。先来个Spring 配置文件的片段吧。对应着说:

    <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"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
            http://www.springframework.org/schema/util
            http://www.springframework.org/schema/util/spring-util-3241.xsd
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
           
        <!-- 开启controller注解支持 -->      
        <mvc:annotation-driven />

    <!-- 注:指定应用注解的包,如果base-package=com.avicit 则注解事务不起作用 -->
    <context:component-scan base-package="com.hcc">
    </context:component-scan>

    <!-- 加载静态资源 -->
    <mvc:default-servlet-handler/>

    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->    
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
        
        <!-- 上传拦截,如最大上传值及最小上传值  
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        
            <property name="maxUploadSize" value="10000000" />
            <property name="maxInMemorySize" value="4096"/>
        </bean>  
         -->
    <!--  ***************配置数据源************** --> 
    <!-- mysql数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">   

     
          <property name="driverClassName" value="com.mysql.jdbc.Driver" />         
          <property name="url" value="jdbc:mysql://localhost:3306/test" />         
          <property name="username" value="root" />         
          <property name="password" value="123456" />   


          
          <property name="maxActive"><value>500</value></property>
          <!-- 设定最大空闲时间(毫秒) -->
          <property name="maxIdle"><value>10000</value></property>
          <!-- 设定最大等待时间(毫秒) -->
          <property name="maxWait"><value>1000</value></property>
          <!-- 超时自动收回 -->
          <property name="removeAbandoned"><value>true</value></property>
          <!--
                      超时时间(以秒数为单位)设置超时时间有一个要注意的地方,
                      超时时间=现在的时间-程序中创建Connection的时间,如果
                      maxActive比较大,比如超过100,那么removeAbandonedTimeout
                      可以设置长一点比如180, 也就是三分钟无响应的连接进行回收,
                      当然应用的不同设置长度也不同。
          -->
          <property name="removeAbandonedTimeout"><value>180</value></property>
          <!-- 在自动回收超时连接的时候打印连接的超时错误 -->
          <property name="logAbandoned"><value>true</value></property>        
    </bean> 

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
    </bean>

    <!--  jdbcTemplate数据库操作类 -->  
        <bean id="jdbcTemplate"  class="org.springframework.jdbc.core.JdbcTemplate">  
            <property name="dataSource" ref="dataSource" />  
        </bean>  
    </beans>


    上面都写了注释,相信能看到这篇文章的人都能看懂吧,不多解释。以上都是常用到的配置,其他的配置我还没碰到,不多说。说多了也掌握不了。学东西还是在项目上学得快。


    配置好之后就是Spring mvc的框架下开发了。


    之所以认为Spring mvc开发比Struts2简单很多就是因为注释。 你看Spring文件中就没有对应Controller的配置。不像Struts2每个Action都要配置上来,虽然用通配符也简单不少。不过这个完全不写,通过注释搞定就行了。举个例子:


    @Controller
    public class LoginController {
    @RequestMapping( value = "dologin") 
    @ResponseBody 

    @SessionAttributes({"username","xxx"})
    public Map<String,Object> dologin(HttpServletRequest req,

    Model model,
    @RequestParam(value = "username") String username,
    @RequestParam(value = "password") String password
    ){
    Map<String,Object> res = new HashMap<String,Object>();

    model.addAttribute("username",username);
    if(username.equals("hello")&&password.equals("hello")){
    res.put("status", true);
    res.put("result", "success");
    }else{
    res.put("status",false);
    res.put("result", "用户名或密码错误!");
    }
    return res;
    }
    }


    这段代码的意思就不用我解释了吧。

    直接看注释,@Controller 这个注释就是表明此类是个Controller类(对应于Struts2的Action类),有了此注释就不用继承基本Controller类了。

    @RequestMapping( value = "login/dologin") 这个注释可以用于方法上面也可以用于类上面。我只说用在方法上面(我觉得用在类上面复杂)。 看到里面有个value参数了吧。这个参数的值就是匹配的request中url的值,也就是访问这个方法的话在url后面写login/dologin这个就找到这个方法了。这个对应比Struts2中写个Action方法都去配置文件中写个配置简单吧。

    @ResponseBody 这个注释是指不反回视图了只返回数据。 SpringMVC中controller的默认返回值类型是ModelAndView就是视图和数据。别问我为什么数据用Model来存,Model是什么?我也不懂,跟着用就行了。就我理解我认为Model就是个jsp中用来页面间传值的request。代码中有句model.addAttribute("username",username);就是把username的值存在名字叫做”username“的属性中。然后在返回的页面中就可以通过${username}来取得username的值。

    @SessionAttributes 这个注释放在类的上面。看了上面model.addAttribute("username",username);就好理解了。 model.addAttribute("username",username);是将属性”username“放在request中。如果在类上面加了@SessionAttributes({"username"})那么”username“这个属性就会加到session中随时来取。

    @RequestParam(value = "username",defaultValue ="xxx") 这个注释,是指页面访问此方法的时候url后面加的参数在这接收。 例如url 是 ……login/dologin?username="aaa 就是想后台传了个username参数。那么可以通过此注释来接收参数。

    还有这段代码中没用到的注释:

    @Service("businessService")     对于这个注释我认为就是向Spring配置文件中注释<bean>.这个注释放在类的上面。例如放在BusinessServiceImpl 的上面那么就相当于在配置文件中配置了<bean id="businessService"  class="com.xxx.xxx.BusinessServiceImpl" />

    @Resource(name = "businessService") 这个注释就是注入的意思。上面注释相当于配置了bean那么这个注释就是取得那个bean的意思。用法为 在注释下面声明一个此对象就相当于new 了这对象了,就可以拿来用了。例如:

    @Resource(name = "businessService")

    BusinessService businessService;

    (BusinessService是BusinessServiceImpl 实现的接口,应该能想到。)这样就可以直接拿businessService这个对象来用了。


    注释就说这么几个吧。其他的我用的还不多。


    然后说下Spring mvc的controller方法默认返回 的ModelAndView类型是怎么回事。 这个类应该是spring mvc中特有的。

    一般如果需要返回页面的话 就用这个返回类。 这个类对象的生成方法是:ModelAndView mv = new ModelAndView("login/success");其中的参数是个jsp页面。可能你要问这为什么是个jsp页面,看上面的spring配置文件中有个配置是:

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

    看到了吗。他会自动把视图的前后缀加上。这个页面就是"/WEB-INF/jsp/login/success.jsp"。这样的话就会返回success.jsp这个页面,Model上面说了就是向页面传值。作用域和Request一样。把他当做Request就行了。取值方式都一样。${requestScope.xxxxxx}。如果是传大量数据的话 一般也不用这个传。比如用List返回一系列数据的话。这样的话 返回值就不是ModelAndView类型了。就不能同时返回视图。所以用@ResponseBody 注释。来指明只返回数据部返回视图。

    想学习的话 可以找点demo试试。看是不是比Struts简单多了。就写这点吧。其他的还没怎么了解。

    至尊新手 纯手写,有什么问题欢迎指正。

  • 相关阅读:
    百度之星资格赛1001——找规律——大搬家
    HDU1025——LIS——Constructing Roads In JGShining's Kingdom
    DP(递归打印路径) UVA 662 Fast Food
    递推DP UVA 607 Scheduling Lectures
    递推DP UVA 590 Always on the run
    递推DP UVA 473 Raucous Rockers
    博弈 HDOJ 4371 Alice and Bob
    DFS(深度) hihoCoder挑战赛14 B 赛车
    Codeforces Round #318 [RussianCodeCup Thanks-Round] (Div. 2)
    DP(DAG) UVA 437 The Tower of Babylon
  • 原文地址:https://www.cnblogs.com/james1207/p/3341822.html
Copyright © 2011-2022 走看看