|
Language/jQuery 2014. 11. 17. 17:58
The JavaScriptBelow is the JavaScript that is used in the demo this plugin simply extends the jQuery framework, allowing you to activate a message box by calling the function ‘noticeAdd()’. One interesting feature of this plugin is that it allows you to append a CSS class to the popup notice which can then be styled. For example with the error message I’m appending the .error class and in the CSS i’m just adding a background color. $(document).ready( function () |
text: 'This is a simple notification using the jQuery notice plugin. Click the X above to remove this notice.' , |
$( '.add' ).click( function () |
text: 'This is a notification that you have to remove' , |
$( '.add2' ).click( function () |
text: 'This is a notification that will remove itself' , |
$( '.add3' ).click( function () |
text: 'This is an error notification!' , |
$( '.add4' ).click( function () |
text: 'This is a success notification!' , |
$( '.remove' ).click( function () |
jQuery.noticeRemove($( '.notice-item-wrapper' ), 400); |
The HTML < li class = "add" >Click here to see a notification that you have to remove</ li > |
< li class = "add2" >Click here to see a notification that does not stay</ li > |
< li class = "add3" >Error Notification</ li > |
< li class = "add4" >Success Notification</ li > |
< li class = "remove" >Remove all active notifications</ li > |
출처 - http://papermashup.com/jquery-growl-notification-plugin/
Language/jQuery 2014. 11. 17. 16:29
I'm trying to over ride the default error message label with a div instead of a label. I have looked at this post as well and get how to do it but my limitations with CSS are haunting me. How can I display this like some of these examples: Example #1 (Dojo) - Must type invalid input to see error display Example #2 Here is some example code that overrides the error label to a div element $(document).ready(function(){
$("#myForm").validate({
rules: {
"elem.1": {
required: true,
digits: true
},
"elem.2": {
required: true
}
},
errorElement: "div"
});
});
Now I'm at a loss on the css part but here it is: div.error {
position:absolute;
margin-top:-21px;
margin-left:150px;
border:2px solid #C0C097;
background-color:#fff;
color:white;
padding:3px;
text-align:left;
z-index:1;
color:#333333;
font:100% arial,helvetica,clean,sans-serif;
font-size:15px;
font-weight:bold;
}
UPDATE: Okay I'm using this code now but the image and the placement on the popup is larger than the border, can this be adjusted to be dynamic is height? if (element.attr('type') == 'radio' || element.attr('type') == 'checkbox') {
element = element.parent();
offset = element.offset();
error.insertBefore(element)
error.addClass('message'); // add a class to the wrapper
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth());
error.css('top', offset.top - (element.height() / 2)); // Not working for Radio, displays towards the bottom of the element. also need to test with checkbox
} else {
// Error placement for single elements
offset = element.offset();
error.insertBefore(element)
error.addClass('message'); // add a class to the wrapper
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth());
error.css('top', offset.top - (element.height() / 2));
}
the css is the same as below (your css code) Html <span>
<input type="radio" class="checkbox" value="P" id="radio_P" name="radio_group_name"/>
<label for="radio_P">P</label>
<input type="radio" class="checkbox" value="S" id="radio_S" name="radio_group_name"/>
<label for="radio_S">S</label>
</span>
출처 - http://stackoverflow.com/questions/860055/jquery-override-default-validation-error-message-display-css-popup-tooltip-lik
Language/jQuery 2014. 11. 17. 16:27
JQuery Validate 활용시 참고할 소스특정 조건에 따라 validation 유무 결정을 하고 싶은 경우(You could use depends on rule to apply a conditional validation)rules: {
someField: {
required: true,
email: {
depends: function(element) {
return $("#contactform_email:checked");
}
}
}
}
에러 메시지를 다양한 형태로 변형하고자 하는 경우(showErrors)$('#someForm').validate({
showErrors: function(errorMap, errorList) {
if (errorList && errorList[0]) {
alert(errorList[0].message);
}
},
rules: {
}
[...]
}
에러 메시지를 출력할 위치를 변경하고자 하는 경우(errorPlacement)$('#someForm').validate({
errorElement: "span",
errorPlacement: function(error, element) {
error.insertAfter(element);
error.css("margin", "0 0 0 5px");
}
});
- errorElement를 활용해 에러 메시지의 태그를 변경하는 것이 가능하며, 위치는 errorPlacement 속성을 활용해 변경 가능하다.
JQuery Validate- JQuery Validation 프레임워크를 사용할 때 에러 메시지 출력 위치와 CSS를 변경하고자 할 경우
출처 - http://www.javajigi.net/display/WEB20/JQuery+Validation(Validate)+Plugin
Language/jQuery 2014. 11. 17. 15:32
http://www.jqueryscript.net/tags.php?/Notification/
Language/jQuery 2014. 11. 17. 15:08
Colorbox - a jQuery lightboxA lightweight customizable lightbox plugin for jQuery
view demo 1 2 3 4 5 Released under the MIT License. Source on Github (changelog). Compatible with: jQuery 1.3.2+ in Firefox, Safari, Chrome, Opera, Internet Explorer 7+ Bower Package: jquery-colorbox - Supports photos, grouping, slideshow, ajax, inline, and iframed content.
- Lightweight: 10KB of JavaScript (less than 5KBs gzipped).
- Appearance is controlled through CSS so it can be restyled.
- Can be extended with callbacks & event-hooks without altering the source files.
- Completely unobtrusive, options are set in the JS and require no changes to existing HTML.
- Preloads upcoming images in a photo group.
- Currently used on more than 1.9 million websites.
Instructions & HelpThe FAQ has instructions on asking for help, solutions to common problems, and how-to examples. First-time jQuery users can check out the Colorbox Beginner's Guide. Intermediate users can probably glean everything needed by view-source'ing the demo pages. UsageColorbox accepts settings from an object of key/value pairs, and can be assigned to any HTML element.
$(selector).colorbox({key:value, key:value, key:value});
$('a.gallery').colorbox({rel:'gal'});
$('a#login').colorbox();
$.colorbox({href:"thankyou.html"});
$.colorbox({html:"<h1>Welcome</h1>"});
$("a.gallery").colorbox({rel: 'gal', title: function(){
var url = $(this).attr('href');
return '<a href="' + url + '" target="_blank">Open In New Window</a>';
}});
SettingsProperty | Default | Description |
---|
transition | "elastic" | The transition type. Can be set to "elastic", "fade", or "none". | speed | 350 | Sets the speed of the fade and elastic transitions, in milliseconds. | href | false | This can be used as an alternative anchor URL or to associate a URL for non-anchor elements such as images or form buttons. $("h1").colorbox({href:"welcome.html"}); | title | false | This can be used as an anchor title alternative for Colorbox. | rel | false | This can be used as an anchor rel alternative for Colorbox. This allows the user to group any combination of elements together for a gallery, or to override an existing rel so elements are not grouped together. $("a.gallery").colorbox({rel:"group1"}); Note: The value can also be set to 'nofollow' to disable grouping. | scalePhotos | true | If true, and if maxWidth, maxHeight, innerWidth, innerHeight, width, or height have been defined, Colorbox will scale photos to fit within the those values. | scrolling | true | If false, Colorbox will hide scrollbars for overflowing content. This could be used on conjunction with the resize method (see below) for a smoother transition if you are appending content to an already open instance of Colorbox. | opacity | 0.85 | The overlay opacity level. Range: 0 to 1. | open | false | If true, Colorbox will immediately open. | returnFocus | true | If true, focus will be returned when Colorbox exits to the element it was launched from. | trapFocus | true | If true, keyboard focus will be limited to Colorbox's navigation and content. | fastIframe | true | If false, the loading graphic removal and onComplete event will be delayed until iframe's content has completely loaded. | preloading | true | Allows for preloading of 'Next' and 'Previous' content in a group, after the current content has finished loading. Set to false to disable. | overlayClose | true | If false, disables closing Colorbox by clicking on the background overlay. | escKey | true | If false, will disable closing colorbox on 'esc' key press. | arrowKey | true | If false, will disable the left and right arrow keys from navigating between the items in a group. | loop | true | If false, will disable the ability to loop back to the beginning of the group when on the last element. | data | false | For submitting GET or POST values through an ajax request. The data property will act exactly like jQuery's .load() data argument, as Colorbox uses .load() for ajax handling. | className | false | Adds a given class to colorbox and the overlay. | fadeOut | 300 | Sets the fadeOut speed, in milliseconds, when closing Colorbox. | closeButton | true | Set to false to remove the close button. | Internationalization | | |
---|
current | "image {current} of {total}" | Text or HTML for the group counter while viewing a group. {current} and {total} are detected and replaced with actual numbers while Colorbox runs. | previous | "previous" | Text or HTML for the previous button while viewing a group. | next | "next" | Text or HTML for the next button while viewing a group. | close | "close" | Text or HTML for the close button. The 'esc' key will also close Colorbox. | xhrError | "This content failed to load." | Error message given when ajax content for a given URL cannot be loaded. | imgError | "This image failed to load." | Error message given when a link to an image fails to load. | Content Type | | |
---|
iframe | false | If true, specifies that content should be displayed in an iFrame. | inline | false | If true, content from the current document can be displayed by passing the href property a jQuery selector, or jQuery object. // Using a selector:
$("#inline").colorbox({inline:true, href:"#myForm"});
// Using a jQuery object:
var $form = $("#myForm");
$("#inline").colorbox({inline:true, href:$form});
| html | false | For displaying a string of HTML or text: $.colorbox({html:"<p>Hello</p>"}); | photo | false | If true, this setting forces Colorbox to display a link as a photo. Use this when automatic photo detection fails (such as using a url like 'photo.php' instead of 'photo.jpg') | ajax | | This property isn't actually used as Colorbox assumes all hrefs should be treated as either ajax or photos, unless one of the other content types were specified. | Dimensions | | |
---|
width | false | Set a fixed total width. This includes borders and buttons. Example: "100%", "500px", or 500 | height | false | Set a fixed total height. This includes borders and buttons. Example: "100%", "500px", or 500 | innerWidth | false | This is an alternative to 'width' used to set a fixed inner width. This excludes borders and buttons. Example: "50%", "500px", or 500 | innerHeight | false | This is an alternative to 'height' used to set a fixed inner height. This excludes borders and buttons. Example: "50%", "500px", or 500 | initialWidth | 300 | Set the initial width, prior to any content being loaded. | initialHeight | 100 | Set the initial height, prior to any content being loaded. | maxWidth | false | Set a maximum width for loaded content. Example: "100%", 500, "500px" | maxHeight | false | Set a maximum height for loaded content. Example: "100%", 500, "500px" | Slideshow | | |
---|
slideshow | false | If true, adds an automatic slideshow to a content group / gallery. | slideshowSpeed | 2500 | Sets the speed of the slideshow, in milliseconds. | slideshowAuto | true | If true, the slideshow will automatically start to play. | slideshowStart | "start slideshow" | Text for the slideshow start button. | slideshowStop | "stop slideshow" | Text for the slideshow stop button | Positioning | | |
---|
fixed | false | If true, Colorbox will be displayed in a fixed position within the visitor's viewport. This is unlike the default absolute positioning relative to the document. | top | false | Accepts a pixel or percent value (50, "50px", "10%"). Controls Colorbox's vertical positioning instead of using the default position of being centered in the viewport. | bottom | false | Accepts a pixel or percent value (50, "50px", "10%"). Controls Colorbox's vertical positioning instead of using the default position of being centered in the viewport. | left | false | Accepts a pixel or percent value (50, "50px", "10%"). Controls Colorbox's horizontal positioning instead of using the default position of being centered in the viewport. | right | false | Accepts a pixel or percent value (50, "50px", "10%"). Controls Colorbox's horizontal positioning instead of using the default position of being centered in the viewport. | reposition | true | Repositions Colorbox if the window's resize event is fired. | Retina Images | | |
---|
retinaImage | false | If true, Colorbox will scale down the current photo to match the screen's pixel ratio | retinaUrl | false | If true and the device has a high resolution display, Colorbox will replace the current photo's file extention with the retinaSuffix+extension | retinaSuffix | "@2x.$1" | If retinaUrl is true and the device has a high resolution display, the href value will have it's extention extended with this suffix. For example, the default value would change my-photo.jpg to my-photo@2x.jpg | Callbacks | | |
---|
onOpen | false | Callback that fires right before Colorbox begins to open. | onLoad | false | Callback that fires right before attempting to load the target content. | onComplete | false | Callback that fires right after loaded content is displayed. | onCleanup | false | Callback that fires at the start of the close process. | onClosed | false | Callback that fires once Colorbox is closed. |
Public Methods$.colorbox() | This method allows you to call Colorbox without having to assign it to an element. $.colorbox({href:"login.php"}); | $.colorbox.next() $.colorbox.prev() | These methods moves to the next and previous items in a group and are the same as pressing the 'next' or 'previous' buttons. | $.colorbox.close() | This method initiates the close sequence, which does not immediately complete. The lightbox will be completely closed only when the cbox_closed event / onClosed callback is fired. | $.colorbox.element() | This method is used to fetch the current HTML element that Colorbox is associated with. Returns a jQuery object containing the element. var $element = $.colorbox.element(); | $.colorbox.resize() | This allows Colorbox to be resized based on it's own auto-calculations, or to a specific size. This must be called manually after Colorbox's content has loaded. The optional parameters object can accept width or innerWidth and height orinnerHeight . Without specifying a width or height, Colorbox will attempt to recalculate the height of it's current content. | $.colorbox.remove() | Removes all traces of Colorbox from the document. Not the same as $.colorbox.close(), which tucks colorbox away for future use. |
Event HooksThese event hooks fire at the same time as their corresponding callbacks (ie. cbox_complete & onComplete), but can be used to make a universal change to Colorbox, while callbacks are only applied to selected elements. // Example of using an event listener and public method to build a primitive slideshow:
$(document).bind('cbox_complete', function(){
setTimeout($.colorbox.next, 1500);
});
cbox_open | triggers when Colorbox is first opened, but after a few key variable assignments take place. | cbox_load | triggers at the start of the phase where content type is determined and loaded. | cbox_complete | triggers when the transition has completed and the newly loaded content has been revealed. | cbox_cleanup | triggers as the close method begins. | cbox_closed | triggers as the close method ends. |
출처 - http://www.jacklmoore.com/colorbox/
Language/jQuery 2014. 11. 17. 15:05
"But doesn't jQuery make it easy to write your own validation plugin?" Sure, but there are still a lot of subtleties to take care of: You need a standard library of validation methods (such as emails, URLs, credit card numbers). You need to place error messages in the DOM and show and hide them when appropriate. You want to react to more than just a submit event, like keyup and blur. You may need different ways to specify validation rules according to the server-side enviroment you are using on different projects. And after all, you don't want to reinvent the wheel, do you? "But aren't there already a ton of validation plugins out there?" Right, there are a lot of non-jQuery-based solutions (which you'd avoid since you found jQuery) and some jQuery-based solutions. This particular one is one of the oldest jQuery plugins (started in July 2006) and has proved itself in projects all around the world. There is also anarticle discussing how this plugin fits the bill of the should-be validation solution. Not convinced? Have a look at this example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <form class="cmxform" id="commentForm" method="get" action="">
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required/>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required/>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url"/>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
<input class="submit" type="submit" value="Submit"/>
$("#commentForm").validate();
|
Isn't that nice and easy?A single line of jQuery to select the form and apply the validation plugin, plus a few annotations on each element to specify the validation rules. Of course that isn't the only way to specify rules. You also don't have to rely on those default messages, but they come in handy when starting to setup validation for a form. A few things to look out for when playing around with the demo- After trying to submit an invalid form, the first invalid element is focused, allowing the user to correct the field. If another invalid field – that wasn't the first one – was focused before submit, that field is focused instead, allowing the user to start at the bottom if he or she prefers.
- Before a field is marked as invalid, the validation is lazy: Before submitting the form for the first time, the user can tab through fields without getting annoying messages – they won't get bugged before having the chance to actually enter a correct value
- Once a field is marked invalid, it is eagerly validated: As soon as the user has entered the necessary value, the error message is removed
- If the user enters something in a non-marked field, and tabs/clicks away from it (blur the field), it is validated – obviously the user had the intention to enter something, but failed to enter the correct value
That behaviour can be irritating when clicking through demos of the validation plugin – it is designed for an unobtrusive user experience, annoying the user as little as possible with unnecessary error messages. So when you try out other demos, try to react like one of your users would, and see if the behaviour is better then. If not, please let me know about any ideas you may have for improvements! API DocumentationYou're probably looking for If not, read on. Throughout the documentation, two terms are used very often, so it's important that you know their meaning in the context of the validation plugin: - method: A validation method implements the logic to validate an element, like an email method that checks for the right format of a text input's value. A set of standard methods is available, and it is easy to write your own.
- rule: A validation rule associates an element with a validation method, like "validate input with name "primary-mail" with methods "required" and "email".
Plugin methodsThis library adds three jQuery plugin methods, the main entry point being the validate method: Custom selectorsThis library also extends jQuery with three custom selectors: ValidatorThe validate method returns a Validator object that has a few public methods that you can use to trigger validation programmatically or change the contents of the form. The validator object has more methods, but only those documented here are intended for usage. There are a few static methods on the validator object: List of built-in Validation methodsA set of standard validation methods is provided: Some more methods are provided as add-ons, and are currently included in additional-methods.js in the download package. Not all of them are documented here: The General Guidelines section provides detailed discussion of the design and ideas behind the plugin, explaining why certain things are as they are. It covers the features in more detail than the API documentation, which just briefly explains the various methods and options available. If you've decided to use the validation plugin in your application and want to get to know it better, it is recommended that you read the guidelines. Fields with complex names (brackets, dots)When you have a name attribute like user[name], make sure to put the name in quotes. More details in the General Guidelines. Too much recursionAnother common problem occurs with this code: 1 2 3 4 5 6 7 8 | submitHandler: function(form) {
|
This results in a too-much-recursion error: $(form).submit() triggers another round of validation, resulting in another call to submitHandler, and voila, recursion. Replace that with form.submit(), which triggers the native submit event instead and not the validation. So the correct code looks slightly different: 1 2 3 4 5 | submitHandler: function(form) {
|
DemosBased on an old version of the marketo.com sign-up form. The custom validation was once replaced with this plugin. Thanks to Glen Lipka for contributing it! Notable features of the demo: - Customized message display: No messages displayed for the required method, only for typing-errors (like wrong email format); A summary is displayed at the top ("You missed 12 fields. They have been highlighted below.")
- Remote validation of email field. Try to enter eg. glen@marketo.com
- Integration with masked-input plugin, see Zip and Phone fields and Credit Card Number on step 2
- A custom method for making the billing address on step 2 optional when "Same as Company Address" is checked
- A custom method for checking the password: Checks that the password contains at least one number and one character and that it is at least 6 characters long. If the user blurs the field with an invalid value, the input is emptied and gets focus again.
The sign-up form from rememberthemilk.com (based on an older version). The custom validation was replaced using this plugin. Thanks to RTM for contributing! Notable features of the demo: - Custom message display, based on the original table layout, using success option to display a checkmark for valid fields
- Remote validation of username, to check if it is already taken (try "Peter", "asdf" or "George")
Contributed by Michael Evangelista, showing a multipart form for buying and selling houses. Notable features of the demo: - Multipart, implemented using the jQuery UI accordion and a custom method to check if an element is on the current page when validated
- Integration with masked-input plugin, see Phone and Zip fields
Features remote validation for helping the user to fill out captchas, based on example atpsyrens.com. Notable features of the demo: - Remote validation to check if the user entered the correct captcha, without forcing him to submit the form first
출처 - http://jqueryvalidation.org/documentation/
Language/jQuery 2014. 11. 17. 15:04
With jQuery, it’s very easy to trigger mouse event handlers by calling functions such as click, mousedown and trigger. They even propagate events so that event handlers registered higher up the DOM tree through delegate() and on() would get called as well. So in most of the cases I could just use them instead of triggering real browser events when writing tests. However recently, I had to write a couple components that need to listen to mouse events such as control click, shift click and mouse drag. Looking at the jQuery API, I couldn’t find any built in functions that could trigger mouse events but at the same time specify extra properties such as control or shift click. Googling a bit on firing real browser events and thanks to the great documentation on MDN, first an event needs to becreated, then initialized and lastly dispatched. The initMouseEvent sure makes me dizzy by looking at it. On top of that, older IE browsers has a different API for doing the same thing. This got me thinking there gotta be a better way. What I wanted to do was just something other JavaScript UI projects must have had done. Then I took a look at the tests injQuery UI project and sure enough, I found the jquery.simulate.js to simulate real browser events and it already handles the cross browser event creation. Now let’s see how it helps me create those events that I want. jquery.simulate.js is just another jQuery plugin and its API is fairly simple. The first parameter of the plugin is the name of the event. Here you can use the names of the browser mouse events such as click, mousemove, mouseout, etc. For example, if we want to trigger a mouse click on elements with class name “target”. We can simply call this. 1 | $( '.target' ).simulate( 'click' );
|
The plugin can also take a second argument to override the default event properties. These default properties include pretty much the same arguments required to call the browser native event initialization method, event.initEvent. Two of these properties are ctrlKey and shiftKey. With them, I can now easily test my event handlers for control click and shift click. 1 2 | $( '.target' ).simulate( 'click' , { ctrlKey: true });
$( '.target' ).simulate( 'click' , { shiftKey: true });
|
To test mouse dragging, although “drag” is not a real browser event, the plugin comes with support to handle the case when the event name specified is “drag”. We just need to specify the name as drag and the change in x and y of the mouse position. Internally, the plugin will perform a series of events including mousedown, mousemove, mouseup and click to simulate mouse drag. 1 | $( '.target' ).simulate( 'drag' , { dx: 200, dy: 100 });
|
Here is a sample page that shows how the plugin works. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <! doctype html>
< html >
< head >
< title ></ title >
< script type = "text/javascript" >
$(function() {
$('.target').click(function(e) {
if (e.ctrlKey) {
console.log('control click');
} else if (e.shiftKey) {
console.log('shift click');
} else {
console.log('regular click');
}
}).mousedown(function(e) {console.log('mousedown', e);})
.mouseup(function(e) { console.log('mouseup', e); });
$('button').click(function() {
if($(this).hasClass('drag')) {
$('.target').simulate('drag', {dx: 100, dy: 50});
} else if($(this).hasClass('ctrl')) {
$('.target').simulate('click', {ctrlKey: true});
} else if($(this).hasClass('shift')) {
$('.target').simulate('click', {shiftKey: true});
} else {
$('.target').simulate('click');
}
});
});
</ script >
</ head >
< body >
< div class = "target" style = "background-color: yellow; height: 300px; width: 500px" >Test Target</ div >
< div >
< button class = "ctrl" >Ctrl Click</ button >
< button class = "shift" >Shift Click</ button >
< button class = "regular" >Regular Click</ button >
< button class = "drag" >Drag</ button >
</ div >
</ body >
</ html >
|
There are other options that are supported in the plugin. For complete list of options, please refer to the plugin on GitHub. Have fun coding!
출처 - http://wingkaiwan.com/2012/09/23/triggering-mouse-events-with-jquery-simulate-when-testing-in-javascript/
Language/jQuery 2014. 11. 17. 15:03
https://code.google.com/p/jqueryjs/
Language/JSP 2014. 11. 14. 17:41
설정web.xml <taglib> <taglib-uri>jstl-c</taglib-uri> <taglib-location>/WEB-INF/tlds/jstl/c.tld</taglib-location> </taglib> <taglib> <taglib-uri>jstl-fmt</taglib-uri> <taglib-location>/WEB-INF/tlds/jstl/fmt.tld</taglib-location> </taglib> <taglib> <taglib-uri>jstl-fn</taglib-uri> <taglib-location>/WEB-INF/tlds/jstl/fn.tld</taglib-location> </taglib>
jsp 에서 <%@ taglib uri="jstl-c" prefix="c" %> <%@ taglib uri="jstl-fmt" prefix="fmt" %> <%@ taglib uri="jstl-fn" prefix="fn" %> EL#
생존범위 속성 맵 - pageScope
- requestScope
- sessionScope
- applicationScope
요청 파라미터 맵 - param
- paramValues
요청 헤더 맵 - header
- headerValues
쿠키 맵 - cookie
컨텍스트 초기화 파라미터 맵(서블릿 초기화 파라미터 아님) - initParam
실제 pageContext 객체에 대한 참조. 이것은 빈임 pageContext pageContext 접근자 - getErrorData()
- getPage()
- getRequest()
- getResponse()
- getServletConfig)()
- getServletContext()
- getSession()
JspContext로 부터 상속받은 접근자 - getAttribute()
- getAttributeNamesInScope()
- getAttributesScope()
- getExpression!Eval!uator()
- getOut()
- getVariableResolver()
스크립팅 - <$= request.getHeader("host") %>
EL 내장 객체 - ${header["host"]}
- ${header.host}
- ${headerValues.host[]}
스크립팅 - <%= request.getMethod() %>
EL 내장 객체 - ${pageContext.request.method}
core <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 일반적인 것 - <c:out>
- <c:set>
- <c:remove>
- <c:catch>
조건 - <c:if>
- <c:choose>
- <c:when>
- <c:otherwise>
URL 관련 - <c:import!>
- <c:url>
- <c:redirect>
- <c:param>
반복 - <c:forEach>
- <c:forEachToken>
① set - JSP의 setAttribute()와 같은 역활 - 기본형 <c:set var="변수명" value="변수명에 할당된 값" target="자바빈 객체명이나 Map 객체명" property="자바빈 객체나 Map 객체의 값을 설정할 프로퍼티 명" scope="변수의 공유 범위(유효기간)으로 page|request|session|application" /> - 예제 <c:set var="country" value="${'Korea'}" /> <c:set var="intArray" value="<%=new int[] {1,2,3,4,5}%>" /> <c:set var="sum" value="${sum+i}" /> ② out
- JSP의 표현식을 대체하는 것으로 많이 사용됨 - 기본형 <c:out var="변수명" default="기본값" escapeXML="true|false" /> * escapeXML > 생략시 기본값은 true > true일 경우 값 중에 포함된 <>&'" 문자들을 각각 <, >, &, ', "로 출력
- 예제 <c:out value="${sum}" /> <c:out value="${val}" /> ③ remove
- JSP의 removeAttribute()와 같은 역활 - 기본형 <c:remove var="변수명" scope="변수의 공유 범위로 page(생략 시 기본)|request|session|application" /> - 예제 <c:remove var="browser" /> ④ catch
- body 위치에서 실행되는 코드의 예외를 잡아내는 역할 - 기본형 <c:catch var="에러가 발생할 때 에러 메세지가 포함될 변수명" /> - 예제 <c:catch var="errmsg"> line 1~ <%=1/0%> line 2~ </c:catch> <c:out value="${errmsg}" /> ⑤ if
- 조건문에 사용 - 기본형 <c:if test="조건 판별식" var="변수명" scope="변수의 공유범위 page|request|session|application" - 예제 <c:if test="${country != null}"> 국가명 : <c:out value="${country}" /> </c:if> ⑥ choose
- 자바의 switch문과 동일 - 조건에서 문자열 비교가 가능 - 하나 이상의 <when>과 하나의 <otherwise> 서브 태그를 가짐 ⑦ when
- choose 태그의 서브태그 - choose 태그내에서 여러번 사용될 수 있다. - 기본형 <c:when test="조건 판별식" /> ⑧ otherwise
- choose 태그의 서브태그 - choose 태그내에서 한번만 사용될 수 있다. - 예제 : <c:choose> <c:when test="${country == 'Korea'}"> 나라 : <c:out value="${country}" /> </c:when> <c:when test="${country == 'Canada'}"> 나라 : <c:out value="${country}" /> </c:when> <c:otherwise> 선택된 나라가 없습니다. </c:otherwise> </c:choose> ⑨ forEach
- 객체 전체에 걸쳐 반복 실행할 때 사용 - 기본형 <c:forEach items="반복할 객체명" begin="시작값" end="종료값" step="증가값" var="변수명" varStatus="별도의 변수" />
⑩ forTokens
- 문자열을 주어진 구분자(delimiter)로 분할 - 기본형 <c:forTokens items="반복할 객체명" delims="구분자" begin="반복할 시작값" end="반목 마지막값" step="증가값" var="변수명" varStatus="별도의 변수" - 예제 <c:forTokens var="color" items="빨강색,주황색.노란색.초록색,파랑색,남색.보라색" delims=",."> color : <c:out value="${color}" /><br> </c:forTokens> ⑪ import!
- 웹 어플리케이션 내부의 자원 및 http, ftp와 같은 외부에 있는 자원에 대해 접근 - 기본형 <c:import! url="읽어올 URL" var="읽어올 데이터를 저장할 변수명" scope="변수의 공유 범위" varReader="리소스의 내용을 Reader 객체로 읽어올 때 사용" charEncoding="읽어온 데이터의 캐릭터셋 지정" /> ⑫ redirect
- response.sendRedirect()를 대체하는 태그로 지정한 다른 페이지로 이동 - 기본형 <c:redirect url="이동할 URL" /> ⑬ url
- 쿼리 파라미터로 부터 URL 생성 - 기본형 <c:url var="생성한 URL이 저장될 변수명" value="생성할 URL" scope="변수의 공유 범위" /> ⑭ param
- 기본형 <c:param name="파라미터 명" value="파라미터 값" /> <c:url var="registrationURL" value="/customers/register"> <c:param name="name" value="${param.name}" /> <c:param name="country" value="${param.country}" /> </c:url>
<c:set var="temp" value="Hello! World" /> <c:out value="${ temp }" default="value is null"/><br> <c:out value="${ temp }" default="value is null" escapeXml="false" /><br> <c:out value="${ temp2 }" default="value is null" /><br> <c:remove var="timezone" scope="session"/> <c:set var="timezone" scope="session">CST</c:set> <c:out value="${cookie['tzPref'].value}" default=="CST"/> function${fn:substring(name, 1, 10)}
fn:contains(string, substring) string이 substring을 포함하면 true 리턴.
fn:containsIgnoreCase(string,substring) 대소문자에 관계없이, string이 substring을 포함하면 true 리턴.
fn:endsWith(string, suffix) string이 suffix로 끝나면 true 리턴.
fn:escapeXml(string) string에 XML과 HTML에서 특별한 의미를 가진 문자들이 있으면, XML 엔티티 코드로 바꿔준 뒤 문자열 리턴.
fn:indexOf(string,substring) string에서 substring이 처음으로 나타나는 인덱스 리턴.
fn:join(array, separator) array(배열) 요소들을 separator를 구분자로 하여 연결해서 리턴
fn:length(item) item 이 배열이나 컬렉션이면 요소의 갯수를, 문자열이면 문자의 갯수를 리턴.
fn:replace(string, before, after) string 내에 있는 before 문자열을 after 문자열로 모두 바꿔서 리턴.
fn:split(string, separator) string 내의 문자열을 separator에 따라 나누어서 배열로 구성해 리턴.
fn:startsWith(string, prefix) string이 prefix로 시작하면 true 리턴.
fn:substring(string, begin, end) tring에서 begin 인덱스에서 시작해서 end 인덱스에 끝나는 부분 (end 인덱스에 있는문자 포함)의 문자열을 리턴.
fn:substringAfter(string, substring) string에서 substring이 나타나는 이후의 부분에 있는 문자열을 리턴.
fn:substringBefore(string, substring) string에서 substring이 나타나기 이전의 부분에 있는 문자열을 리턴.
fn:toLowerCase(string) string을 모두 소문자로 바꿔 리턴.
fn:toUpperCase(string) string을 모두 대문자로 바꿔 리턴.
fn:trim(string) string 앞뒤의 공백(whitespace)을 모두 제거하여 리턴. fmt
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 국제화 - <fmt:message>
- <fmt:setLocale>
- <fmt:setTimeZone>
- <fmt:bundle>
- <fmt:setBundle>
- <fmt:param>
- <fmt:requestEncoding>
포맷팅 - <fmt:timeZone>
- <fmt:setTimeZone>
- <fmt:formatNumber>
- <fmt:formatDate>
- <fmt:parseNumber>
- <fmt:parseData>
- <fmt:parseNumber>
jstl fmt로 날짜보여줄때, pattern attribute에 의한 날짜 표현 방식들 pattern="yyyy-MM-dd aa h:mm:ss" 2007-12-13 오전 9:36:48
pattern="yyyy-MM-dd aa hh:mm:ss" 2007-12-13 오전 09:36:48
pattern="yyyy-MM-dd H:mm:ss" 2007-12-13 9:36:48
pattern="yyyy-MM-dd HH:mm:ss" 2007-12-13 09:36:48
<fmt:setLocale value="fr_CA" scope="session"/> <fmt:setTimeZone value="Australia/Brisbane" scope="session"/> <fmt:formatDate value="${blogEntry.created}" dateStyle="full"/> <c:out value="${blogEntry.title}" escapeXml="false"/> <fmt:formatDate value="${blogEntry.created}" pattern="h:mm a zz"/> <fmt:formatNumber value="0.02" type="currency" currencySymbol="원"/> <fmt:formatNumber value="9876543.61" type="number"/> [type="{number|currency|percent}"] <fmt:parseDate value="${usDateString}" parseLocale="en_US" type="both" dateStyle="short" timeStyle="short" var="usDate"/>
sql데이터베이스 접근 - <sql:query>
- <sql:update>
- <sql:setDataSource>
- <sql:param>
- <sql:dataParam>
xml
출처 - http://tazz009.tistory.com/484
Language/JSP 2014. 11. 14. 17:39
Function, 함수 기능 : 컬렉션 처리, String 처리 접두어(Prefix) : fn directive : <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
JSTL functions은 JSTL에서 제공하는 각종 함수를 사용해서 문자열이나, 컬렉션들을 처리한다. fn태그는 단독으로 사용할 수 없고 EL 표현식 내에서 사용한다.
● boolean contains(String sting, String substring) : string이 substring을 포함하면 true값을 리턴 한다. ● boolean containsIgnoreCase(String string, String substring) : 대소문자에 관계없이, string이 substring을 포함하면 true 리턴 ${fn:contains("helloworld", "world")} // true ${fn:containsIgnoreCase("hello world!", "WoRLd")} // true ● boolean startsWith(String string, String prefix) : string이 prefix로 시작하면 true값을 리턴 한다. ● boolean endsWith(String string, String substring) : string이 suffix로 끝나면 true값을 리턴 한다. ${fn:startsWith("hello world!", "ld!")} // false ${fn:endsWith("hello world!", "ld!")} // true
● String escapeXml(String string) : string에서 XML, HTML의 < >& ' " 문자들을 각각 < > & ' "로 바꿔준 뒤 문자열을 리턴 한다. <c:out value="${fn:escapeXml('<>')}"/> // <>
● int indexOf( java.lang.String string, java.lang.String substring) : string에서 substring이 처음으로 나타나는 인덱스를 리턴 한다. ${fn:indexOf("abcdefg", "f")} // 5
● String[] split(String string, String separator) : string 내의 문자열을 separator에 따라 잘라내서 잘려진 문자열들을 배열로 리턴한다. ● String join(String[], String separator) : 배열 요소들을 separator를 구분자로 하여 모두 연결해서 리턴 한다. <c:set var="texts" value="${fn:split('Hi My name is waldo', ' ')}"/> <c:out value="${fn:join(texts, '-')}"/> // Hi-My-name-is-waldo
// jstl이나 el에 문자열 리터럴로 배열을 직접 생성하는 예제는 검색결과가 없다. 대부분 fn:split이나 jsp:useBean을 사용했다.
● int length(Object item) : item이 배열이나 컬렉션이면 요소의 개수를, 문자열이면 문자의 개수를 리턴 한다. <c:set var="texts" value="${fn:split('Hi My name is waldo', ' ')}"/> ${fn:length(texts)} // 5 ${fn:length("123456")} // 6
● String replace(String string, String before, String after) : string 내에 있는 before 문자열을 after 문자열로 모두 바꿔서 리턴 한다. ${fn:replace("hi hello", "hello", "hi")} // hi hi
// replace 함수는 HTML에서 공백과 줄바꿈을 표현할 때 사용할 수 있다. ${fn:replace("hell o o ~", " ", " ")} // hell o o ~
<% pageContext.setAttribute("enter","\n"); %> ${fn:replace(info.text, enter, '<br/>') // 엔터처리
<% pageContext.setAttribute("enter","\n"); %> ${fn:replace(fn:replace(fn:escapeXml(info.content_txt), enter, '<br/>') , ' ', ' ')} // 엔터와 공백 처리
● String substring(String string, int begin, int end) : string에서 begin 인덱스에서 시작해서 end 인덱스에 끝나는 부분의 문자열을 리턴. ● String substringAfter(String string, String substring) : string에서 substring이 나타나는 이후의 부분에 있는 문자열을 리턴 한다. ● String substringBefore(String string, String substring) : string에서 substring이 나타나기 이전의 부분에 있는 문자열을 리턴 한다. ${fn:substring(text, 3, 19)} // My name is waldo ${fn:substringAfter(text, "Hi ")} // My name is waldo ${fn:substringBefore(text, "waldo")} // Hi My name is
● String toLowerCase(String string) : string을 모두 소문자로 바꿔 리턴한다. ● String toUpperCase(String string) : string을 모두 대문자로 바꿔 리턴한다. <c:set var="text" value="Hi My name is waldo"/> ${fn:toLowerCase(text)} // hi my name is waldo ${fn:toUpperCase(text)} // HI MY NAME IS WALDO
● String trim(String string) : string 앞뒤의 공백을 모두 제거하여 리턴 한다. <c:set var="text" value=" blank spcae "/> ${fn:length(text)} // 31 <c:set var="text" value="${fn:trim(text)}"/> ${fn:length(text)} // 11
출처 - http://noritersand.tistory.com/260
|