4

I'm trying to realise the point of the xmlns definitions of the following xml-file:

<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"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">   
</beans>

I didn't get what schemaLocation specified here. Why, for instance, should I add both xmlns:mvc = "http://www.springframework.org/schema/mvc" and http://www.springframework.org/schema/mvc to the schemaLocation attribute to use mvc:xxx_something_xxx in my spring config-file?

I just want to understand what I do every time when I start to create spring-mvc apps, not just copy-paste it from google without understanding.

user3663882
  • 6,957
  • 10
  • 51
  • 92

2 Answers2

2

xmlns defines a namespace. If you want to use mvc:xxx you have to define what mvc namespace is.

xsi:schemaLocation defines where the XSD(for XML validation) are situated.

If I'm not mistaken, the latest is not mandatory but if you don't set it then you might use invalid XML without noticing it.

Related to :

Community
  • 1
  • 1
alain.janinm
  • 19,951
  • 10
  • 65
  • 112
2

These are 2 different things:

  • xmlns:mvc="http://www.springframework.org/schema/mvc" is a declaration, here you say "hey, when I'm gonna use "mvc" prefix in my XML code I'm gonna use elements and types from this namespace"; the declared namespace should match with the xmlns attribute in the desired schema so it can be identified
  • schemaLocation="http://www.springframework.org/schema/mvc" is a schema location, like a classpath in java or path in linux it's a list of sources where XML processor can find the XSD schema files; the schema you desire should be located in this list so the XSD file can be found

Without a declaration you can't refer to elements and types in a namespace that is different from current schema namespace (which is xmlns="http://www.springframework.org/schema/beans" in your case).

Withour a schema location you will get an error that the element or type can not be found.

davidluckystar
  • 928
  • 5
  • 15
  • So, as far as I understand when we use `mvc:xxx_smth_xxx` the `SAXParser` go to the URL specified in the `schemaLocation` in order to get `XSD` schemas and then invoking validation. But it's still working when I turned off my internet connection, why? – user3663882 Dec 31 '14 at 19:37
  • because it have a cache of course, consider anytime you want to deal with your applicationContext.xml you read schemas from internet - this would end very bad – davidluckystar Jan 07 '15 at 15:16