Mobile Marketplace Fourth "Controller configuration, add brand file upload and data validation"

Source: Internet
Author: User
Tags aop json relative trim
Controller Layer Configuration

Writing a SPRINGMVC configuration file

Springmvc.xml


<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xs I= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc= "Http://www.springframework.org/schema/mvc" xmlns:
    context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi:schemalocation= "http://www.springframework.org/schema/  
    Beans Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd Http://www.springframework.org/schema/mvc 
    Http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd Http://www.springframework.org/schema/context 
    Http://www.springframework.org/schema/context/spring-context-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Http://www.springframework.org/schema/aop/spring-aop-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX http://www . springframework.org/schema/tx/spring-tx-3.0.xsd "> <context:component-scan base-package=" Com.rl.ecps.controller "/> <bean class=" Org.springframewo Rk.web.servlet.view.InternalResourceViewResolver "> <property name=" prefix "value="/web-inf/shop/"></p roperty> <property name= "suffix" value= ". jsp" ></property> </bean> <bean id= "multi Partresolver "class=" Org.springframework.web.multipart.commons.CommonsMultipartResolver "> <property name=" M
 Axuploadsize "value=" 1024000 "></property> </bean> </beans>
Add branding

On the prototype interface, we are all "dead" data, and we need to replace the database records with these "dead" data.

Upload Image

The server console uploads images to our image servers, while the portal accesses images from the image server ...

In front, we have set up a picture server, then how we will upload the console image "to" the image server ...

when uploading images using the Jersey client API to invoke RESTful Web services , Jersey 1 is an open source, Jax-rs (Java API specification for RESTful WEB services) that can be used in a production environment, a JSR -311) implementation. With Jersey, it is easy to use Java to create a RESTful Web Services.

Config file Upload parser:

    <bean id= "Multipartresolver" class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" >
        <property name= "maxuploadsize" value= "1024000" ></property>
    </bean>

We uploaded to the image server, so we need to configure the corresponding path .... This configuration file should be written in the core, as it is likely to be reused.

It is important to note that the file server is set to writable "default is read-only"

Refer to the following blog post:
http://blog.csdn.net/hon_3y/article/details/77840532

Write the tool class to get the corresponding data

public class Resourcesutils {public
    static string Readprop (String key) {
        InputStream in = RESOURCESUTILS.CLASS.G Etclassloader (). getResourceAsStream ("System.properties");
        Properties prop = new properties ();
        try {
            prop.load (in);
        } catch (IOException e) {
            e.printstacktrace ();
        }

        return Prop.getproperty (key);
    }

}

Write a controller that handles file uploads

If there are multiple files or we do not know the name of the uploaded input, we can use the request object to get the map and then get the corresponding file

        Convert request to complex request
        multiparthttpservletrequest Mr = (multiparthttpservletrequest) request;
        Get file
        map<string, multipartfile> Map = Mr.getfilemap ();
        set<string> set = Map.keyset ();
        Iterator<string> it = Set.iterator ();
        String fileinputname = It.next ();
        Multipartfile MF = map.get (fileinputname);

And now we know the name of input, so here I'm going to use the Multipartfile object directly to get it .

@Controller @RequestMapping ("/upload") public class Uploadebbrandpiccontroller {@RequestMapping ("/uploadpic.do") public void Uploadpic (@RequestParam multipartfile Imgsfile, writer writer) throws IOException {//upload file name is not the same, because
        Here we set the name of the file String filename = new SimpleDateFormat ("Yyyymmddhhmmsssss"). Format (new Date ());
        Random random = new random ();
        for (int i = 0; i < 3; i++) {filename = filename + random.nextint (10);

        }//Get the original name of the file String OriginalFilename = Imgsfile.getoriginalfilename ();

        Gets the suffix of the file String suffix = originalfilename.substring (Originalfilename.lastindexof ("."));
         /*** * Absolute path is left to the page src attribute to do the display of the relative path is saved in the database, through input to commit.
        *///Get the absolute path of the uploaded file String realpath = Resourcesutils.readprop ("File_path") + "/upload/" +filename+suffix;

        Gets the relative path of String RelativePath = "/upload/" +filename+suffix; Creating Jersy Client Clients Client = Client.create ();

        Create a Web resource object WebResource WR = Client.resource (Realpath);
        Get the binary data of the file, use the Web resource object to upload byte[] bytes = Imgsfile.getbytes ();

        Wr.put (bytes);
        Use the JSON format to return our absolute and relative paths.
        Jsonobject Jo = new Jsonobject ();
        Jo.accumulate ("Realpath", Realpath);
        Jo.accumulate ("RelativePath", RelativePath);
        String result = Jo.tostring ();
    Writer.write (result);

 }
}

In the front-end we are using Ajax to upload files asynchronously, when the image option is modified, we trigger the event to upload the image to our image server,.

function Submitupload () {
            var opt = {
                //re-specify the value of the action of the form
                URL: "${path}/upload/uploadpic.do",
                type: " Post ",
                Datetype:" JSON ",
                success:function (responsetext) {
                    //resolving extra string data causes the JSON problem to be unresolved" additional blog posts "
                    var Jsonobj = $.parsejson (Responsetext.replace (/<.*?>/ig, ""));
                    $ ("#imgsImgSrc"). attr ("src", jsonobj.realpath);
                    $ ("#imgs"). Val (Jsonobj.relativepath);
                },
                error:function () {
                    alert ("System error");
                }
            };
            $ ("#form111"). Ajaxsubmit (opt);
        }

Successfully uploaded the image to the image server.

Data Validation

The interface for adding products is like this, we need to verify

And calibration We have two ways: the foreground using JS check the background and then check

We do this by customizing several properties in the input box: TheREG2 indicates that it must be verified, and REG1 indicates that the checksum is not verifiable. If the REG1 has data, then it is necessary to verify

        <div class= "edit Set" > <p><label><samp>*</samp> brand Name: </label><i Nput type= "text" id= "brandname" name= "brandname" class= "text State" reg2= "^[a-za-z0-9\u4e00-\u9fa5]{1,20}$" tip= " Must be in English or numeric characters, length 1-20 "/> <span></span> </p> <p><label C lass= "alg_t" ><samp>*</samp> brand logo:</label> </p> <p><label></label><input type= ' file ' size= ' id= ' img SFile ' name= ' imgsfile ' class= "file" Onchange= ' Submitupload () '/><span id= ' submitimgtip ' class= ' pos ' > Please upload the image width is 120px, height is 50px, size does not exceed 100K. </span> <input type= ' hidden ' id= ' IMGs ' name= ' IMGs ' value= ' ' reg2= ' ^.+$ ' tip= ' Pro. You forgot to upload the image.  "/> </p> <p><label> brand website: </label><input type=" text "name=" website " class= "text State" Maxlength= "100 "tip=" please start with/http "reg1=" http:///* "/> <span class=" pos ">&nbsp;</span> &L t;/p> <p><label class= "alg_t" > Brand Description: </label><textarea rows= "4" cols= "Name=" brandDes C "Class=" is "reg1=" ^ (. |
            \ n) {0,300}$ "tip=" any character, length 0-300 "></textarea> <span class=" POS ">&nbsp;</span> </p> <p><label> Sort: </label><input type= "text" id= "Brandsort" reg1= "^[1-9][0-9 ]{0,2}$ "tip=" sort can only enter 1-3-digit positive integer "name=" Brandsort "class=" text small "/> <span class=" POS ">&nbsp; </span> </p> <p><label>&nbsp;</label><input type= "Submit" Nam E= "Button1" D class= "Hand btn83x23" value= "complete"/><input type= "button" class= "Hand btn83x23b" id= "Reset1" value= " Cancel ' onclick= ' Backlist (' ${backurl} ') '/> </p> </div>

First of all, we first write the front desk check ...

When the form is submitted, we validate the data on the form

detects each required input box data, if each required input box data matches the content, then detects whether the brand name is duplicated.

        $ (function () {$ ("#form111"). Submit (function () {/*) sets the identity amount to true if the checksum does not pass set to false*/
                var issubmit = true;
                    /* Get each required input box data */$ ("[REG2]"). each (function () {var tip = $ (this). attr ("Tip");
                    var regstr = $ (this). attr ("REG2");
                    /* Get the JS Check object */var reg = new RegExp (REGSTR);

                    var value = $.trim ($ (this). Val ());
                        /* Verify that the value entered matches the check rule */if (!reg.test (value)) {/* Fills the wrong information into span */
                        $ (this). Next ("span"). HTML ("<font color= ' Red ' >" + Tip + "</font>");
                        Issubmit = false;
                        Interrupts each use return false, cannot use return;
                    return false; } else {//required data rules are passed, then determine whether the brand name has duplicate "background check" var InputName = $ (this).attr ("name"); if (InputName = = "Brandname") {$.ajax ({url: "${path}/brand/v
                                Alidatebrandname.do ", type:" Post ", Async:false,
                                data:{Brandname:value},
                                    DataType: "Text", Success:function (responsetest) { if (ResponseTest = = "No") {$ ("#brandNameSpan"). HTML ("Name of the brand
                                        cannot be the same.! ");
                                        Issubmit = false;
                                    return false;
                                    }else{$ (this). Next ("span"). HTML (""); }}, Error:funCtion () {Alert ("system error");
                        }
                            });

                }
                    }
                });
            return issubmit;
        });

 });

Controller method for detecting the same name

    @RequestMapping ("/validatebrandname.do") public
    void Validatebrandname (String brandname, Writer out) throws IOException {

        //= Success
        String responsetest = "yes";

        Search the database by name
        list<ebbrand> brands = Ebbrandservice.selectbrandbyname (brandname);
        If the returned collection has brand, then it proves that the database has the same branding
        if (brands! = NULL && brands.size () > 0) {
            responsetest = "no";
        }

        Out.write (ResponseTest);

    }

If the brand name is the same, submission is not allowed.

For non-mandatory data items, if the user fills in the data, then it must be written according to our Rules

 * * Not required data, if filled out, you must follow the rules */$ ("[REG1]"). each (function () {
                    var tip = $ (this). attr ("Tip");
                    var regstr = $ (this). attr ("REG1");
                    /* Get the JS Check object */var reg = new RegExp (REGSTR);

                   var value = $.trim ($ (this). Val ()); /* If the user fills in the data, then you need to follow the rules */if (value!=null && value!= "") {if (!reg.test (valu e) {/* Fill in the wrong information into span */$ (this). Next ("span"). HTML ("<font color="
                           Red ' > + tip + ' </font> ');
                           Issubmit = false;
                           Interrupts each use return false, cannot use return;
                       return false; }else{

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.