Spring学习(六)—— Spring注解(二)

核心原理

1.       用户发送请求给服务器。url:user.do

2.       服务器收到请求。发现Dispatchservlet可以处理。于是调用DispatchServlet。

3.       DispatchServlet内部,通过HandleMapping检查这个url有没有对应的Controller。如果有,则调用Controller。

4、    Control开始执行

5.       Controller执行完毕后,如果返回字符串,则ViewResolver将字符串转化成相应的视图对象;如果返回ModelAndView对象,该对象本身就包含了视图对象信息。

6.       DispatchServlet将执视图对象中的数据,输出给服务器。

7.       服务器将数据输出给客户端。

spring3.0中相关jar包的含义


org.springframework.aop-3.0.3.RELEASE.jar


spring的aop面向切面编程


org.springframework.asm-3.0.3.RELEASE.jar


spring独立的asm字节码生成程序


org.springframework.beans-3.0.3.RELEASE.jar


IOC的基础实现


org.springframework.context-3.0.3.RELEASE.jar


IOC基础上的扩展服务


org.springframework.core-3.0.3.RELEASE.jar


spring的核心包


org.springframework.expression-3.0.3.RELEASE.jar


spring的表达式语言


org.springframework.web-3.0.3.RELEASE.jar


web工具包


org.springframework.web.servlet-3.0.3.RELEASE.jar


mvc工具包

@Controller控制器定义

和Struts1一样,Spring的Controller是Singleton的。这就意味着会被多个请求线程共享。因此,我们将控制器设计成无状态类。

在spring 3.0中,通过@controller标注即可将class定义为一个controller类。为使spring能找到定义为controller的bean,需要在spring-context配置文件中增加如下定义:


<context:component-scan base-package="com.sxt.web"/>

 

         注:实际上,使用@component,也可以起到@Controller同样的作用。

@RequestMapping

在类前面定义,则将url和类绑定。

在方法前面定义,则将url和类的方法绑定

@RequestParam

一般用于将指定的请求参数付给方法中形参。示例代码如下:

@RequestMapping(params="method=reg5")

    public String reg5(@RequestParam("name")String uname,ModelMap map) {

       System.out.println("HelloController.handleRequest()");

       System.out.println(uname);

       return"index";

    }

这样,就会将name参数的值付给uname。当然,如果请求参数名称和形参名称保持一致,则不需要这种写法。

@SessionAttributes

将ModelMap中指定的属性放到session中。示例代码如下:

@Controller

@RequestMapping("/user.do")

@SessionAttributes({"u","a"})   //将ModelMap中属性名字为u、a的再放入session中。这样,request和session中都有了。

publicclass UserController  {

    @RequestMapping(params="method=reg4")

    public String reg4(ModelMap map) {         System.out.println("HelloController.handleRequest()");

       map.addAttribute("u","uuuu");  //将u放入request作用域中,这样转发页面也可以取到这个数据。

       return"index";

    }

}
<body>

   <h1>**********${requestScope.u.uname}</h1>

   <h1>**********${sessionScope.u.uname}</h1>

  </body>

注:名字为”user”的属性再结合使用注解@SessionAttributes可能会报错。

@ModelAttribute

这个注解可以跟@SessionAttributes配合在一起用。可以将ModelMap中属性的值通过该注解自动赋给指定变量。

示例代码如下:

package com.sxt.web;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.SessionAttributes;

@Controller

@RequestMapping("/user.do")

@SessionAttributes({"u","a"}) 

publicclass UserController  {

    @RequestMapping(params="method=reg4")

    public String reg4(ModelMap map) {

       System.out.println("HelloController.handleRequest()");

       map.addAttribute("u","尚学堂高淇");

       return"index";

    }

    @RequestMapping(params="method=reg5")

public String reg5(@ModelAttribute("u")String uname ,ModelMap map) {

       System.out.println("HelloController.handleRequest()");

       System.out.println(uname);

       return"index";

    }

} 

先调用reg4方法,再调用reg5方法。

Controller类中方法参数的处理

Controller类中方法返回值的处理

1.       返回string(建议)

a)         根据返回值找对应的显示页面。路径规则为:prefix前缀+返回值+suffix后缀组成

b)         代码如下:

@RequestMapping(params="method=reg4")

    public String reg4(ModelMap map) {

       System.out.println("HelloController.handleRequest()");

       return"index";

    }

前缀为:/WEB-INF/jsp/    后缀是:.jsp

在转发到:/WEB-INF/jsp/index.jsp

2.       也可以返回ModelMap、ModelAndView、map、List、Set、Object、无返回值。一般建议返回字符串!

请求转发和重定向

代码示例:

package com.sxt.web;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.SessionAttributes;

@Controller

@RequestMapping("/user.do")

publicclass UserController  {

    @RequestMapping(params="method=reg4")

    public String reg4(ModelMap map) {

       System.out.println("HelloController.handleRequest()");

//     return "forward:index.jsp";

//     return "forward:user.do?method=reg5"; //转发

//     return "redirect:user.do?method=reg5";  //重定向

       return"redirect:http://www.baidu.com";  //重定向

    }

    @RequestMapping(params="method=reg5")

    public String reg5(String uname,ModelMap map) {

       System.out.println("HelloController.handleRequest()");

       System.out.println(uname);

       return"index";

    }

}     

访问reg4方法,既可以看到效果。

获得request对象、session对象

普通的Controller类,示例代码如下:

@Controller

@RequestMapping("/user.do")

publicclass UserController  {

    @RequestMapping(params="method=reg2")

    public String reg2(String uname,HttpServletRequest req,ModelMap map){

       req.setAttribute("a", "aa");

       req.getSession().setAttribute("b", "bb");

       return"index";

    }

}

ModelMap

是map的实现,可以在其中存放属性,作用域同request。下面这个示例,我们可以在modelMap中放入数据,然后在forward的页面上显示这些数据。通过el表达式、JSTL、java代码均可。代码如下:

package com.sxt.web;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

@Controller

@RequestMapping("/user.do")

publicclass UserController extends MultiActionController  {

    @RequestMapping(params="method=reg")

    public String reg(String uname,ModelMap map){

       map.put("a", "aaa");

       return"index";

    }

}
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head></head>

  <body>

       <h1>${requestScope.a}</h1>

       <c:out value="${requestScope.a}"></c:out>

  </body>

</html>

将属性u的值赋给形参uname

ModelAndView模型视图类

见名知意,从名字上我们可以知道ModelAndView中的Model代表模型,View代表视图。即,这个类把要显示的数据存储到了Model属性中,要跳转的视图信息存储到了view属性。我们看一下ModelAndView的部分源码,即可知其中关系:

[java] view plaincopy

public class ModelAndView {  

    /** View instance or view name String */
    private Object view;  

    /** Model Map */
    private ModelMap model;  

    /**
     * Indicates whether or not this instance has been cleared with a call to {@link #clear()}.
     */
    private boolean cleared = false;  

    /**
     * Default constructor for bean-style usage: populating bean
     * properties instead of passing in constructor arguments.
     * @see #setView(View)
     * @see #setViewName(String)
     */
    public ModelAndView() {
    }  

    /**
     * Convenient constructor when there is no model data to expose.
     * Can also be used in conjunction with <code>addObject</code>.
     * @param viewName name of the View to render, to be resolved
     * by the DispatcherServlet‘s ViewResolver
     * @see #addObject
     */
    public ModelAndView(String viewName) {
        this.view = viewName;
    }  

    /**
     * Convenient constructor when there is no model data to expose.
     * Can also be used in conjunction with <code>addObject</code>.
     * @param view View object to render
     * @see #addObject
     */
    public ModelAndView(View view) {
        this.view = view;
    }  

    /**
     * Creates new ModelAndView given a view name and a model.
     * @param viewName name of the View to render, to be resolved
     * by the DispatcherServlet‘s ViewResolver
     * @param model Map of model names (Strings) to model objects
     * (Objects). Model entries may not be <code>null</code>, but the
     * model Map may be <code>null</code> if there is no model data.
     */
    public ModelAndView(String viewName, Map<String, ?> model) {
        this.view = viewName;
        if (model != null) {
            getModelMap().addAllAttributes(model);
        }
    }  

    /**
     * Creates new ModelAndView given a View object and a model.
     * <emphasis>Note: the supplied model data is copied into the internal
     * storage of this class. You should not consider to modify the supplied
     * Map after supplying it to this class</emphasis>
     * @param view View object to render
     * @param model Map of model names (Strings) to model objects
     * (Objects). Model entries may not be <code>null</code>, but the
     * model Map may be <code>null</code> if there is no model data.
     */
    public ModelAndView(View view, Map<String, ?> model) {
        this.view = view;
        if (model != null) {
            getModelMap().addAllAttributes(model);
        }
    }  

    /**
     * Convenient constructor to take a single model object.
     * @param viewName name of the View to render, to be resolved
     * by the DispatcherServlet‘s ViewResolver
     * @param modelName name of the single entry in the model
     * @param modelObject the single model object
     */
    public ModelAndView(String viewName, String modelName, Object modelObject) {
        this.view = viewName;
        addObject(modelName, modelObject);
    }  

    /**
     * Convenient constructor to take a single model object.
     * @param view View object to render
     * @param modelName name of the single entry in the model
     * @param modelObject the single model object
     */
    public ModelAndView(View view, String modelName, Object modelObject) {
        this.view = view;
        addObject(modelName, modelObject);
    }  

    /**
     * Set a view name for this ModelAndView, to be resolved by the
     * DispatcherServlet via a ViewResolver. Will override any
     * pre-existing view name or View.
     */
    public void setViewName(String viewName) {
        this.view = viewName;
    }  

    /**
     * Return the view name to be resolved by the DispatcherServlet
     * via a ViewResolver, or <code>null</code> if we are using a View object.
     */
    public String getViewName() {
        return (this.view instanceof String ? (String) this.view : null);
    }  

    /**
     * Set a View object for this ModelAndView. Will override any
     * pre-existing view name or View.
     */
    public void setView(View view) {
        this.view = view;
    }  

    /**
     * Return the View object, or <code>null</code> if we are using a view name
     * to be resolved by the DispatcherServlet via a ViewResolver.
     */
    public View getView() {
        return (this.view instanceof View ? (View) this.view : null);
    }  

    /**
     * Indicate whether or not this <code>ModelAndView</code> has a view, either
     * as a view name or as a direct {@link View} instance.
     */
    public boolean hasView() {
        return (this.view != null);
    }  

    /**
     * Return whether we use a view reference, i.e. <code>true</code>
     * if the view has been specified via a name to be resolved by the
     * DispatcherServlet via a ViewResolver.
     */
    public boolean isReference() {
        return (this.view instanceof String);
    }  

    /**
     * Return the model map. May return <code>null</code>.
     * Called by DispatcherServlet for evaluation of the model.
     */
    protected Map<String, Object> getModelInternal() {
        return this.model;
    }  

    /**
     * Return the underlying <code>ModelMap</code> instance (never <code>null</code>).
     */
    public ModelMap getModelMap() {
        if (this.model == null) {
            this.model = new ModelMap();
        }
        return this.model;
    }  

    /**
     * Return the model map. Never returns <code>null</code>.
     * To be called by application code for modifying the model.
     */
    public Map<String, Object> getModel() {
        return getModelMap();
    }  

    /**
     * Add an attribute to the model.
     * @param attributeName name of the object to add to the model
     * @param attributeValue object to add to the model (never <code>null</code>)
     * @see ModelMap#addAttribute(String, Object)
     * @see #getModelMap()
     */
    public ModelAndView addObject(String attributeName, Object attributeValue) {
        getModelMap().addAttribute(attributeName, attributeValue);
        return this;
    }  

    /**
     * Add an attribute to the model using parameter name generation.
     * @param attributeValue the object to add to the model (never <code>null</code>)
     * @see ModelMap#addAttribute(Object)
     * @see #getModelMap()
     */
    public ModelAndView addObject(Object attributeValue) {
        getModelMap().addAttribute(attributeValue);
        return this;
    }  

    /**
     * Add all attributes contained in the provided Map to the model.
     * @param modelMap a Map of attributeName -> attributeValue pairs
     * @see ModelMap#addAllAttributes(Map)
     * @see #getModelMap()
     */
    public ModelAndView addAllObjects(Map<String, ?> modelMap) {
        getModelMap().addAllAttributes(modelMap);
        return this;
    }  

    /**
     * Clear the state of this ModelAndView object.
     * The object will be empty afterwards.
     * <p>Can be used to suppress rendering of a given ModelAndView object
     * in the <code>postHandle</code> method of a HandlerInterceptor.
     * @see #isEmpty()
     * @see HandlerInterceptor#postHandle
     */
    public void clear() {
        this.view = null;
        this.model = null;
        this.cleared = true;
    }  

    /**
     * Return whether this ModelAndView object is empty,
     * i.e. whether it does not hold any view and does not contain a model.
     */
    public boolean isEmpty() {
        return (this.view == null && CollectionUtils.isEmpty(this.model));
    }  

    /**
     * Return whether this ModelAndView object is empty as a result of a call to {@link #clear}
     * i.e. whether it does not hold any view and does not contain a model.
     * <p>Returns <code>false</code> if any additional state was added to the instance
     * <strong>after</strong> the call to {@link #clear}.
     * @see #clear()
     */
    public boolean wasCleared() {
        return (this.cleared && isEmpty());
    }  

    /**
     * Return diagnostic information about this model and view.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("ModelAndView: ");
        if (isReference()) {
            sb.append("reference to view with name ‘").append(this.view).append("‘");
        }
        else {
            sb.append("materialized View is [").append(this.view).append(‘]‘);
        }
        sb.append("; model is ").append(this.model);
        return sb.toString();
    }
}  

[java] view plaincopy

测试代码如下:

package com.sxt.web;  

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

import com.sxt.po.User;  

@Controller
@RequestMapping("/user.do")
public class UserController extends MultiActionController  {  

    @RequestMapping(params="method=reg")
    public ModelAndView reg(String uname){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("index");
//      mv.setView(new RedirectView("index"));  

        User u = new User();
        u.setUname("高淇");
        mv.addObject(u);   //查看源代码,得知,直接放入对象。属性名为”首字母小写的类名”。 一般建议手动增加属性名称。
        mv.addObject("a", "aaaa");
        return mv;
    }  

}
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  <body>
       <h1>${requestScope.a}</h1>
       <h1>${requestScope.user.uname}</h1>
  </body>
</html>  

地址栏输入:http://localhost:8080/springmvc03/user.do?method=reg

时间: 2024-08-04 02:32:59

Spring学习(六)—— Spring注解(二)的相关文章

spring学习 六 spring与mybatis整合

在mybatis学习中有两种配置文件 :全局配置文件,映射配置文件.mybatis和spring整合,其实就是把mybatis中的全局配置文件的配置内容都变成一个spring容器的一个bean,让spring容器进行托管.因此整合过程就是把mybatis全局配置文件的内容整合到spring的配置文件中 (一)mybatis全局配置文件 : 根标签是<configuration>, 子标签包括: <typeAliases>配置别名, <environments> 配置数据

spring学习2:基于注解+xml实现ioc和依赖注入

spring学习2:基于注解+xml实现ioc和依赖注入 一.在spring配置文件中开启spring对注解的支持 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&qu

Spring学习之事务注解@Transactional

今天学习spring中的事务注解,在学习Spring注解事务之前需要明白一些事务的基本概念: 事务:并发控制的单位,是用户定义的一个操作序列.这些操作要么都做,要么都不做,是一个不可分割的工作单位.通过事务数据库能将逻辑相关的一组操作绑定在一起,以便服务器保持数据的完整性. 事务隔离级别:在并发处理数据中,为了保持数据的完整性和正确性,而执行的操作数据方式. 脏读 :一个事务读取到另一事务未提交的更新数据. 幻读:一个事务读到另一个事务已提交的insert数据. 不可重复读: 是指在一个事务内多

spring学习3:spring ioc的纯注解配置

spring ioc的纯注解配置 一.分析 在上一篇博客中实现了xml+注解的ioc使用,我们发现,之所以离不开xml配置文件的原因是在该文件中有一句很关键的话,告知spring在创建容器时要扫描的包,依据扫描到的注解创建对象并放入容器中. <!-- 开启注解扫描,告知spring在创建容器时要扫描的包 --> <context:component-scan base-package="com.lyy.service"> </context:compone

Spring学习之常用注解(转)

使用注解来构造IoC容器 用注解来向Spring容器注册Bean.需要在applicationContext.xml中注册<context:component-scan base-package=”pagkage1[,pagkage2,…,pagkageN]”/>. 如:在base-package指明一个包 1 <context:component-scan base-package="cn.gacl.java"/> 表明cn.gacl.java包及其子包中,如

Spring Cloud 学习 (六) Spring Cloud Config

在实际开发过程中,每个服务都有大量的配置文件,例如数据库的配置.日志输出级别的配置等,而往往这些配置在不同的环境中也是不一样的.随着服务数量的增加,配置文件的管理也是一件非常复杂的事 在微服务架构中,需要有统一管理配置文件的组件,例如 Spring Cloud 的 Spring Cloud Config.阿里的 Diamond.百度的 Disconf.携程的 Apollo 等 新建 spring-cloud-config-server 从本地读取配置 pom <parent> <arti

spring学习(三) ———— spring事务操作

前面一篇博文讲解了什么是AOP.学会了写AOP的实现,但是并没有实际运用起来,这一篇博文就算是对AOP技术应用的进阶把,重点是事务的处理. --wh 一.jdbcTemplate 什么是JdbcTemplate? spring提供用于操作数据库模版,类似Dbutils,通俗点讲,我们操作数据库,spring也会帮我们提供一个操作数据库的工具供我们使用,而不用我们自己手动编写连接数据库,获取结果集等等操作,这个工具就是JdbcTemplate.跟Dbutils一样,想要使用JdbcTemplate

Spring学习2—Spring容器

一.Spring容器接口关系 容器是Spring框架的核心,Spring容器就是一个巨大的工厂.Spring容器使用Ioc(控制反转(Inversion of Control )管理所有组成应用系统的组件. Spring容器会使用XML解析器读取改属性值,并利用反射来创建该实现类的实例. Spring有两个核心接口:BeanFactory和ApplicationContext,其中ApplicationContext是BeanFactory的子接口.它们都可以代表Spring容器.Spring容

Spring学习【Spring概述】

从本文开始,我们就要一起学习Spring框架,首先不得不说Spring框架是一个优秀的开源框架.其中采用IoC原理实现的基于Java Beans的配置管理和AOP的思想都是很值得学习与使用的.下面我们就进入正题!介绍Java平台上的一个优秀的开源应用框架Spring,以及Spring框架的历史和Spring框架相关基本知识. [转载使用,请注明出处:http://blog.csdn.net/mahoking] Spring 介绍 Spring是Java平台上的一个开源应用框架.它的第一个版本是由

Spring 学习6 -Spring MVC-2 (Spring MVC讲解)

在本例中,我们将使用Spring MVC框架构建一个入门级web应用程序.Spring MVC 是Spring框架最重要的的模块之一.它以强大的Spring IoC容器为基础,并充分利用容器的特性来简化它的配置. 目录 MVC框架是什么Dispatcher Servlet(Spring控制器)Spring入门示例运行时依赖库web.xml和spring-servlet.xml文件配置请求控制器EmployeeController.java视图模型EmployeeVO.javaDao类业务层类视图