• ckediter


    ckediter

    ##<link rel='stylesheet' href='/css/index.css' />

     <script type="text/javascript" src="/ckeditor/ckeditor.js"></script>

                <textarea name="editor1" id="editor1" rows="10" cols="80">

                </textarea>

                <div style="margin-top:3rem;">

                    消息标题:<input type="text" id="ctitle" style="500px;"/>

        <input type="button" id="button1" value="提交" style="height:2.5rem;100%;font-size:1.2rem;letter-spacing:3rem;"/>

                </div>

             <script type="text/javascript">

                    $(function(){

                          CKEDITOR.replace( 'editor1', {

                            filebrowserUploadUrl: '$!{base}/haliluya/uploadimg.html'

                        });

                        $("#button1").click(function(){

                            var editor = CKEDITOR.instances.editor1;

                             $.ajax({

                                url : "/haliluya/uploadContent.html",

                                data : {

                                    'editorData' : editor.getData(),

                                    'ctitle' : $("#ctitle").val()

                                },

                                type : "POST",

                                success : function(result) {

                                    if (result) {

                                        alert("保存成功");

                                    }else{

                                        alert("提交失败");

                                    }

                                },

                                error : function(request) {

                                    alert("sorry!");

                                }

                            }, "json");

                        });

                    });

                </script>

    package shareAction;

    import java.io.File;

    import java.io.PrintWriter;

    import javax.servlet.ServletContext;

    import javax.servlet.http.HttpServletRequest;

    import javax.servlet.http.HttpServletResponse;

    import javax.servlet.http.HttpSession;

    import org.springframework.beans.factory.annotation.Autowired;

    import org.springframework.stereotype.Controller;

    import org.springframework.util.FileCopyUtils;

    import org.springframework.web.bind.annotation.RequestMapping;

    import org.springframework.web.bind.annotation.ResponseBody;

    import org.springframework.web.multipart.MultipartFile;

    import org.springframework.web.multipart.MultipartHttpServletRequest;

    import shareMode.GoodNews;

    import shareService.GoodNewsService;

    @Controller

    @RequestMapping({"/haliluya"})

    public class Halelujah

    {

      @Autowired

      private GoodNewsService goodNewsService;

      @RequestMapping({"/uploadContent"})

      @ResponseBody

      public boolean uploadContent(String editorData, String ctitle)

      {

        boolean ok = true;

        GoodNews goodNews = new GoodNews();

        goodNews.setContent(editorData);

        goodNews.setCtitle(ctitle);

        int insert = this.goodNewsService.insertGoodNewsService(goodNews);

        if (insert <= 0) {

          ok = false;

        }

        return ok;

      }

      @RequestMapping({"/uploadimg"})

      public void execute(HttpServletResponse response, MultipartHttpServletRequest multipartHttpServletRequest, HttpServletRequest httpServletRequest)

        throws Exception

      {

        MultipartFile file = multipartHttpServletRequest.getFile("upload");

        String filename = file.getOriginalFilename();

        String imgtype = filename.substring(filename.lastIndexOf("."));

        String localhostUrl = "images/contentImg/";

        String ctxPath = multipartHttpServletRequest.getSession().getServletContext().getRealPath("/") + localhostUrl;

        File dirPath = new File(ctxPath);

        if (!dirPath.exists()) {

          dirPath.mkdir();

        }

        filename = String.valueOf(Math.random()) + imgtype;

        File uploadFile = new File(ctxPath + filename);

        FileCopyUtils.copy(file.getBytes(), uploadFile);

        String URL = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + httpServletRequest.getContextPath() + "/";

        String callbackUrl = URL + localhostUrl + filename;

        String callback = httpServletRequest.getParameter("CKEditorFuncNum");

        PrintWriter out = response.getWriter();

        out.println("<script type="text/javascript">");

        out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + callbackUrl + "','')");

        out.println("</script>");

      }

      @RequestMapping({"/uploadNews"})

      public String uploadNews()

      {

        return "/b/uploadNews";

      }

    }

    Joda Time

    2016年5月17日

    18:24

    http://www.joda.org/joda-time/

    Let me show difference between Joda Interval and Days:

    DateTime start = new DateTime(2012, 2, 6, 10, 44, 51, 0);
    DateTime end = new DateTime(2012, 2, 6, 11, 39, 47, 1);
    Interval interval = new Interval(start, end);
    Period period = interval.toPeriod();
    System.out.println(period.getYears() + " years, " + period.getMonths() + " months, " + period.getWeeks() + " weeks, " + period.getDays() + " days");
    System.out.println(period.getHours() + " hours, " + period.getMinutes() + " minutes, " + period.getSeconds() + " seconds ");
    //Result is:
    //0 years, 0 months, *1 weeks, 1 days*
    //0 hours, 54 minutes, 56 seconds

    //Period can set PeriodType,such as PeriodType.yearMonthDay(),PeriodType.yearDayTime()...
    Period p = new Period(start, end, PeriodType.yearMonthDayTime());
    System.out.println(p.getYears() + " years, " + p.getMonths() + " months, " + p.getWeeks() + " weeks, " + p.getDays() + "days");
    System.out.println(p.getHours() + " hours, " + p.getMinutes() + " minutes, " + p.getSeconds() + " seconds ");
    //Result is:
    //0 years, 0 months, *0 weeks, 8 days*
    //0 hours, 54 minutes, 56 seconds

    来自 <http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances>

      // from Joda to JDK
        DateTime dt = new DateTime();
        Date jdkDate = dt.toDate();

    // from JDK to Joda
        dt = new DateTime(jdkDate);

    Similarly, for JDK Calendar:

        // from Joda to JDK
        DateTime dt = new DateTime();
        Calendar jdkCal = dt.toCalendar(Locale.CHINESE);

    // from JDK to Joda
        dt = new DateTime(jdkCal);

    and JDK GregorianCalendar:

        // from Joda to JDK
        DateTime dt = new DateTime();
        GregorianCalendar jdkGCal = dt.toGregorianCalendar();

    // from JDK to Joda
        dt = new DateTime(jdkGCal);

    来自 <http://www.joda.org/joda-time/userguide.html>

    Querying DateTimes

    The separation of the calculation of calendar fields (DateTimeField) from the representation of the calendar instant (DateTime) makes for a powerful and flexible API. The connection between the two is maintained by the property (DateTime.Property) which provides access to the field.

    For instance, the direct way to get the day of week for a particular DateTime, involves calling the method

        int iDoW = dt.getDayOfWeek();

    where iDoW can take the values (from class DateTimeConstants).

        public static final int MONDAY = 1;
        public static final int TUESDAY = 2;
        public static final int WEDNESDAY = 3;
        public static final int THURSDAY = 4;
        public static final int FRIDAY = 5;
        public static final int SATURDAY = 6;
        public static final int SUNDAY = 7;

    Accessing fields

    The direct methods are fine for simple usage, but more flexibility can be achieved via the property/field mechanism. The day of week property is obtained by

        DateTime.Property pDoW = dt.dayOfWeek();

    which can be used to get richer information about the field, such as

        String strST = pDoW.getAsShortText(); // returns "Mon", "Tue", etc.
        String strT = pDoW.getAsText(); // returns "Monday", "Tuesday", etc.

    which return short and long name strings (based on the current locale) of the day-of-week. Localized versions of these methods are also available, thus

        String strTF = pDoW.getAsText(Locale.FRENCH); // returns "Lundi", etc.

    can be used to return the day-of-week name string in French.

    Of course, the original integer value of the field is still accessible as

        iDoW = pDoW.get();

    The property also provides access to other values associated with the field such as metadata on the minimum and maximum text size, leap status, related durations, etc. For a complete reference, see the documentation for the base class AbstractReadableInstantFieldProperty

    In practice, one would not actually create the intermediate pDoW variable. The code is easier to read if the methods are called on anonymous intermediate objects. Thus, for example,

        strT = dt.dayOfWeek().getAsText();
        iDoW = dt.dayOfWeek().get();

    would be written instead of the more indirect code presented earlier.

    Note: For the single case of getting the numerical value of a field, we recommend using the get method on the main DateTime object as it is more efficient.

        iDoW = dt.getDayOfWeek();

    Date fields

    The DateTime implementation provides a complete list of standard calendar fields:

        dt.getEra();
        dt.getYear();
        dt.getWeekyear();
        dt.getCenturyOfEra();
        dt.getYearOfEra();
        dt.getYearOfCentury();
        dt.getMonthOfYear();
        dt.getWeekOfWeekyear();
        dt.getDayOfYear();
        dt.getDayOfMonth();
        dt.getDayOfWeek();

    Each of these also has a corresponding property method, which returns a DateTime.Property binding to the appropriate field, such as year() or monthOfYear(). The fields represented by these properties behave pretty much as their names would suggest. The precise definitions are available in the field reference.

    As you would expect, all the methods we showed above in the day-of-week example can be applied to any of these properties. For example, to extract the standard month, day and year fields from a datetime, we can write

        String month = dt.monthOfYear().getAsText();
        int maxDay = dt.dayOfMonth().getMaximumValue();
        boolean leapYear = dt.yearOfEra().isLeap();

    Time fields

    Another set of properties access fields representing intra-day durations for time calculations. Thus to compute the hours, minutes and seconds of the instant represented by aDateTime, we would write

        int hour = dt.getHourOfDay();
        int min = dt.getMinuteOfHour();
        int sec = dt.getSecondOfMinute();

    Again each of these has a corresponding property method for more complex manipulation. The complete list of time fields can be found in the field reference.

    Manipulating DateTimes

    DateTime objects have value semantics, and cannot be modified after construction (they are immutable). Therefore, most simple manipulation of a datetime object involves construction of a new datetime as a modified copy of the original.

    WARNING: A common mistake to make with immutable classes is to forget to assign the result to a variable. Remember that calling an add or set method on an immtable object has no effect on that object - only the result is updated.

    Modifying fields

    One way to do this is to use methods on properties. To return to our prior example, if we wish to modify the dt object by changing its day-of-week field to Monday we can do so by using the setCopy method of the property:

        DateTime result = dt.dayOfWeek().setCopy(DateTimeConstants.MONDAY);

    Note: If the DateTime object is already set to Monday then the same object will be returned.

    To add to a date you could use the addToCopy method.

        DateTime result = dt.dayOfWeek().addToCopy(3);

    DateTime methods

    Another means of accomplishing similar calculations is to use methods on the DateTime object itself. Thus we could add 3 days to dt directly as follows:

        DateTime result = dt.plusDays(3);

    Using a MutableDateTime

    The methods outlined above are suitable for simple calculations involving one or two fields. In situations where multiple fields need to be modified, it is more efficient to create a mutable copy of the datetime, modify the copy and finally create a new value datetime.

        MutableDateTime mdt = dt.toMutableDateTime();
        // perform various calculations on mdt
        ...
        DateTime result = mdt.toDateTime();

    MutableDateTime has a number of methods, including standard setters, for directly modifying the datetime.

    Changing TimeZone

    DateTime comes with support for a couple of common timezone calculations. For instance, if you want to get the local time in London at this very moment, you would do the following

        // get current moment in default time zone
        DateTime dt = new DateTime();
        // translate to London local time
        DateTime dtLondon = dt.withZone(DateTimeZone.forID("Europe/London"));

    where DateTimeZone.forID("Europe/London") returns the timezone value for London. The resulting value dtLondon has the same absolute millisecond time, but a different set of field values.

    There is also support for the reverse operation, i.e. to get the datetime (absolute millisecond) corresponding to the moment when London has the same local time as exists in the default time zone now. This is done as follows

        // get current moment in default time zone
        DateTime dt = new DateTime();
        // find the moment when London will have / had the same time
        dtLondonSameTime = dt.withZoneRetainFields(DateTimeZone.forID("Europe/London"));

    A set of all TimeZone ID strings (such as "Europe/London") may be obtained by calling DateTimeZone.getAvailableIDs(). A full list of available time zones is provided here.

    Changing Chronology

    The DateTime class also has one method for changing calendars. This allows you to change the calendar for a given moment in time. Thus if you want to get the datetime for the current time, but in the Buddhist Calendar, you would do

        // get current moment in default time zone
        DateTime dt = new DateTime();
        dt.getYear();  // returns 2004
        // change to Buddhist chronology
        DateTime dtBuddhist = dt.withChronology(BuddhistChronology.getInstance());
        dtBuddhist.getYear();  // returns 2547

    where BuddhistChronology.getInstance is a factory method for obtaining a Buddhist chronology.

    Input and Output

    Reading date time information from external sources which have their own custom format is a frequent requirement for applications that have datetime computations. Writing to a custom format is also a common requirement.

    Many custom formats can be represented by date-format strings which specify a sequence of calendar fields along with the representation (numeric, name string, etc) and the field length. For example the pattern "yyyy" would represent a 4 digit year. Other formats are not so easily represented. For example, the pattern "yy" for a two digit year does not uniquely identify the century it belongs to. On output, this will not cause problems, but there is a problem of interpretation on input.

    In addition, there are several date/time serialization standards in common use today, in particular the ISO8601. These must also be supported by most datetime applications.

    Joda-Time supports these different requirements through a flexible architecture. We will now describe the various elements of this architecture.

    Formatters

    All printing and parsing is performed using a DateTimeFormatter object. Given such an object fmt, parsing is performed as follows

        String strInputDateTime;
        // string is populated with a date time string in some fashion
        ...
        DateTime dt = fmt.parseDateTime(strInputDateTime);

    Thus a DateTime object is returned from the parse method of the formatter. Similarly, output is performed as

        String strOutputDateTime = fmt.print(dt);

    Standard Formatters

    Support for standard formats based on ISO8601 is provided by the ISODateTimeFormat class. This provides a number of factory methods.

    For example, if you wanted to use the ISO standard format for datetime, which is yyyy-MM-dd'T'HH:mm:ss.SSSZZ, you would initialize fmt as

        DateTimeFormatter fmt = ISODateTimeFormat.dateTime();

    You would then use fmt as described above, to read or write datetime objects in this format.

    Custom Formatters

    If you need a custom formatter which can be described in terms of a format pattern, you can use the factory method provided by the DateTimeFormat class. Thus to get a formatter for a 4 digit year, 2 digit month and 2 digit day of month, i.e. a format of yyyyMMdd you would do

        DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");

    The pattern string is compatible with JDK date patterns.

    You may need to print or parse in a particular Locale. This is achieved by calling the withLocale method on a formatter, which returns another formatter based on the original.

        DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");
        DateTimeFormatter frenchFmt = fmt.withLocale(Locale.FRENCH);
        DateTimeFormatter germanFmt = fmt.withLocale(Locale.GERMAN);

    Formatters are immutable, so the original is not altered by the withLocale method.

    Freaky Formatters

    Finally, if you have a format that is not easily represented by a pattern string, Joda-Time architecture exposes a builder class that can be used to build a custom formatter which is programatically defined. Thus if you wanted a formatter to print and parse dates of the form "22-Jan-65", you could do the following:

        DateTimeFormatter fmt = new DateTimeFormatterBuilder()
                .appendDayOfMonth(2)
                .appendLiteral('-')
                .appendMonthOfYearShortText()
                .appendLiteral('-')
                .appendTwoDigitYear(1956)  // pivot = 1956
                .toFormatter();

    Each append method appends a new field to be parsed/printed to the calling builder and returns a new builder. The final toFormatter method creates the actual formatter that will be used to print/parse.

    What is particularly interesting about this format is the two digit year. Since the interpretation of a two digit year is ambiguous, the appendTwoDigitYear takes an extra parameter that defines the 100 year range of the two digits, by specifying the mid point of the range. In this example the range will be (1956 - 50) = 1906, to (1956 + 49) = 2005. Thus 04 will be 2004 but 07 will be 1907. This kind of conversion is not possible with ordinary format strings, highlighting the power of the Joda-Time formatting architecture.

    Direct access

    To simplify the access to the formatter architecture, methods have been provided on the datetime classes such as DateTime.

        DateTime dt = new DateTime();
        String a = dt.toString();
        String b = dt.toString("dd:MM:yy");
        String c = dt.toString("EEE", Locale.FRENCH);
        DateTimeFormatter fmt = ...;
        String d = dt.toString(fmt);

    Each of the four results demonstrates a different way to use the formatters. Result a is the standard ISO8601 string for the DateTime. Result b will output using the pattern 'dd:MM:yy' (note that patterns are cached internally). Result c will output using the pattern 'EEE' in French. Result d will output using the specified formatter, and is thus the same asfmt.print(dt).

    Advanced features

    Change the Current Time

    Joda-Time allows you to change the current time. All methods that get the current time are indirected via DateTimeUtils. This allows the current time to be changed, which can be very useful for testing.

        // always return the same time when querying current time
        DateTimeUtils.setCurrentMillisFixed(millis);
        // offset the real time
        DateTimeUtils.setCurrentMillisOffset(millis);

    Note that changing the current time this way does not affect the system clock.

    Converters

    The constructors on each major concrete class in the API take an Object as a parameter. This is passed to the converter subsystem which is responsible for converting the object to one acceptable to Joda-Time. For example, the converters can convert a JDK Date object to a DateTime. If required, you can add your own converters to those supplied in Joda-Time.

    Security

    Joda-Time includes hooks into the standard JDK security scheme for sensitive changes. These include changing the time zone handler, changing the current time and changing the converters. See JodaTimePermission for details.

    来自 <http://www.joda.org/joda-time/userguide.html>

    已使用 Microsoft OneNote 2016 创建。

  • 相关阅读:
    自动化测试之web自动化测试
    unittest框架中读取有特殊符号的配置文件内容的方法-configparser的RawConfigParser类应用
    No matching distribution found for selenium
    python之selenium多窗口切换
    python之selenium玩转鼠标操作(ActionChains)
    python之selenium三种等待方法
    python之selenium元素定位方法
    hadoop零基础系列之一:虚拟机下的Linux集群构建
    MapReduce分布式缓存程序,无法在Windows下的Eclipse中执行问题解决
    协程详解(三)
  • 原文地址:https://www.cnblogs.com/thankyouGod/p/5996945.html
Copyright © 2020-2023  润新知