Springmvc configuration, simple instance, file upload and download, Ajax request

Source: Internet
Author: User

Based on springmvc, This article uses the annotation method to explain the examples from configuration to simple common functions. The functions have been tested on the local machine and can run.

References: iteye blog;

Spring document;

1. Import relevant jar packages:

Spring-core-3.2.0.jar; spring-web-3.2.0.jar; spring-webmvc-3.2.0.jar; common-annotations.jar; commons-fileupload-1.2.2.jar.

2. In the web. xml configuration dispatcherservlet, intercept matching requests; (the default WEB-INF folder under the initialization process to find the name [servlet-name]-servlet. XML. You can also specify the classpath parameter)

<Servlet> <servlet-Name> spring </servlet-Name> <servlet-class> Org. springframework. web. servlet. dispatcherservlet </servlet-class> <load-on-startup> 1 </load-on-startup> </servlet> <servlet-mapping> <servlet-Name> spring </ servlet-Name> <! -- Here With Spring, below also need to write a file named spring-servlet.xml, mainly used to configure its controller --> <URL-pattern> *. DO </url-pattern> </servlet-mapping> <welcome-file-List> <welcome-File>/userinfo. JSP </welcome-File> </welcome-file-List>

3. Configure [servlet-name]-servlet. xml

<Context: annotation-config/> <! -- Convert the class marked with @ controller annotation to Bean --> <context: component-scan base-package = "com. Test. controllers"/> <! -- Start the annotation function of spring MVC to map requests and annotation pojo --> <! -- <Bean class = "org. springframework. web. servlet. MVC. annotation. annotationmethodhandleradapter "/> <bean id =" viewresolver "class =" org. springframework. web. servlet. view. internalresourceviewresolver "P: prefix ="/WEB-INF/View/"P: suffix = ". JSP "/> --> <! -- The default attribute file of the configuration view parser is in the classpath: views. properties --> <bean id = "resourcebundleviewresolver" class = "org. springframework. web. servlet. view. resourcebundleviewresolver "> <property name =" basename "value =" views "> </property> </bean> <! -- The setviewclass method can be used to specify the View class used by the parser to generate a view --> <bean id = "viewresolver" class = "org. springframework. web. servlet. view. internalresourceviewresolver "P: viewclass =" org. springframework. web. servlet. view. jstlview "P: prefix ="/WEB-INF/"P: suffix = ". JSP "/> <! -- File Upload configuration --> <bean id = "multipartresolver" class = "org. springframework. web. multipart. commons. commonsmultipartresolver "P: defaultencoding = "UTF-8"> <property name = "maxuploadsize" value = "1024000000"/> <property name = "resolvelazily" value = "true"/> </bean>

4. Write the Controller class

@ Controller @ requestmapping ("/userinfo. do ") public class usercontroller {/*** file uploads and obtains the user object. If the user object is not connected to the database, only the value is obtained, * @ Param user * @ Param Request * @ Param files File Group * @ return * @ throws exception */@ requestmapping (Params = "method = saveuser") in the file upload directory ") public modelandview saveuser (User user, httpservletrequest request, @ requestparam ("FILENAME") multipartfile [] files) throws exception {modelandview MAV = new modelandvie W (); system. Out. println (user. GetUserName () + "password" + User. getuserpwd (); Mav. addobject ("message", "success! "); Mav. addobject ("user", user); // list <multipartfile> files = mrequest. getfiles ("FILENAME"); string uploadpath = request. getsession (). getservletcontext (). getrealpath ("/"); system. out. println (uploadpath); // system. out. println (files. isempty (); For (multipartfile: Files) {If (multipartfile. isempty () continue; system. out. println (multipartfile. getoriginalfilename (); fileoutputstream fileos = new fileoutputstream (uploadpath + multipartfile. getoriginalfilename (); fileos. write (multipartfile. getbytes (); system. out. println (fileos); fileos. close ();}/* fileoutputstream fileos = new fileoutputstream (uploadpath + file. getoriginalfilename (); fileos. write (file. getbytes (); system. out. println (fileos); fileos. close (); */MAV. setviewname ("userview"); // you can specify the returned view. set return MAV;} In Properties ;}

5. Compile JSP pages with annotations. No other configurations are required. Like struts2, the input name attribute corresponds to Java Bean and the parameters are automatically encapsulated.

<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "%> <% string Path = request. getcontextpath (); string basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverport () + path + "/"; %> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <HTML> 

6. Configure views. properties (found under classpath by default)

Userview. (class) = org. springframework. Web. servlet. View. jstlview

Userview. url =/WEB-INF/userinfo. jsp

The preceding steps allow you to upload files and obtain user information.

Ii. Below is a simple post of the file download code

/*** File Download ** @ Param Request * @ Param response * @ return because it is only a test, a lot of information is manually written to death. * @ Throws exception */@ requestmapping (Params = "method = downloadfile") Public modelandview downloadfile (httpservletrequest request, httpservletresponse response) throws exception {bufferedinputstream Bis = NULL; required Bos = NULL; // string downloadpath = "RR. SQL "; string realname =" RR. SQL "; // set the name of the downloaded file string filename = request. getparameter ("FILENAME"); // obtain the complete file name system. out. println (filename ); Long filelength = new file (filename ). length (); string ctxpath = request. getsession (). getservletcontext (). getrealpath ("/"); response. setcontenttype ("application/octet-stream"); response. setheader ("content-disposition", "attachment; filename =" + new string (realname. getbytes ("UTF-8"), "ISO8859-1"); response. setheader ("Content-Length", String. valueof (filelength); Bis = new bufferedinputstream (New File Inputstream (filename); Bos = new bufferedoutputstream (response. getoutputstream (); byte [] buff = new byte [2048]; int bytesread; while (-1! = (Bytesread = bis. read (buff, 0, Buff. length) {Bos. write (buff, 0, bytesread);} bis. close (); Bos. close (); modelandview MAV = new modelandview (); return NULL ;}

JSP Download Page

<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "%> <% string Path = request. getcontextpath (); string basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverport () + path + "/"; %> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <HTML> 

The above parameter filename is written directly because the database is not connected.

Iii. Ajax request JSON data

Step 1: Add a JSON jar package example: ackson-core-asl-1.7.2.jar, jackson-mapper-asl-1.7.2.jar

Step 2: Add <MVC: annotation-driven/> to the spring configuration file.(Httpmessageconverter must be enabled)

Step 3: Add @ responsebody to the returned object to return the content or object as the HTTP response body, call the adapter conversion object suitable for httpmessageconverter, and write it to the output stream. (After enabling this annotationAnnotationmethodhandleradapter initializes the following seven converters:Bytearrayhttpmessageconverter
Stringhttpmessageconverter
Resourcehttpmessageconverter
Sourcehttpmessageconverter
Xmlawareformhttpmessageconverter
Jaxb2rootelementhttpmessageconverter
Mappingjacksonhttpmessageconverter --- the default JSON protocol of spring is completed by Jackson)

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.