The first spring MVC program that uses Ajax

Source: Internet
Author: User
Tags bind json xmlns tomcat

First, the steps and methods of constructing the Spring MVC program using MAVEN and IntelliJ:

1. Use the following command to create a web app named Counterwebapp.

MVN Archetype:generate-dgroupid=com.chf-dartifactid=counterwebapp-darchetypeartifactid=maven-archetype-webapp
-dinteractivemode=false

2. Create the package directory and file for your source code under the Counterwebapp/src/main/java directory.

3. Configure the dependencies that spring MVC needs to add in Pom.xml.

As shown in the following code:

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:s chemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" > <modelversion >4.0.0</modelVersion> <groupId>com.chf</groupId> <artifactid>counterwebapp</ artifactid> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name> Counterwebapp Maven webapp</name> <url>http://maven.apache.org</url> <properties> <jdk. Version>1.7</jdk.version> <spring.version>4.1.1.RELEASE</spring.version> <jstl.version& Gt;1.2</jstl.version> <junit.version>4.11</junit.version> <logback.version>1.0.13</ logback.version> <jcl-over-slf4j.version>1.7.5</jcl-over-slf4j.version> </properties> <de Pendencies> <dependency> <groupId>Junit</groupid> <artifactId>junit</artifactId> &LT;VERSION&GT;${JUNIT.VERSION}&LT;/VERSION&G
      T <scope>test</scope> </dependency> <!--spring core--> <dependency> <gro Upid>org.springframework</groupid> <artifactId>spring-core</artifactId> <version>${ spring.version}</version> <exclusions> <exclusion> <groupid>commons-loggin g</groupid> <artifactId>commons-logging</artifactId> </exclusion> </exc lusions> </dependency> <dependency> <groupId>org.slf4j</groupId> <artif Actid>jcl-over-slf4j</artifactid> <version>${jcl-over-slf4j.version}</version> </depende ncy> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api< /artifactid>
      <version>2.5</version> <!--<scope>provided</scope>--> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactid>logback-classic</a
      rtifactid> <version>${logback.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <versi on>${spring.version}</version> </dependency> <dependency> <groupid>org.springfra Mework</groupid> <artifactId>spring-webmvc</artifactId> <version>${spring.version}< /version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> &L T;artifactid>json-lib</artifactid> <version>2.3</version> <classifier>jdk15</cla Ssifier> &LT;/DEPEndency> <!--jstl--<dependency> <groupId>jstl</groupId> <artifactid >jstl</artifactId> <version>${jstl.version}</version> </dependency> </dependenc Ies> <build> <!--The resulting war file name--<finalName>CounterWebApp</finalName> <plugins&

      Gt 
        <!--Set JDK Compiler level--<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> &lt ;configuration> <source>${jdk.version}</source> <target>${jdk.version}</target > <encoding>GBK</encoding> </configuration> </plugin> <!--Fo R Maven Tomcat Plugin-<plugin> <groupId>org.apache.tomcat.maven</groupId> & Lt;artifactid>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <!--Deploy to server--> <url>http://localhost:8080/manager/text</url> <serve R>tomcat7server</server> <path>/CounterWebApp</path> </configuration> &
 lt;/plugin> </plugins> </build> </project>

4. Then use MVN clean && mvn install to run the program.

5. Problems encountered and workarounds:

1) The following error was encountered during the MVN install process:

Fatal error compiling:?? Mainland?? Ŀ?? Fen?? 1.7, [Help 1]

Workaround:

Add the following configuration in the ~/.bash_profile file. When you are finished adding, run the source ~/.bash_profile.

Alias javac= ' Javac-j-dfile.encoding=utf-8-encoding UTF-8 '

Alias Java= ' Java-dfile.encoding=utf-8 '

Export Lang=en_us. UTF-8

Export Lc_all=en_us. UTF-8

2) After this, MVN install again encountered error: Fatal error compiling:invalid target release:1.7

Workaround:

Add a line below the configuration in the ~/.bash_profile file. When you are finished adding, run the source ~/.bash_profile.

Export java_home= '/library/java/javavirtualmachines/jdk1.7.0_60.jdk/contents/home '


Second, create a program for the first spring MVC.

1. My understanding of Spring MVC:

1) The structure of spring MVC consists mainly of the following sections:

Dispatcherservlet: Forwards the request to the controller.

Controller: The request is processed in detail.

Handler Mapping: Mapping processor, responsible for mapping the central processing Unit, forwarded to the Controller when the mapping strategy.

Modelandview: The wrapper class for the data and view layers returned by the server.

Viewresolver&view: View parser, parse specific view.

Interceptors: interceptors, which intercept our defined requests and do the processing work.

2) The specific processing flow of spring MVC is shown in the following figure:



2. The purpose of the example: in a Web program, there is a class of programs, its service end processing time is relatively long. Due to the long processing time, such programs may cause the request to time out. This is often addressed in the way that applications use asynchronous requests. Not used this way before, so first write an extremely simple program.

The purpose of this program is to use Ajax to send a request to the server every 1s. Server-side accounting, if the count reaches 20, returns a finish to the client (indicating that the server's task is complete), and stops sending the request if the client receives a message that the service-side task has completed.


3. Concrete implementation of the example:

directly on the code and configuration of each configuration file

1) Controller class:

Package Com.chf.controller;
Import Com.chf.services.AsyncServiceImpl;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;
Import Org.springframework.ui.ModelMap;
Import org.springframework.web.bind.annotation.PathVariable;
Import org.springframework.web.bind.annotation.RequestMapping;

Import Org.springframework.web.bind.annotation.RequestMethod;
Import Javax.annotation.Resource;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import Com.chf.util.ResoponseUtil;
 /** * Created by Administrator on 15-1-31. *//*there must be a Controller annotation or the application would doesn ' t work. */@Controller public class Basecontrolle
    R {@Autowired Asyncserviceimpl asyncservice;
@Autowired Resoponseutil Responseutil;
    @RequestMapping (value = "Async/{key}") @RequestMapping (value = "{key}")//async/{key}?public string Asynctest (HttpServletRequest req, HttpServletResponse resp, @PathVariable string
        Key) throws Exception {Asyncservice.asyncmethod (key);
    return "Common/async"; }//@RequestMapping (params= "Method=getstatus", method = Requestmethod.get) @RequestMapping ("/status") public String Showasyncstatus (httpservletrequest req, HttpServletResponse resp) throws Exceptio n {//HttpServletResponse resp, @PathVariable String key) throws Exception {Sys
        Tem.out.println ("in Status new!!");
        String status = asyncservice.getprocess (null);
        Responseutil.outputjson (resp, "{\" status\ ": \" "+ Status +" \ "}");
    return null;
                                   } @RequestMapping (value = "/clear") public String Clearasyncstatus (HttpServletRequest req, HttpServletResponse resp, @PathVariable String key) throws Exception {AsyncservIce.clearcache (key);
        Responseutil.outputjson (resp, "{\" status\ ": \" Ok\ "}");
    return null; }
}

2) Service Interface and service method:

Package com.chf.services;

/**
 * Created by HFC on 15/10/21.
 *
/public interface Asyncservice {
    void Asyncmethod (String cacheKey) throws Exception;

    public string getprocess (String cacheKey) throws Exception;

    public void ClearCache (String cacheKey) throws Exception;

}
Package com.chf.services;
 /** * Created by HFC on 15/10/21.
*/import Com.chf.services.AsyncService;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.scheduling.annotation.Async;

Import Org.springframework.stereotype.Service; @Service ("Asyncservice") public class Asyncserviceimpl implements Asyncservice {//@Autowired//Stringredistempla

    Te Stringredistemplate;
    Integer count = 0;
        @Override @Async public void Asyncmethod (String cacheKey) throws Exception {int maxstep = 20;
            for (int i = 0; i < Maxstep; i++) {Thread.Sleep (2000);
count++;
        Stringredistemplate.opsforvalue (). Set (CacheKey, (i + 1) + "/" + Maxstep);
        }} @Override public string getprocess (String CacheKey) throws Exception {count++;
        if (count>=20) return "Finish";
    return null; } @Override public void ClearCache (String cacheKey) throws Exception {//stringredistemplate.delete (CacheKey);
    Count = 0;
 }


}

3) index.jsp:

 

4) configuration file:

Web. xml:

<web-app xmlns= "Http://java.sun.com/xml/ns/javaee" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version= "2.5" > <display-name>counter Web application </display-name> <servlet> <serv Let-name>mvc-dispatcher</servlet-name> <servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>1</ load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name > <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> &LT;SERVLET-NAME&G T;default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> < Context-param> <param-name>contextConfigLocation</param-name> <param-value>/web-inf/mvc-dispatcher-servlet.xml</param-value> </context-param> <listener> <listener-class>
 Org.springframework.web.context.contextloaderlistener</listener-class> </listener> </web-app>
mvc-dispatch-servlet.xml File:

<web-app xmlns= "Http://java.sun.com/xml/ns/javaee" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version= "2.5" > <display-name>counter Web application </display-name> <servlet> <serv Let-name>mvc-dispatcher</servlet-name> <servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>1</ load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name > <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> &LT;SERVLET-NAME&G T;default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> < Context-param> <param-name>contextConfigLocation</param-name> <param-value>/web-inf/mvc-dispatcher-servlet.xml</param-value> </context-param> <listener> <listener-class>
 Org.springframework.web.context.contextloaderlistener</listener-class> </listener> </web-app>

4. Launch Tomcat and enter localhost:8080 in the browser.

Third, the attention point:
1, the service side returns the format of the JSON data:

1) When returning data, set the mimetype to:

Response.setcontenttype ("Application/json;charset=utf-8");

2) The writing format for JSON data is: name/value pairs.

Name/value pairs include the field name (in double quotation marks), followed by a colon, and then the value:

"FirstName": "John"
So the service side should pay attention to double quotes when returning. Otherwise, the results of the browser parsing are incorrect.

2. Web. XML is configured with the file name of its context as down.

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value> <span style= "color: #ff6666;" >/WEB-INF/mvc-dispatcher-servlet.xml</span></param-value>
</context-param>

3. When using annotations to use the bean, you need to configure the relevant bean in Mvc-dispatcher-servlet.xml. Only after configuration can you use the.

4. The following configuration is available in Web. xml:

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class>
    <load-on-startup>1</ load-on-startup>
</servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher </servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
All URLs will be intercepted by the controller. So that jquery.js resources cannot be found in index.jsp.

To solve this problem: A resource interception configuration was added as follows:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</ Url-pattern>
</servlet-mapping>

5. The 400 error encountered during the request is due to inconsistent parameters of the requested parameter and the service side.


Related Article

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.