Spring mvc 学习拾遗
SpringMVC+Spring+Hibernate框架整合原理,作用及使用方法

SpringMVC+Spring+Hibernate框架整合原理,作⽤及使⽤⽅法SSM框架是spring MVC ,spring和mybatis框架的整合,是标准的MVC模式,将整个系统划分为表现层,controller层,service层,DAO层四层使⽤spring MVC负责请求的转发和视图管理spring实现业务对象管理,mybatis作为数据对象的持久化引擎原理:SpringMVC:1.客户端发送请求到DispacherServlet(分发器)2.由DispacherServlet控制器查询HanderMapping,找到处理请求的Controller3.Controller调⽤业务逻辑处理后,返回ModelAndView4.DispacherSerclet查询视图解析器,找到ModelAndView指定的视图5.视图负责将结果显⽰到客户端Spring:我们平时开发接触最多的估计就是IOC容器,它可以装载bean(也就是我们中的类,当然也包括service dao⾥⾯的),有了这个机制,我们就不⽤在每次使⽤这个类的时候为它初始化,很少看到关键字new。
另外spring的aop,事务管理等等都是我们经常⽤到的。
Mybatis:mybatis是对jdbc的封装,它让数据库底层操作变的透明。
mybatis的操作都是围绕⼀个sqlSessionFactory实例展开的。
mybatis通过配置⽂件关联到各实体类的Mapper⽂件,Mapper⽂件中配置了每个类对数据库所需进⾏的sql语句映射。
在每次与数据库交互时,通过sqlSessionFactory拿到⼀个sqlSession,再执⾏sql命令。
使⽤⽅法:要完成⼀个功能:1. 先写实体类entity,定义对象的属性,(可以参照数据库中表的字段来设置,数据库的设计应该在所有编码开始之前)。
2. 写Mapper.xml(Mybatis),其中定义你的功能,对应要对数据库进⾏的那些操作,⽐如 insert、selectAll、selectByKey、delete、update等。
解决springmvc使用@PathVariable路径匹配问题

解决springmvc使⽤@PathVariable路径匹配问题⼀、问题今天作毕设的时候,在搭建ssm框架的使⽤使⽤springmvc的@PathVariable时出现了⼀个路径匹配的问题,最后花了点时间解决了。
代码结构:问题内容:访问url为:按照道理说,我应该到jsp的index页⾯去。
最后的结果确实到了index页⾯,可是由于该页⾯引⽤了⼏个css和js,报异常找不到。
有使⽤过spring经验的童鞋应该知道使⽤如下代码解决静态资源的访问。
// ⽅法⼀<mvc:default-servlet-handler/>// ⽅法⼆<mvc:resources location="/easyui/js/" mapping="/themes/**"/><mvc:resources location="/easyui/themes/" mapping="/js/**"/>可是最后还是访问不到静态资源。
于是我就想是因为@PathVariable的原因吗?于是在下⾯做了⼀个实验@RequestMapping("/index")public String index() {System.out.println("index execute ");return "index";}⼆、解决⽅法上⾯的问题产⽣是因为我在引⽤静态⽂件使⽤的是相对路径。
解决⽅法就是将其全部修改为绝对路径。
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/easyui/themes/default/easyui.css" rel="external nofollow" ><link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/easyui/themes/icon.css" rel="external nofollow" ><script type="text/javascript" src="${pageContext.request.contextPath}/easyui/js/jquery.min.js"></script><script type="text/javascript" src="${pageContext.request.contextPath}/easyui/js/jquery.easyui.min.js"></script>最后完美解决。
什么是SpringMVC?

什么是SpringMVC?⼀、什么是SpringMVC?1.SpringMVC 是⼀种基于 Java 的实现 MVC 设计模型的请求驱动类型的轻量级 Web 框架,属于SpringFrameWork的后续产品,已经融合在Spring Web Flow 中。
2.SpringMVC = Spring +MVCspring mvc类似于struts的⼀个MVC开框架,其实都是属于spring,spring mvc需要有spring的架包作为⽀撑才能跑起来.spring是⼀个⼀站式的框架,提供了表现层(springmvc)到业务层(spring)再到数据层(springdata)的全套解决⽅案;spring的两⼤核⼼IOC(控制反转)和AOP(⾯向切⾯编程)更是给我们的程序解耦和代码的简介提供了⽀持。
Spring框架图:从Spring的结构图可以看出,springMVC位于spring web端的⼀个框架,是⼀种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使⽤了MVC架构模式的思想,将web层进⾏职责解耦。
附:基于请求驱动指的就是使⽤请求-响应模型。
从名字上就可以窥探出,Spring>SpringMVC,那么事实上,spring和SpringMVC是⼀种⽗⼦关系。
SpringMVC是spring扩展出的⼀个应⽤于web端的框架。
在这⾥需要注意的⼀点,就是到底什么是⽗⼦容器关系:spring主要的作⽤是黏合其他模块组件,进⾏统⼀管理,springmvc则主要是负责web端。
那么,我们都知道,我们在应⽤spring的时候,可以使⽤注⼊。
这个时候,如果我们的web端是⽤的SpringMVC,这个时候,controller理论上是通过SpringMVC去注⼊,但是,使⽤spring注⼊,同样是可⾏的。
同理,service等层,使⽤SpringMVC配置的统⼀扫描装配也是可以的。
SpringMVC学习教程之RequestMappingHandlerAdapter详解

SpringMVC学习教程之RequestMappingHandlerAdapter详解前⾔RequestMappingHandlerAdapter实现了HandlerAdapter接⼝,顾名思义,表⽰handler的adapter,这⾥的handler指的是Spring处理具体请求的某个Controller的⽅法,也就是说HandlerAdapter指的是将当前请求适配到某个Handler的处理器。
RequestMappingHandlerAdapter是HandlerAdapter的⼀个具体实现,主要⽤于将某个请求适配给@RequestMapping类型的Handler处理。
如下是HandlerMapping接⼝的声明:public interface HandlerAdapter {// ⽤于判断当前HandlerAdapter是否能够处理当前请求boolean supports(Object handler);// 如果当前HandlerAdapter能够⽤于适配当前请求,那么就会处理当前请求中// 诸如参数和返回值等信息,以便能够直接委托给具体的Handler处理ModelAndView handle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception;// 获取当前请求的最后更改时间,主要⽤于供给浏览器判断当前请求是否修改过,// 从⽽判断是否可以直接使⽤之前缓存的结果long getLastModified(HttpServletRequest request, Object handler);}1. supports()HandlerAdapter.supports()⽅法的主要作⽤在于判断当前的HandlerAdapter是否能够⽀持当前的handler的适配。
SpringMVC目录结构配置

SpringMVC目录结构配置SpringMVC是一种常见的Java Web框架,它遵循MVC(Model-View-Controller)设计模式,用于构建灵活可扩展的Web应用程序。
SpringMVC的目录结构对于项目的开发和维护非常重要,下面会详细介绍SpringMVC的标准目录结构以及配置方式。
1.标准目录结构1.1 src/main/java:主要用于存放Java源代码。
1.2 src/main/resources:主要用于存放配置文件和资源文件。
1.3 src/main/webapp:主要用于存放Web应用的静态资源。
1.4 src/test/java:主要用于存放测试用例的Java源代码。
1.5 src/test/resources:主要用于存放测试用例的配置文件和资源文件。
2.详细解析2.1 src/main/java目录src/main/java目录是存放Java源代码的默认目录,它包括以下几个子目录:- config:用于存放Spring配置类,如配置数据库连接、配置事务管理等。
- interceptor:用于存放SpringMVC的拦截器。
- model:用于存放数据模型相关的实体类。
- util:用于存放工具类。
- web:用于存放SpringMVC的控制器。
2.2 src/main/resources目录src/main/resources目录是存放配置文件和资源文件的默认目录,它包括以下几个子目录:- static:用于存放静态资源文件,如CSS、JavaScript、图片等。
- templates:用于存放模板文件,如HTML、Thymeleaf模板等。
- application.properties:存放项目的配置信息,如数据库配置、端口配置等。
- logback.xml:存放日志配置,如日志级别、输出路径等。
- mapper:存放MyBatis的Mapper.xml文件。
springMVC配置(XML配置详解)

springMVC配置(XML配置详解)原⽂出⾃: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="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:mvc="/schema/mvc"xmlns:p="/schema/p"xmlns:context="/schema/context"xmlns:aop="/schema/aop"xmlns:tx="/schema/tx"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-3.0.xsd/schema/context/schema/context/spring-context-3.0.xsd/schema/aop/schema/aop/spring-aop-3.0.xsd/schema/tx/schema/tx/spring-tx-3.0.xsd/schema/mvc/schema/mvc/spring-mvc-3.0.xsd/schema/context/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;@Controllerpublic class IndexController {@RequestMapping("/index")public String index() {return "index";}}@Controller注解标识⼀个控制器,@RequestMapping注解标记⼀个访问的路径(/index.htm),return "index"标记返回视图(index.jsp);注:如果@RequestMapping注解在类级别上,则表⽰⼀相对路径,在⽅法级别上,则标记访问的路径;从@RequestMapping注解标记的访问路径中获取参数:Spring MVC ⽀持RESTful风格的URL参数,如:@Controllerpublic 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时的响应。
Springmvc 组合jackson与fastjson使用心得
Springmvc 组合jackson与fastjson使用心得1、解决方案可以将其中的main方法删掉。
测试用的。
我测试的结果是,jackson比fastjson 快。
fastjson是1.1.36jackson是2.2.3jdk是1.7.40,clientcpu是intel i32、主要代码package org.springframework.web.servlet.view.json;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.OutputStream;import java.io.StringReader;import java.io.StringWriter;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.util.CollectionUtils;import org.springframework.validation.BindingResult;import org.springframework.web.servlet.view.AbstractView;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.parser.Feature;import com.alibaba.fastjson.serializer.SerializerFeature;import com.fasterxml.jackson.core.JsonFactory;import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.core.JsonParseException;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.JsonMappingException;import com.fasterxml.jackson.databind.MappingIterator;import com.fasterxml.jackson.databind.ObjectMapper;import mon.collect.Lists;import mon.collect.Maps;import mon.collect.Sets;import er;public class MappingFastJsonView extends AbstractView {/*** Default content type: "application/json".* Overridable through {@link #setContentType}.*/public static final String DEFAULT_CONTENT_TYPE = "application/json"; private String encoding = "UTF-8";private String jsonPrefix;private Boolean prettyPrint;private Set<String> modelKeys;private boolean extractValueFromSingleKeyModel = false;private boolean disableCaching = true;private boolean updateContentLength = false;/*** Construct a new {@code MappingFastJsonView}, setting the content type to {@code application/json}.*/public MappingFastJsonView() {setContentType(DEFAULT_CONTENT_TYPE);setExposePathVariables(false);}public String getEncoding() {return encoding;}public void setEncoding(String encoding) {this.encoding = encoding;}/*** Specify a custom prefix to use for this view's JSON output.* Default is none.* @see #setPrefixJson*/public void setJsonPrefix(String jsonPrefix) {this.jsonPrefix = jsonPrefix;}/*** Indicates whether the JSON output by this view should be prefixed with <tt>"{} && "</tt>.* Default is {@code false}.* <p>Prefixing the JSON string in this manner is used to help prevent JSON Hijacking.* The prefix renders the string syntactically invalid as a script so that it cannot be hijacked.* This prefix does not affect the evaluation of JSON, but if JSON validation is performed* on the string, the prefix would need to be ignored.* @see #setJsonPrefix*/public void setPrefixJson(boolean prefixJson) {// if (prefixJson) {// if (jsonPrefix == null) {// jsonPrefix = "{} && ";// }// }this.jsonPrefix = (prefixJson ? "{} && " : null);}/*** Whether to use the default pretty printer when writing JSON. * This is a shortcut for setting up an {@code JSON}* <p>The default value is {@code false}.*/public void setPrettyPrint(boolean prettyPrint) {this.prettyPrint = prettyPrint;}/*** Set the attribute in the model that should be rendered by this view. * When set, all other model attributes will be ignored.*/public void setModelKey(String modelKey) {this.modelKeys = Collections.singleton(modelKey);}/*** Set the attributes in the model that should be rendered by this view.* When set, all other model attributes will be ignored.*/public void setModelKeys(Set<String> modelKeys) {this.modelKeys = modelKeys;}/*** Return the attributes in the model that should be rendered by this view.*/public final Set<String> getModelKeys() {return this.modelKeys;}/*** Set whether to serialize models containing a single attribute as a map or whether to* extract the single value from the model and serialize it directly. * <p>The effect of setting this flag is similar to using {@code MappingJacksonHttpMessageConverter}* with an {@code @ResponseBody} request-handling method.* <p>Default is {@code false}.*/public void setExtractValueFromSingleKeyModel(boolean extractValueFromSingleKeyModel) {this.extractValueFromSingleKeyModel = extractValueFromSingleKeyModel;}* Disables caching of the generated JSON.* <p>Default is {@code true}, which will prevent the client from caching the generated JSON.*/public void setDisableCaching(boolean disableCaching) {this.disableCaching = disableCaching;}/*** Whether to update the 'Content-Length' header of the response. When set to* {@code true}, the response is buffered in order to determine the content* length and set the 'Content-Length' header of the response.* <p>The default setting is {@code false}.*/public void setUpdateContentLength(boolean updateContentLength) { this.updateContentLength = updateContentLength;}@Overrideprotected void prepareResponse(HttpServletRequest request, HttpServletResponse response) {setResponseContentType(request, response);response.setCharacterEncoding(encoding);if (this.disableCaching) {response.addHeader("Pragma", "no-cache");response.addHeader("Cache-Control", "no-cache, no-store, max-age=0");response.addDateHeader("Expires", 1L);}}@Overrideprotected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)throws Exception {OutputStream stream = (this.updateContentLength ? createTemporaryOutputStream() : response.getOutputStream());Object value = filterModel(model);writeContent(stream, value, this.jsonPrefix);if (this.updateContentLength) {writeToResponse(response, (ByteArrayOutputStream) stream);}/*** Filter out undesired attributes from the given model.* The return value can be either another {@link Map} or a single value object.* <p>The default implementation removes {@link BindingResult} instances and entries* not included in the {@link #setRenderedAttributes renderedAttributes} property.* @param model the model, as passed on to {@link#renderMergedOutputModel}* @return the value to be rendered*/protected Object filterModel(Map<String, Object> model) {Map<String, Object> result = new HashMap<String,Object>(model.size());Set<String> renderedAttributes =(!CollectionUtils.isEmpty(this.modelKeys) ? this.modelKeys :model.keySet());for (Map.Entry<String, Object> entry : model.entrySet()) {if (!(entry.getValue() instanceof BindingResult) && renderedAttributes.contains(entry.getKey())) {result.put(entry.getKey(), entry.getValue());}}return (this.extractValueFromSingleKeyModel && result.size() == 1 ? result.values().iterator().next() : result);}/*** Write the actual JSON content to the stream.* @param stream the output stream to use* @param value the value to be rendered, as returned from {@link #filterModel}* @param jsonPrefix the prefix for this view's JSON output* (as indicated through {@link #setJsonPrefix}/{@link#setPrefixJson})* @throws IOException if writing failed*/protected void writeContent(OutputStream stream, Object value, String jsonPrefix) throws IOException {List<SerializerFeature> list = newArrayList<SerializerFeature>();if (prettyPrint != null && prettyPrint) {list.add(SerializerFeature.PrettyFormat);}SerializerFeature[] features = newSerializerFeature[list.size()];list.toArray(features);byte[] jsonBytes = JSON.toJSONBytes(value, features);if (jsonPrefix != null) {//此处亦可字符串相加,然后转成字节数组byte[] prefixBytes =jsonPrefix.getBytes(Charset.forName("UTF-8"));int prefixLength = prefixBytes.length;int jsonLength = jsonBytes.length;byte[] finalJsonBytes = new byte[prefixLength + jsonLength];System.arraycopy(prefixBytes, 0, finalJsonBytes, 0, prefixLength);System.arraycopy(jsonBytes, 0, finalJsonBytes, prefixLength, jsonLength);stream.write(finalJsonBytes);} else {stream.write(jsonBytes);}stream.flush();}public static void main(String[] args) {List<User> users = Lists.newArrayList();for (int j = 0; j < 10; j++) {User value = new User();value.setAddress("asdfjklasdjf");value.setAge(22);value.setGender(1);value.setPassword("jkljklj");value.setUserName("");List<String> strList = Lists.newArrayList();Map<String, String> strMap = Maps.newHashMap();Set<Integer> setInt = Sets.newHashSet();for (int i = 0; i < 10; i++) {strList.add("a" + i);strMap.put("a" + i, "a" + i);setInt.add(i);}value.setSetInt(setInt);value.setStrList(strList);value.setStrMap(strMap);users.add(value);}int times = 1;// long d = System.currentTimeMillis();// String jsonPrefix = "aaa{}";//// for (int i = 0; i < times; i++) {// byte[] jsonBytes = JSON.toJSONBytes(value);// byte[] prefixBytes =jsonPrefix.getBytes(Charset.forName("UTF-8"));// int prefixLength = prefixBytes.length;// int jsonLength = jsonBytes.length;// byte[] finalJsonBytes = new byte[prefixLength + jsonLength];//// System.arraycopy(prefixBytes, 0, finalJsonBytes, 0, prefixLength);// System.arraycopy(jsonBytes, 0, finalJsonBytes, prefixLength, jsonLength);// }// System.out.println(System.currentTimeMillis() - d);String json = "";String json2 = "";long d2 = System.currentTimeMillis();//String jsonPrefix2 = "aaa{}";for (int i = 0; i < times; i++) {json = JSON.toJSONString(users);// jsonBytes = jsonPrefix2 + jsonBytes;//// byte[] prefixBytes =jsonBytes.getBytes(Charset.forName("UTF-8"));}System.out.println("fastjson parser :" +(System.currentTimeMillis() - d2));ObjectMapper mapper = new ObjectMapper();//org.codehaus.jackson.map.ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();long d3 = System.currentTimeMillis();//String jsonPrefix3 = "aaa{}";for (int i = 0; i < times; i++) {//String jsonBytes = null;try {//StringWriter writer = new StringWriter();//JsonGenerator generator = newJsonFactory().createGenerator(writer);//mapper.writeValue(writer, value);//jsonBytes = writer.toString();json2 = mapper.writeValueAsString(users);//mapper.readValue(new StringReader(""), class1); } catch (Exception e) {e.printStackTrace();}// jsonBytes = jsonPrefix3 + jsonBytes;//// byte[] prefixBytes =jsonBytes.getBytes(Charset.forName("UTF-8"));}System.out.println("jackson parser :" +(System.currentTimeMillis() - d3));long d5 = System.currentTimeMillis();for (int i = 0; i < times; i++) {JSON.parseArray(json, User.class);}System.out.println("fastjson deserializer :" + (System.currentTimeMillis() - d5));long d4 = System.currentTimeMillis();for (int i = 0; i < times; i++) {try {//List<User> userList = Lists.newArrayList();mapper.readValue(json2, new TypeReference<List<User>>() {});// List<User> userList = Lists.newArrayList();// for (;iterator.hasNext();) {// userList.add(iterator.nextValue());// }//System.out.println(userList);} catch (JsonParseException e) {e.printStackTrace();} catch (JsonMappingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}System.out.println("jackson deserializer :" +(System.currentTimeMillis() - d4));}}package com.test;import java.util.List;import java.util.Map;import java.util.Set;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class User {private String userName;private String address;private int age;private int gender;private String password;private List<String> strList;private Map<String, String> strMap;private Set<Integer> setInt;public String getUserName() {return userName;}public void setUserName(String userName) {erName = userName;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public int getGender() {return gender;}public void setGender(int gender) {this.gender = gender;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public List<String> getStrList() {return strList;}public void setStrList(List<String> strList) { this.strList = strList;}public Map<String, String> getStrMap() {return strMap;}public void setStrMap(Map<String, String> strMap) { this.strMap = strMap;}public Set<Integer> getSetInt() {return setInt;}public void setSetInt(Set<Integer> setInt) {this.setInt = setInt;}}。
springMVC详解以及注解说明
springMVC详解以及注解说明基于注释(Annotation)的配置有越来越流行的趋势,Spring 2.5 顺应这种趋势,提供了完全基于注释配置Bean、装配Bean 的功能,您可以使用基于注释的Spring IoC 替换原来基于XML 的配置。
本文通过实例详细讲述了Spring 2.5 基于注释IoC 功能的使用。
概述注释配置相对于XML 配置具有很多的优势:∙ 它可以充分利用Java 的反射机制获取类结构信息,这些信息可以有效减少配置的工作。
如使用JPA 注释配置ORM 映射时,我们就不需要指定PO 的属性名、类型等信息,如果关系表字段和PO 属性名、类型都一致,您甚至无需编写任务属性映射信息——因为这些信息都可以通过Java 反射机制获取。
∙ 注释和Java 代码位于一个文件中,而XML 配置采用独立的配置文件,大多数配置信息在程序开发完成后都不会调整,如果配置信息和Java 代码放在一起,有助于增强程序的内聚性。
而采用独立的XML 配置文件,程序员在编写一个功能时,往往需要在程序文件和配置文件中不停切换,这种思维上的不连贯会降低开发效率。
因此在很多情况下,注释配置比XML 配置更受欢迎,注释配置有进一步流行的趋势。
Spring 2.5 的一大增强就是引入了很多注释类,现在您已经可以使用注释配置完成大部分XML 配置的功能。
在这篇文章里,我们将向您讲述使用注释进行Bean 定义和依赖注入的内容。
Spring2.5的注释Spring 2.5 提供了AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 和RequiredAnnotationBeanPostProcessor这四个主要的关于Annotation 的BeanPostProcessor。
Springmvc拦截器实现原理解析
Springmvc拦截器实现原理解析概述SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,⽤于对处理器进⾏预处理和后处理。
开发者可以⾃⼰定义⼀些拦截器来实现特定的功能。
过滤器与拦截器的区别:拦截器是AOP思想的具体应⽤。
过滤器servlet规范中的⼀部分,任何java web⼯程都可以使⽤在url-pattern中配置了/*之后,可以对所有要访问的资源进⾏拦截拦截器拦截器是SpringMVC框架⾃⼰的,只有使⽤了SpringMVC框架的⼯程才能使⽤拦截器只会拦截访问的控制器⽅法,如果访问的是jsp/html/css/image/js是不会进⾏拦截的⾃定义拦截器那如何实现拦截器呢?想要⾃定义拦截器,必须实现 HandlerInterceptor 接⼝。
新建⼀个Moudule ,添加web⽀持配置web.xml 和 springmvc-servlet.xml ⽂件编写⼀个拦截器package com.xiaohua.interceptor;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class MyInterceptor implements HandlerInterceptor {//在请求处理的⽅法之前执⾏//如果返回true执⾏下⼀个拦截器//如果返回false就不执⾏下⼀个拦截器public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {System.out.println("------------处理前------------");return true;}//在请求处理⽅法执⾏之后执⾏public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("------------处理后------------");}//在dispatcherServlet处理后执⾏,做清理⼯作.public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {System.out.println("------------清理------------");}}在springmvc的配置⽂件中配置拦截器<!--关于拦截器的配置--><mvc:interceptors><mvc:interceptor><!--/** 包括路径及其⼦路径--><!--/admin/* 拦截的是/admin/add等等这种 , /admin/add/user不会被拦截--><!--/admin/** 拦截的是/admin/下的所有--><mvc:mapping path="/**"/><!--bean配置的就是拦截器--><bean class="com.xiaohua.interceptor.MyInterceptor"/></mvc:interceptor></mvc:interceptors>编写⼀个Controller,接收请求package com.xiaohua.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;//测试拦截器的控制器@Controllerpublic class InterceptorController {@RequestMapping("/interceptor")@ResponseBodypublic String testFunction() {System.out.println("控制器中的⽅法执⾏了");return "hello";}}前端 index.jsp<a href="${pageContext.request.contextPath}/interceptor" rel="external nofollow" >拦截器测试</a>启动tomcat 测试⼀下!验证⽤户是否登陆(认证⽤户)实现思路有⼀个登陆页⾯,需要写⼀个controller访问页⾯。
Spring知识点总结
精品文档 . 关于spring的几个集合对象介绍 ListFactoryBean org.springframework.beans.factory.config.ListFactoryBean
ListFactoryBean类为开发者提供了一种在Spring的bean配置文件中创建一个具体的列表集合类(ArrayList和LinkedList)。 这里有一个 ListFactoryBean 示例,在运行时它将实例化一个ArrayList,并注入到一个 bean 属性。 1. 2.
3.
4. pechorin@hero.org
5. raskolnikov@slums.org
6. stavrogin@gov.org
7. porfiry@gov.org
8.
9.
10.
配置 java.util.ArrayList one 2 three
代码 public class App { public static void main(String[] args) { 精品文档 . ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml");
Customer cust = (Customer) context.getBean("CustomerBean"); System.out.println(cust);
} } 结果 Customer [lists=[one, 2, three]] Type=[class java.util.ArrayList]
MapFactoryBean org.springframework.beans.factory.config.MapFactoryBean
1. 2.
3.
4.
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
矿产资源开发利用方案编写内容要求及审查大纲
矿产资源开发利用方案编写内容要求及《矿产资源开发利用方案》审查大纲一、概述
㈠矿区位置、隶属关系和企业性质。
如为改扩建矿山, 应说明矿山现状、
特点及存在的主要问题。
㈡编制依据
(1简述项目前期工作进展情况及与有关方面对项目的意向性协议情况。
(2 列出开发利用方案编制所依据的主要基础性资料的名称。
如经储量管理部门认定的矿区地质勘探报告、选矿试验报告、加工利用试验报告、工程地质初评资料、矿区水文资料和供水资料等。
对改、扩建矿山应有生产实际资料, 如矿山总平面现状图、矿床开拓系统图、采场现状图和主要采选设备清单等。
二、矿产品需求现状和预测
㈠该矿产在国内需求情况和市场供应情况
1、矿产品现状及加工利用趋向。
2、国内近、远期的需求量及主要销向预测。
㈡产品价格分析
1、国内矿产品价格现状。
2、矿产品价格稳定性及变化趋势。
三、矿产资源概况
㈠矿区总体概况
1、矿区总体规划情况。
2、矿区矿产资源概况。
3、该设计与矿区总体开发的关系。
㈡该设计项目的资源概况
1、矿床地质及构造特征。
2、矿床开采技术条件及水文地质条件。