zoukankan      html  css  js  c++  java
  • Spring MVC 注解[转]

    摘要: 本章节,仅为@SessionAttributes的功能扩展介绍介绍,结合@requestparam注解进行简易无数据库分页。 之前介绍了@SessionAttributes的功能,他可以保存指定的值在modelnap中,不会因为request提交后则消失,我们利用这个特性,可以利用SessionAttributes注解进行简易的分页。 代码如下: 1: public class testservi...阅读全文
    posted @ 2011-04-12 16:51 EdwardLau 阅读(1680) | 评论 (0) 编辑
     
    摘要: 原本打算将@ModelAttribute跟@SessionAttributes一起写的发现有些例子不可以重复使用,所以决定再开一篇文章写顾名思义SessionAttributes就是保存session的,SessionAttributes使用方法很简单,@SessionAttributes 允许指定多个属性。你可以通过字符串数组的方式指定多个属性,如 @SessionAttributes({“attr1”,”attr2”})。此外,@SessionAttributes 还可以通过属性类型指定要 session 化的 ModelMap 属性,如 @SessionAttributes(types 阅读全文
    posted @ 2011-03-11 17:09 EdwardLau 阅读(6372) | 评论 (0) 编辑
     
    摘要: 本次介绍的是@ModelAttribute注解,这个注解可以跟@SessionAttributes配合在一起用,或者单独使用,首先先介绍@ModelAttribute注解,他跟mvc中的modelMap很相似,可以把它当作一个modelmap的简易版,使用@ModelAttribute方法很简单只是@ModelAttribute("保存的名字")就可以了,他只支持以下几种方式: (如果有还有其他方...阅读全文
    posted @ 2011-02-28 17:31 EdwardLau 阅读(2643) | 评论 (1) 编辑
     
    摘要: 近期心情不太好,想起当初有些事情,继续springmvc的返回类型中带有redirect方式的使用,使用redirect方式返回跟有3种方式首先介绍第一种,代码如下: 使用redirect后他不会对modelmap中的数据进行调用request.setAttribute而采用带参数的形式进行传值,如下图: 再页面中调用request.getParameter("testdata")后得到以下结果:...阅读全文
    posted @ 2011-01-18 22:16 EdwardLau 阅读(3344) | 评论 (0) 编辑
     
    摘要: 在通过requestmapping中返回中,我们可以通过forward还有redirect方式进行页面跳转而避开视图模型的控制,这次先讲forward的功能,forward有2种表示模式,forward功能的功能同request中的request.getRequestDispatcher("目标地址").forward(request,response)功能是一样的(spring mvc 默认这种)先看第一种:代码如下: 1: @RequestMapping("/forward") 2: public String testForword(ModelMa阅读全文
    posted @ 2011-01-04 22:05 EdwardLau 阅读(4006) | 评论 (0) 编辑
     
    摘要: 好久没有更新关于spring3.0.x的学习笔记了,这笔记除了平时工作上用的代码之外还有部分代码是根据我的老师学习下来后我再重新理解所整理的,接着上期第三部分的内容:上次写到了requestMapping对返回集合的用法,使用集合返回的话则需要根据requestmapping中values的值进行命名jsp页面,而整个路径地址是根据视图模型的返回地址来确定.这次主要介绍的是返回类型为Model,List.Collection,Set,Object,先看返回类型为Model,代码如下:temp方法代码如下:通过model的addAllAttributes可以把一个map集合的内容放到model对阅读全文
    posted @ 2011-01-03 23:42 EdwardLau 阅读(3172) | 评论 (1) 编辑
     
    摘要: 这篇不会大量的张贴代码,毕竟是自己对springMVC的学习,而不是对某一种东西作为详细解析的,好了话不多说了,近期学习springMVC换了不少东西,连日志工具也换了,采用了slf4j+logback进行日志管理,至于好处,请自行Google如何把主流的log4j+commons-loggin更换为slf4j+logback呢,由于spring里面采用了commons-logging日志监控,所以我们需要准备以下几个包:logback-classic.jar:改善了log4j并且实现了slf4j-log4j的代码logback-core.jar:logback的核心代码slf4j-api.j阅读全文
    posted @ 2010-08-10 16:29 EdwardLau 阅读(2286) | 评论 (0) 编辑
     
    摘要: 用惯了maven管理项目之后会发现自己懒惰了很多,所以决定放弃使用maven去学习spring3的mvc,采用传统的web project进行学习,好了闲话不说,首先我们需要知道spring mvc需要加什么包.使用到spring mvc的需要加入以下依赖包:org.springframework.aop-3.0.3.RELEASE.jar--------------Spring的切面编程org.springframework.asm-3.0.3.RELEASE.jar--------------Spring独立的asm程序org.springframework.beans-3.0.3.REL阅读全文
    posted @ 2010-07-23 14:42 EdwardLau 阅读(2557) | 评论 (0) 编辑
     
    摘要: 学习spring3.0.x(以下简称spring 3)已经一段日子了,新特性也接触不少,比较感兴趣还是spring mvc这一块3.0的mvc变化太大了,跟2.5基本上是两个样子,至于详细的区别可以参考以下文章领略Spring 3.x 时代的Spring MVCspring3 mvc变化比较大,但是还是有些2.5的影子的,首先来个2.5也可以使用的注解版本的mvc 入门例子.例子采用maven2管理,所以必须要安装m2eclipse插件或者使用maven2进行管理.本文基于eclipse3.5 Galileo-sr2Javaee 版本跟m2eclipse插件进行管理. m2eclipse在线阅读全文
    posted @ 2010-07-21 22:03 EdwardLau 阅读(7028) | 评论 (1) 编辑

    基于注解的 Spring MVC 简单入门

     
     
     

    6月14日【上海】开源中国 OSC 源创会第 25 期   现在报名»

    以下内容是经过自己整理资料、官方文档所得:


    web.xml 配置:

     

    <servlet>
    	<servlet-name>dispatcher</servlet-name>
    	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    	<init-param>
    		<description>加载/WEB-INF/spring-mvc/目录下的所有XML作为Spring MVC的配置文件</description>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>/WEB-INF/spring-mvc/*.xml</param-value>
    	</init-param>
    	<load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    	<servlet-name>dispatcher</servlet-name>
    	<url-pattern>*.htm</url-pattern>
    </servlet-mapping>

    这样,所有的.htm的请求,都会被DispatcherServlet处理;

    初始化 DispatcherServlet 时,该框架在 web 应用程序WEB-INF 目录中寻找一个名为[servlet-名称]-servlet.xml的文件,并在那里定义相关的Beans,重写在全局中定义的任何Beans,像上面的web.xml中的代码,对应的是dispatcher-servlet.xml;当然也可以使用<init-param>元素,手动指定配置文件的路径;

    dispatcher-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:mvc="http://www.springframework.org/schema/mvc"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
    			http://www.springframework.org/schema/beans/spring-beans-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/aop 
    			http://www.springframework.org/schema/aop/spring-aop-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/mvc 
    			http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    			http://www.springframework.org/schema/context 
    			http://www.springframework.org/schema/context/spring-context-3.0.xsd">
        <!--
            使Spring支持自动检测组件,如注解的Controller
        -->
        <context:component-scan base-package="com.minx.crm.web.controller"/>
       
        <bean id="viewResolver"
              class="org.springframework.web.servlet.view.InternalResourceViewResolver"
              p:prefix="/WEB-INF/jsp/"
              p:suffix=".jsp" />
    </beans>

    第一个Controller

    package com.minx.crm.web.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    @Controller
    public class IndexController {
        @RequestMapping("/index")
        public String index() {
            return "index";
        }
    }

    @Controller注解标识一个控制器,@RequestMapping注解标记一个访问的路径(/index.htm),return "index"标记返回视图(index.jsp);

    注:如果@RequestMapping注解在类级别上,则表示一相对路径,在方法级别上,则标记访问的路径;

    @RequestMapping注解标记的访问路径中获取参数:

    Spring MVC 支持RESTful风格的URL参数,如:

    @Controller
    public class IndexController {
    
        @RequestMapping("/index/{username}")
        public String index(@PathVariable("username") String username) {
            System.out.print(username);
            return "index";
        }
    }

    @RequestMapping中定义访问页面的URL模版,使用{}传入页面参数,使用@PathVariable 获取传入参数,即可通过地址:http://localhost:8080/crm/index/tanqimin.htm 访问;

    根据不同的Web请求方法,映射到不同的处理方法:

    使用登陆页面作示例,定义两个方法分辨对使用GET请求和使用POST请求访问login.htm时的响应。可以使用处理GET请求的方法显示视图,使用POST请求的方法处理业务逻辑

    @Controller
    public class LoginController {
        @RequestMapping(value = "/login", method = RequestMethod.GET)
        public String login() {
            return "login";
        }
        @RequestMapping(value = "/login", method = RequestMethod.POST)
        public String login2(HttpServletRequest request) {
                String username = request.getParameter("username").trim();
                System.out.println(username);
            return "login2";
        }
    }

    在视图页面,通过地址栏访问login.htm,是通过GET请求访问页面,因此,返回登陆表单视图login.jsp;当在登陆表单中使用POST请求提交数据时,则访问login2方法,处理登陆业务逻辑;

    防止重复提交数据,可以使用重定向视图:

    return "redirect:/login2"

    可以传入方法的参数类型:

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
    	String username = request.getParameter("username");
    	System.out.println(username);
    	return null;
    }

    可以传入HttpServletRequestHttpServletResponseHttpSession,值得注意的是,如果第一次访问页面,HttpSession没被创建,可能会出错;

    其中,String username = request.getParameter("username");可以转换为传入的参数:

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session,@RequestParam("username") String username) {
    	String username = request.getParameter("username");
    	System.out.println(username);
    	return null;
    }

    使用@RequestParam 注解获取GET请求或POST请求提交的参数;

    获取Cookie的值:使用@CookieValue 

    获取PrintWriter

    可以直接在Controller的方法中传入PrintWriter对象,就可以在方法中使用:

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String testParam(PrintWriter out, @RequestParam("username") String username) {
    	out.println(username);
    	return null;
    }

    获取表单中提交的值,并封装到POJO中,传入Controller的方法里:

    POJO如下(User.java):

    public class User{
    	private long id;
    	private String username;
    	private String password;
    
    	…此处省略getter,setter...
    }

    通过表单提交,直接可以把表单值封装到User对象中:

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String testParam(PrintWriter out, User user) {
    	out.println(user.getUsername());
    	return null;
    }

    可以把对象,put 入获取的Map对象中,传到对应的视图:

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String testParam(User user, Map model) {
    	model.put("user",user);
    	return "view";
    }

    在返回的view.jsp中,就可以根据key来获取user的值(通过EL表达式,${user }即可);

    Controller中方法的返回值:

    void:多数用于使用PrintWriter输出响应数据;

    String 类型:返回该String对应的View Name

    任意类型对象:

    返回ModelAndView

    自定义视图(JstlViewExcelView):

    拦截器(Inteceptors):

    public class MyInteceptor implements HandlerInterceptor {
    	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) 
    		throws Exception {
    		return false;
    	}
    	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mav) 
    		throws Exception {
    	}
    	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception excptn) 
    		throws Exception {
    	}
    }

    拦截器需要实现HandleInterceptor接口,并实现其三个方法:

    preHandle:拦截器的前端,执行控制器之前所要处理的方法,通常用于权限控制、日志,其中,Object o表示下一个拦截器;

    postHandle:控制器的方法已经执行完毕,转换成视图之前的处理;

    afterCompletion:视图已处理完后执行的方法,通常用于释放资源;

    MVC的配置文件中,配置拦截器与需要拦截的URL

    <mvc:interceptors>
    	<mvc:interceptor>
    		<mvc:mapping path="/index.htm" />
    		<bean class="com.minx.crm.web.interceptor.MyInterceptor" />
    	</mvc:interceptor>
    </mvc:interceptors>

    国际化:

    MVC配置文件中,配置国际化属性文件:

    <bean id="messageSource"
    	class="org.springframework.context.support.ResourceBundleMessageSource"
    	p:basename="message">
    </bean>

    那么,Spring就会在项目中搜索相关的国际化属性文件,如:message.propertiesmessage_zh_CN.properties

    VIEW中,引入Spring标签:<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>,使用<spring:message code="key" />调用,即可;

    如果一种语言,有多个语言文件,可以更改MVC配置文件为:

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    	<property name="basenames">
    		<list>
    			<value>message01</value>
    			<value>message02</value>
    			<value>message03</value>
    		</list>
    	</property>
    </bean>
  • 相关阅读:
    python网络编程 — HTTP客户端
    实验吧Web-天网管理系统
    实验吧Web-FALSE
    实验吧Web-Forms
    离散数学-集合运算基本法则
    sublime text3编译运行C,Java程序的一些配置
    kali Rolling 安装QQ和虚拟机
    python并行任务之生产消费模式
    Linux磁盘管理
    python网络编程之网络主机信息
  • 原文地址:https://www.cnblogs.com/fx2008/p/3770075.html
Copyright © 2011-2022 走看看