Spring MVC summary tutorial

Source: Internet
Author: User
Tags tld

This article will teach you how to quickly use the Spring framework. if you have a book "Spring in Action" in your hand, you 'd better start from the third part "Spring's application on the Web layer -- building the Web layer". Otherwise, it would be a nightmare!

First, I need to establish the basic concept of Spring MVC in your mind. spring-based Web applications receive http: // localhost: 8080/hello. do (in fact, The Request Path is/hello. do), Spring will send this request to a program named helloController for processing, and helloController will call another program named hello. jsp files generate HTML code and send it to the user's browser for display. the above name (/hello. do, helloController, hello. jsp) are all variables, you can change.

In Spring MVC, Java code should not be included in jsp files. Only HTML code and "forEach" and "Judgment (if)" are available. jsp files are used only as rendering (or View) templates.

Let's get started. First we need a web. xml file in the WEB-INF directory:
Java code
<? Xml version = "1.0" encoding = "UTF-8"?>
 
<Web-app version = "2.4" xmlns = "http://java.sun.com/xml/ns/j2ee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://java.sun.com/xml/ns/j2ee
Http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>

<Context-param>
<Param-name> contextConfigLocation </param-name>
<Param-value>
/WEB-INF/database. xml
/WEB-INF/applicationContext. xml
</Param-value>
</Context-param>
 
<Listener>
<Listener-class> org. springframework. web. context. ContextLoaderListener </listener-class>
</Listener>
 
<Filter>
<Filter-name> encodingFilter </filter-name>
<Filter-class> org. springframework. web. filter. CharacterEncodingFilter </filter-class>
<Init-param>
<Param-name> encoding </param-name>
<Param-value> UTF-8 </param-value>
</Init-param>
</Filter>
 
<Filter-mapping>
<Filter-name> encodingFilter </filter-name>
<Url-pattern> *. do </url-pattern>
</Filter-mapping>
 
<Servlet>
<Servlet-name> ideawu </servlet-name>
<Servlet-class> org. springframework. web. servlet. DispatcherServlet </servlet-class>
<Load-on-startup> 1 </load-on-startup>
</Servlet>
 
<Servlet-mapping>
<Servlet-name> ideawu </servlet-name>
<Url-pattern> *. do </url-pattern>
</Servlet-mapping>
 
<Welcome-file-list>
<Welcome-file> index. jsp </welcome-file>
<Welcome-file> index.html </welcome-file>
</Welcome-file-list>
 
<Jsp-config>
<Taglib>
<Taglib-uri> http://java.sun.com/jsp/jstl/core </taglib-uri>
<Taglib-location>/WEB-INF/tld/c. tld </taglib-location>
</Taglib>
<Taglib>
<Taglib-uri> http://java.sun.com/jsp/jstl/fmt </taglib-uri>
<Taglib-location>/WEB-INF/tld/fmt. tld </taglib-location>
</Taglib>
</Jsp-config>
 
</Web-app>

It is configured with the following features:

Configure the DispatcherServlet (servlet tag), which is a Java Servlet program. we name it ideawu. then we configure the Servlet ing (servlet-mapping tag), that is, the requests you want to process by the DispatcherServlet. here, we set the suffix to do (*. all URL requests are processed by the DispatcherServlet program named ideawu. select. do is just a habit, but you do not have to choose. html! Although Spring in Action chose. html, it is a very bad practice, especially when you integrate Apache and Tomcat.

Configure CharacterEncodingFilter (filter tag). Otherwise, you will find Chinese garbled characters. because my jsp and html files are both UTF-8 encoded, I set the UTF-8 In The param-value tag. it is estimated that you are using GB2312 or GBK, immediately go to the UTF-8.

Break down the configuration file. the context-param label specifies that our configuration file also has a/WEB-INF/database. and/WEB-INF/applicationContext. xml. the ContextLoaderListener (listener tag) shows which configuration files are loaded.

Since we named DispatcherServlet ideawu, we created a file named WEB-INF under the ideawu-servlet.xml directory:

Ideawu-servlet.xml:
Java code
<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE beans PUBLIC "-// SPRING // dtd bean // EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<Beans>

<Bean id = "viewResolver" class = "org. springframework. web. servlet. view. InternalResourceViewResolver">
<Property name = "prefix" value = "/WEB-INF/jsp/"/>
<Property name = "suffix" value = ". jsp"/>
</Bean>
 
<Bean id = "simpleUrlHandlerMapping" class = "org. springframework. web. servlet. handler. SimpleUrlHandlerMapping">
<Property name = "mappings">
<Props>
<Prop key = "/hello. do"> helloController </prop>
</Props>
</Property>
</Bean>
 
<Bean id = "helloController" class = "com. ideawu. HelloController">
<! --
<Property name = "helloManager" ref = "helloManager"/>
-->
</Bean>
 
</Beans>


It is configured with the following features:

Configure InternalResourceViewResolver, which is the processor of the jsp rendering template. if you tell InternalResourceViewResolver to process a template named hello, it will render/WEB-INF/jsp/hello. jsp file. put the jsp file in the/WEB-INF/jsp/directory is encouraged, this can prevent users from directly accessing the jsp file through the Controller and thus errors (some naughty people like this ).

Configure SimpleUrlHandlerMapping in the configuration file above,/hello. do requests will be processed by helloController. "/hello. do "and" helloController "are variables that you can change. but have you noticed that, hello. do. do Is the suffix. if you do not use it here (under the conditions described in this article. as a suffix, do does not have a program to process this request. because DispatcherServlet transfers the received request to SimpleUrlHandlerMapping, and DispatcherServlet does not receive the request, SimpleUrlHandlerMapping certainly cannot. you can configure multiple prop labels in the props label.

We will compile the com. ideawu. HelloController class later.

Above, we told ContextLoaderListener in the web. xml file that we have two other configuration files/WEB-INF/database. xml and/WEB-INF/applicationContext. xml.

ApplicationContext. xml:
Java code
<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE beans PUBLIC "-// SPRING // dtd bean // EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<Beans>

<Bean id = "propertyConfigurer" class = "org. springframework. beans. factory. config. PropertyPlaceholderConfigurer">
<Property name = "locations">
<List>
<Value>/WEB-INF/jdbc. properties </value>
</List>
</Property>
</Bean>
 
</Beans>

It is configured with the following features:

Read the/WEB-INF/jdbc. properties file. You can configure multiple value tags in the list tag.

Database. xml:
Java code
<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE beans PUBLIC "-// SPRING // dtd bean // EN" "http://www.springframework.org/dtd/spring-beans.dtd">
 
<Beans>
 
<! -- Remove this if your database setting is fine.
<Bean id = "dataSource" class = "org. apache. commons. dbcp. BasicDataSource" destroy-method = "close">
<Property name = "driverClassName" value = "$ {jdbc. driverClassName}"/>
<Property name = "url" value = "$ {jdbc. url}"/>
<Property name = "username" value = "$ {jdbc. username}"/>
<Property name = "password" value = "$ {jdbc. password}"/>
</Bean>
-->
 
<! -- Transaction manager for a single JDBC DataSource
<Bean id = "transactionManager" class = "org. springframework. jdbc. datasource. cetcetransactionmanager">
<Property name = "dataSource" ref = "dataSource"/>
</Bean>
-->
 
<! --
<Bean id = "attributeManager" class = "com. ideawu. core. AttributeManager">
<Property name = "dataSource" ref = "dataSource"/>
</Bean>
-->
 
Lt;/beans>

It configures the following features (however, it has been commented out ):

Configure the database connection. similar to $ {jbbc. url} is an access variable method. we can from/WEB-INF/jdbc. properties to find the value of this variable. if your database has been configured, remove the first comment.

Jdbc. properties:
Jdbc. driverClassName = com. mysql. jdbc. Driver
Jdbc. url = jdbc: mysql: // localhost/test? UseUnicode = true & characterEncoding = UTF-8
Jdbc. username = test
Jdbc. password = 12345
Now, let's write the Java code.
Java code
/*************************************** ********************
* Date: 2006-8-26
* File: HelloController. java
* Author: ideawu
**************************************** *******************/

Package com. ideawu;

Import org. springframework. web. servlet. mvc. Controller;
Mport org. springframework. web. servlet. ModelAndView;
 
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
 
/**
* @ Author ideawu
*
*/
Public class HelloController implements Controller {
/*
Private HelloManager helloManager;
 
Public void setHelloManager (HelloManager helloManager ){
This. helloManager = helloManager;
}
*/
 
Public ModelAndView handleRequest (HttpServletRequest request,
HttpServletResponse response) throws Exception {
 
Request. setAttribute ("hello_1", "Hello, Spring! ");
Request. setAttribute ("hello_2", "Hello World! ");
 
Return new ModelAndView ("hello ");
}
 
}

Return new ModelAndView ("hello"); tells InternalResourceViewResolver that the jsp Template Name is "hello. request. setAttribute ()". We can use it in the jsp file.

Hello. jsp:
Java code
<% @ Page contentType = "text/html; charset = UTF-8" %>
<% @ Taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> Hello World! </Title>
</Head>
<Body>
 
<H2 >$ {hello_1}  
<H2 >$ {hello_2}  
</Body>
</Html>

You can download the entire Web application. It runs well In Debian Linux, Tomcat 5.5.16, and JDK1.5.0. decompress the package to get a spring folder, put it in your webapps directory, and enter it in your browser.

Author "love me"
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.