Monday, February 28, 2011

JQuery-DOM

Hey ...
In my previous post we worked on JQuery-Core. Here I am going to explain JQuery-DOM. After this post you can write your jquery script easily. So please pay attention as much as possible.

2. DOM
2.1 Attributes

2.1.1 attr(String)
attr(String name) returns Object

Access a property on the first matched element. This method makes it easy to retrieve a
property value from the first matched element.


Example:

Returns the src attribute from the first image in the document.

$("img").attr("src");

HTML:
<img src="test.jpg"/>

Result:

test.jpg

2.1.2 attr(Map)
attr(Map properties) returns jQuery
Set a key/value object as properties to all matched elements.
This serves as the best way to set a large number of properties on all matched elements.

Example:
Sets src and alt attributes to all images.
$("img").attr({ src: "test.jpg", alt: "Test Image" });
HTML:
<img/>
Result:
<img src="test.jpg" alt="Test Image"/>

2.1.3 attr(String,Object)
attr(String key, Object value) returns jQuery
Set a single property to a value, on all matched elements.
Can compute values provided as ${formula}, see second example.
Note that you can't set the name property of input elements in IE. Use $(html) or
.append(html) or .html(html) to create elements on the fly including the name property.

Example:
Sets src attribute to all images.
$("img").attr("src","test.jpg");
HTML:
<img/>
Result:
<img src="test.jpg"/>
Example:
Sets title attribute from src attribute, a shortcut for attr(String,Function)
$("img").attr("title", "${this.src}");
HTML:
<img src="test.jpg" />
Result:
<img src="test.jpg" title="test.jpg" />

2.1.4 attr(String,Function)
attr(String key, Function value) returns jQuery
Set a single property to a computed value, on all matched elements.
Instead of a value, a function is provided, that computes the value.

Example:
Sets title attribute from src attribute.
$("img").attr("title", function() { return this.src });
HTML:
<img src="test.jpg" />
Result:
<img src="test.jpg" title="test.jpg" />

Example:
Enumerate title attribute.
$("img").attr("title", function(index) { return this.title + (i + 1); });
HTML:
<img title="pic" /><img title="pic" /><img title="pic" />
Result:
<img title="pic1" /><img title="pic2" /><img title="pic3" />

2.1.5 text()
text() returns String
Get the text contents of all matched elements. The result is a string that contains the
combined text contents of all matched elements. This method works on both HTML and XML
documents.

Example:
Gets the concatenated text of all paragraphs
$("p").text();
HTML:
<p><b>Test</b> Paragraph.</p><p>Paraparagraph</p>
Result:
Test Paragraph.Paraparagraph

2.1.6 text(String)
text(String val) returns String
Set the text contents of all matched elements.
Similar to html(), but escapes HTML (replace "<" and ">" with their HTML entities).

Example:
Sets the text of all paragraphs.
$("p").text("<b>Some</b> new text.");
HTML:
<p>Test Paragraph.</p>
Result:
<p>&lt;b&gt;Some&lt;/b&gt; new text.</p>

Example:
Sets the text of all paragraphs.
$("p").text("<b>Some</b> new text.", true);
HTML:
<p>Test Paragraph.</p>
Result:
<p>Some new text.</p>

2.1.7 val()
val() returns String
Get the current value of the first matched element.

Example:
$("input").val();
HTML:
<input type="text" value="some text"/>
Result:
"some text"

2.1.8 val(String)
val(String val) returns jQuery
Set the value of every matched element.

Example:
$("input").val("test");
HTML:
<input type="text" value="some text"/>
Result:
<input type="text" value="test"/>

2.1.9 html()
html() returns String
Get the html contents of the first matched element. This property is not available on XML
documents.

Example:
$("div").html();
HTML:
<div><input/></div>
Result:
<input/>

2.1.10 html(String)
html(String val) returns jQuery
Set the html contents of every matched element. This property is not available on XML
documents.

Example:
$("div").html("<b>new stuff</b>");
HTML:
<div><input/></div>
Result:
<div><b>new stuff</b></div>

2.1.11 removeAttr(String)
removeAttr(String name) returns jQuery
Remove an attribute from each of the matched elements.

Example:
$("input").removeAttr("disabled")
HTML:
<input disabled="disabled"/>
Result:
<input/>

2.1.12 addClass(String)
addClass(String class) returns jQuery
Adds the specified class(es) to each of the set of matched elements.

Example:
$("p").addClass("selected")
HTML:
<p>Hello</p>
Result:
[ <p class="selected">Hello</p> ]

Example:
$("p").addClass("selected highlight")
HTML:
<p>Hello</p>
Result:
[ <p class="selected highlight">Hello</p> ]

2.1.13 removeClass(String)
removeClass(String class) returns jQuery
Removes all or the specified class(es) from the set of matched elements.

Example:
$("p").removeClass()
HTML:
<p class="selected">Hello</p>
Result:
[ <p>Hello</p> ]

Example:
$("p").removeClass("selected")
HTML:
<p class="selected first">Hello</p>
Result:
[ <p class="first">Hello</p> ]

Example:
$("p").removeClass("selected highlight")
HTML:
<p class="highlight selected first">Hello</p>
Result:
[ <p class="first">Hello</p> ]

2.1.14 toggleClass(String)
toggleClass(String class) returns jQuery
Adds the specified class if it is not present, removes it if it is present.

Example:
$("p").toggleClass("selected")
HTML:
<p>Hello</p><p class="selected">Hello Again</p>
Result:
[ <p class="selected">Hello</p>, <p>Hello Again</p> ]

2.2 Manipulation 
2.2.1 wrap(String)
wrap(String html) returns jQuery
Wrap all matched elements with a structure of other elements. This wrapping process is most
useful for injecting additional stucture into a document, without ruining the original semantic
qualities of a document.
This works by going through the first element provided (which is generated, on the fly, from
the provided HTML) and finds the deepest ancestor element within its structure - it is that
element that will en-wrap everything else.
This does not work with elements that contain text. Any necessary text must be added after
the wrapping is done.

Example:
$("p").wrap("<div class='wrap'></div>");
HTML:
<p>Test Paragraph.</p>
Result:
<div class='wrap'><p>Test Paragraph.</p></div>

2.2.2 wrap(Element)
wrap(Element elem) returns jQuery
Wrap all matched elements with a structure of other elements. This wrapping process is most
useful for injecting additional stucture into a document, without ruining the original semantic
qualities of a document.
This works by going through the first element provided and finding the deepest ancestor
element within its structure - it is that element that will en-wrap everything else.
This does not work with elements that contain text. Any necessary text must be added after
the wrapping is done.

Example:
$("p").wrap( document.getElementById('content') );
HTML:
<p>Test Paragraph.</p><div id="content"></div>
Result:
<div id="content"><p>Test Paragraph.</p></div>

2.2.3 append(<Content>)
append(<Content> content) returns jQuery
Append content to the inside of every matched element.
This operation is similar to doing an appendChild to all the specified elements, adding them
into the document.

Example:
Appends some HTML to all paragraphs.
$("p").append("<b>Hello</b>");
HTML:
<p>I would like to say: </p>
Result:
<p>I would like to say: <b>Hello</b></p>

Example:
Appends an Element to all paragraphs.
$("p").append( $("#foo")[0] );
HTML:
<p>I would like to say: </p><b id="foo">Hello</b>
Result:
<p>I would like to say: <b id="foo">Hello</b></p>

Example:
Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
$("p").append( $("b") );
HTML:
<p>I would like to say: </p><b>Hello</b>
Result:
<p>I would like to say: <b>Hello</b></p>

2.2.4 prepend(<Content>)
prepend(<Content> content) returns jQuery
Prepend content to the inside of every matched element.
This operation is the best way to insert elements inside, at the beginning, of all matched
elements.

Example:
Prepends some HTML to all paragraphs.
$("p").prepend("<b>Hello</b>");
HTML:
<p>I would like to say: </p>
Result:
<p><b>Hello</b>I would like to say: </p>

Example:
Prepends an Element to all paragraphs.
$("p").prepend( $("#foo")[0] );
HTML:
<p>I would like to say: </p><b id="foo">Hello</b>
Result:
<p><b id="foo">Hello</b>I would like to say: </p>

Example:
Prepends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
$("p").prepend( $("b") );
HTML:
<p>I would like to say: </p><b>Hello</b>
Result:
<p><b>Hello</b>I would like to say: </p>

2.2.5 before(<Content>)
before(<Content> content) returns jQuery
Insert content before each of the matched elements.

Example:
Inserts some HTML before all paragraphs.
$("p").before("<b>Hello</b>");
HTML:
<p>I would like to say: </p>
Result:
<b>Hello</b><p>I would like to say: </p>

Example:
Inserts an Element before all paragraphs.
$("p").before( $("#foo")[0] );
HTML:
<p>I would like to say: </p><b id="foo">Hello</b>
Result:
<b id="foo">Hello</b><p>I would like to say: </p>

Example:
Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs.
$("p").before( $("b") );
HTML:
<p>I would like to say: </p><b>Hello</b>Result:
<b>Hello</b><p>I would like to say: </p>

2.2.6 after(<Content>)
after(<Content> content) returns jQuery
Insert content after each of the matched elements.

Example:
Inserts some HTML after all paragraphs.
$("p").after("<b>Hello</b>");
HTML:
<p>I would like to say: </p>
Result:
<p>I would like to say: </p><b>Hello</b>

Example:
Inserts an Element after all paragraphs.
$("p").after( $("#foo")[0] );
HTML:
<b id="foo">Hello</b><p>I would like to say: </p>
Result:
<p>I would like to say: </p><b id="foo">Hello</b>

Example:
Inserts a jQuery object (similar to an Array of DOM Elements) after all paragraphs.
$("p").after( $("b") );
HTML:
<b>Hello</b><p>I would like to say: </p>Result:
<p>I would like to say: </p><b>Hello</b>

2.2.7 clone(Boolean)
clone(Boolean deep) returns jQuery
Clone matched DOM Elements and select the clones.
This is useful for moving copies of the elements to another location in the DOM.

Example:
Clones all b elements (and selects the clones) and prepends them to all paragraphs.
$("b").clone().prependTo("p");
HTML:
<b>Hello</b><p>, how are you?</p>
Result:
<b>Hello</b><p><b>Hello</b>, how are you?</p>

2.2.8 appendTo(<Content>)
appendTo(<Content> content) returns jQuery
Append all of the matched elements to another, specified, set of elements. This operation is,
essentially, the reverse of doing a regular $(A).append(B), in that instead of appending B to
A, you're appending A to B.

Example:
Appends all paragraphs to the element with the ID "foo"
$("p").appendTo("#foo");
HTML:
<p>I would like to say: </p><div id="foo"></div>
Result:
<div id="foo"><p>I would like to say: </p></div>

2.2.9 prependTo(<Content>)
prependTo(<Content> content) returns jQuery
Prepend all of the matched elements to another, specified, set of elements. This operation is,
essentially, the reverse of doing a regular $(A).prepend(B), in that instead of prepending B to
A, you're prepending A to B.

Example:
Prepends all paragraphs to the element with the ID "foo"
$("p").prependTo("#foo");
HTML:
<p>I would like to say: </p><div id="foo"><b>Hello</b></div>
Result:
<div id="foo"><p>I would like to say: </p><b>Hello</b></div>

2.2.10 insertBefore(<Content>)
insertBefore(<Content> content) returns jQuery
Insert all of the matched elements before another, specified, set of elements. This operation
is, essentially, the reverse of doing a regular $(A).before(B), in that instead of inserting B
before A, you're inserting A before B.

Example:
Same as $("#foo").before("p")
$("p").insertBefore("#foo");
HTML:
<div id="foo">Hello</div><p>I would like to say: </p>
Result:
<p>I would like to say: </p><div id="foo">Hello</div>


2.2.11 insertAfter(<Content>)
insertAfter(<Content> content) returns jQuery
Insert all of the matched elements after another, specified, set of elements. This operation is,
essentially, the reverse of doing a regular $(A).after(B), in that instead of inserting B after A,
you're inserting A after B.

Example:
Same as $("#foo").after("p")
$("p").insertAfter("#foo");
HTML:
<p>I would like to say: </p><div id="foo">Hello</div>
Result:
<div id="foo">Hello</div><p>I would like to say: </p>

2.2.12 remove(String)
remove(String expr) returns jQuery
Removes all matched elements from the DOM. This does NOT remove them from the jQuery
object, allowing you to use the matched elements further.
Can be filtered with an optional expressions.

Example:
$("p").remove();
HTML:
<p>Hello</p> how are <p>you?</p>
Result:
how are

Example:
$("p").remove(".hello");
HTML:
<p class="hello">Hello</p> how are <p>you?</p>
Result:
how are <p>you?</p>

2.2.13 empty()
empty() returns jQuery
Removes all child nodes from the set of matched elements.

Example:
$("p").empty()
HTML:
<p>Hello, <span>Person</span> <a href="#">and person</a></p>
Result:
[ <p></p> ]

2.3 Traversing
2.3.1 end()
end() returns jQuery
End the most recent 'destructive' operation, reverting the list of matched elements back to its
previous state. After an end operation, the list of matched elements will revert to the last state
of matched elements.
If there was no destructive operation before, an empty set is returned.



Example:
Selects all paragraphs, finds span elements inside these, and reverts the selection back to
the paragraphs.
$("p").find("span").end();
HTML:
<p><span>Hello</span>, how are you?</p>
Result:
 [ <p>...</p> ]

2.3.2 find(String)
find(String expr) returns jQuery
Searches for all elements that match the specified expression. This method is a good way to
find additional descendant elements with which to process.
All searching is done using a jQuery expression. The expression can be written using CSS 1-
3 Selector syntax, or basic XPath.

Example:
Starts with all paragraphs and searches for descendant span elements, same as $("p span")
$("p").find("span");
HTML:
<p><span>Hello</span>, how are you?</p>
Result:
[ <span>Hello</span> ]

2.3.3 filter(String)
filter(String expression) returns jQuery
Removes all elements from the set of matched elements that do not match the specified
expression(s). This method is used to narrow down the results of a search.
Provide a comma-separated list of expressions to apply multiple filters at once.

Example:
Selects all paragraphs and removes those without a class "selected".
$("p").filter(".selected")
HTML:
<p class="selected">Hello</p><p>How are you?</p>
Result:
[ <p class="selected">Hello</p> ]

Example:
Selects all paragraphs and removes those without class "selected" and being the first one.
$("p").filter(".selected, :first")
HTML:
<p>Hello</p><p>Hello Again</p><p class="selected">And Again</p>
Result:
[ <p>Hello</p>, <p class="selected">And Again</p> ]

2.3.4 filter(Function)
filter(Function filter) returns jQuery
Removes all elements from the set of matched elements that do not pass the specified filter.
This method is used to narrow down the results of a search.

Example:
Remove all elements that have a child ol element
$("p").filter(function(index) {
 return $("ol", this).length == 0;
})
HTML:
<p><ol><li>Hello</li></ol></p><p>How are you?</p>
Result:
[ <p>How are you?</p> ]

2.3.5 not(Element)
not(Element el) returns jQuery
Removes the specified Element from the set of matched elements. This method is used to
remove a single Element from a jQuery object.

Example:
Removes the element with the ID "selected" from the set of all paragraphs.
$("p").not( $("#selected")[0] )
HTML:
<p>Hello</p><p id="selected">Hello Again</p>
Result:
[ <p>Hello</p> ]

2.3.6 not(String)
not(String expr) returns jQuery
Removes elements matching the specified expression from the set of matched elements.
This method is used to remove one or more elements from a jQuery object.

Example:
Removes the element with the ID "selected" from the set of all paragraphs.
$("p").not("#selected")
HTML:
<p>Hello</p><p id="selected">Hello Again</p>
Result:
[ <p>Hello</p> ]

2.3.7 not(jQuery)
not(jQuery elems) returns jQuery
Removes any elements inside the array of elements from the set of matched elements. This
method is used to remove one or more elements from a jQuery object.

Example:
Removes all elements that match "div p.selected" from the total set of all paragraphs.
$("p").not( $("div p.selected") )
HTML:
<div><p>Hello</p><p class="selected">Hello Again</p></div>
Result:
[ <p>Hello</p> ]

2.3.8 add(String)
add(String expr) returns jQuery
Adds more elements, matched by the given expression, to the set of matched elements.

Example:
$("p").add("span")
HTML:
<p>Hello</p><span>Hello Again</span>
Result:
[ <p>Hello</p>, <span>Hello Again</span> ]

add(String html) returns jQuery
Adds more elements, created on the fly, to the set of matched elements.

Example:
$("p").add("<span>Again</span>")
HTML:
<p>Hello</p>
Result:
[ <p>Hello</p>, <span>Again</span> ]

2.3.9 add(Element|Array<Element>)
add(Element|Array<Element> elements) returns jQuery
Adds one or more Elements to the set of matched elements.

Example:
$("p").add( document.getElementById("a") )
HTML:
<p>Hello</p><p><span id="a">Hello Again</span></p>
Result:
[ <p>Hello</p>, <span id="a">Hello Again</span> ]

Example:
$("p").add( document.forms[0].elements )
HTML:
<p>Hello</p><p><form><input/><button/></form>
Result:
[ <p>Hello</p>, <input/>, <button/> ]

2.3.10 is(String)
is(String expr) returns Boolean
Checks the current selection against an expression and returns true, if at least one element
of the selection fits the given expression.
Does return false, if no element fits or the expression is not valid.
filter(String) is used internally, therefore all rules that apply there apply here, too.

Example:
Returns true, because the parent of the input is a form element
$("input[@type='checkbox']").parent().is("form")
HTML:
<form><input type="checkbox" /></form>
Result:
true

Example:
Returns false, because the parent of the input is a p element
$("input[@type='checkbox']").parent().is("form")
HTML:
<form><p><input type="checkbox" /></p></form>
Result:
false

2.3.11 parent(String)
parent(String expr) returns jQuery
Get a set of elements containing the unique parents of the matched set of elements.
Can be filtered with an optional expressions.

Example:
Find the parent element of each paragraph.
$("p").parent()
HTML:
<div><p>Hello</p><p>Hello</p></div>
Result:
[ <div><p>Hello</p><p>Hello</p></div> ]

Example:
Find the parent element of each paragraph with a class "selected".
$("p").parent(".selected")
HTML:
<div><p>Hello</p></div><div class="selected"><p>Hello Again</p></div>
Result:
[ <div class="selected"><p>Hello Again</p></div> ]

2.3.12 parents(String)
parents(String expr) returns jQuery
Get a set of elements containing the unique ancestors of the matched set of elements
(except for the root element).
Can be filtered with an optional expressions.

Example:
Find all parent elements of each span.
$("span").parents()
HTML:
<html><body><div><p><span>Hello</span></p><span>Hello
Again</span></div></body></html>
Result:
[ <body>...</body>, <div>...</div>, <p><span>Hello</span></p> ]

Example:
Find all parent elements of each span that is a paragraph.
$("span").parents("p")
HTML:
<html><body><div><p><span>Hello</span></p><span>Hello
Again</span></div></body></html>
Result:
[ <p><span>Hello</span></p> ]

2.3.13 next(String)
next(String expr) returns jQuery
Get a set of elements containing the unique next siblings of each of the matched set of
elements.
It only returns the very next sibling, not all next siblings.
Can be filtered with an optional expressions.

Example:
Find the very next sibling of each paragraph.
$("p").next()
HTML:
<p>Hello</p><p>Hello Again</p><div><span>And Again</span></div>
Result:
[ <p>Hello Again</p>, <div><span>And Again</span></div> ]

Example:
Find the very next sibling of each paragraph that has a class "selected".
$("p").next(".selected")
HTML:
<p>Hello</p><p class="selected">Hello Again</p><div><span>And Again</span></div>
Result:
[ <p class="selected">Hello Again</p> ]

2.3.14 prev(String)
prev(String expr) returns jQuery
Get a set of elements containing the unique previous siblings of each of the matched set of
elements.
Can be filtered with an optional expressions.
It only returns the immediately previous sibling, not all previous siblings.

Example:
Find the very previous sibling of each paragraph.
$("p").prev()
HTML:
<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
Result:
[ <div><span>Hello Again</span></div> ]

Example:
Find the very previous sibling of each paragraph that has a class "selected".
$("p").prev(".selected")
HTML:
<div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p>
Result:
[ <div><span>Hello</span></div> ]

2.3.15 siblings(String)
siblings(String expr) returns jQuery
Get a set of elements containing all of the unique siblings of each of the matched set of
elements.
Can be filtered with an optional expressions.

Example:
Find all siblings of each div.
$("div").siblings()
HTML:
<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
Result:
[ <p>Hello</p>, <p>And Again</p> ]

Example:
Find all siblings with a class "selected" of each div.
$("div").siblings(".selected")
HTML:
<div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p>
Result:
[ <p class="selected">Hello Again</p> ]

2.3.16 children(String)
children(String expr) returns jQuery
Get a set of elements containing all of the unique children of each of the matched set of
elements.
Can be filtered with an optional expressions.

Example:
Find all children of each div.
$("div").children()
HTML:
<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
Result:
[ <span>Hello Again</span> ]

Example:
Find all children with a class "selected" of each div.
$("div").children(".selected")
HTML:
<div><span>Hello</span><p class="selected">Hello Again</p><p>And Again</p></div>
Result:
[ <p class="selected">Hello Again</p> ]

2.3.17 contains(String)
contains(String str) returns jQuery
Filter the set of elements to those that contain the specified text.

Example:
$("p").contains("test")
HTML:
<p>This is just a test.</p><p>So is this</p>
Result:
[ <p>This is just a test.</p> ]

OK. That's enough for today. I hope now you can work with jquery. I will explain more in my later posts.

all rights reserved by Mostafa Rastgar and Programmer Assistant weblog

Sunday, February 27, 2011

Spring MVC - View

Hey
So far we could setup and config spring and make an advance controller. In simple pattern of MVC we have three aspects: Model, View, Controller.
I explain each of them in the following figure-1:

figure-1: MVC diagram

It is a customary pattern in web and every presentation layer framework should handle each of these three aspects. In Spring MVC we have some facilities in Controller which has be explained. Here I'm going to explain what is View and what kind of views can we have.

Different kinds of view are supported in Spring MVC. But first we should define our views in spring configuration file as a view resolver. For example in Spring MVC(Simple CRUD) post we had determined tiles as a view in spring-servlet.xml file:
    <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/layout/tiles-config.xml</value>
            </list>
        </property>
    </bean>

    <bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
        <property name="order" value="1"/>
    </bean>
all kinds of viewResolver should implements "org.springframework.web.servlet.ViewResolver" and "org.springframework.core.Ordered" so all of them have order property to assign priority. we can have more than one view resolver in spring mvc so we can make priority on this way. so when a result is returned from Controller, Spring MVC looks for the first order of view resolver. if this can handle the return value so view will be accepted but if not it refers to the second one. for example in StudentController:
    @RequestMapping("/edit")
    public String edit() {
        student = studentService.findById(student.getId());
        return "student.edit";
    }

"student.edit" is returned so first spring looks for view resolver and finds tilesViewResolver with order of "1". This kind of viewResolver needs "tilesConfigurer" (a configuration of tiles for more info refer to Spring MVC(Simple CRUD)) and finally in tiles configuration, this return value is handled so it will be accepted.

some other kinds of spring view resolvers are:
  • JSP
        <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
            <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
  • FreeMarker
    <bean id="freemarkerConfigurer"
      class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
      <property name="templateLoaderPath" value="/WEB-INF/templates/"/>
    </bean>
     
    <bean id="viewResolver"
      class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
      <property name="suffix" value=".ftl"/>
    </bean>
  • Velocity
    <bean id="velocityConfigurer"
      class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
      <property name="configLocation" value="WEB-INF/velocity.properties"/>
    </bean>
    <bean id="viewResolver"
      class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
      <property name="suffix" value=".vm"/>
    </bean>
  • Tiles
    <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
            <property name="definitions">
                <list>
                    <value>/WEB-INF/layout/tiles-config.xml</value>
                </list>
            </property>
    </bean>

    <bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
            <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
            <property name="order" value="1"/>
    </bean>
  • ...
in jsp files spring mvc has some basic tags that I am going explain them. These are so simple and basic tags. one of the weakness points of spring MVC is this. there are no advance tag libraries for Spring MVC or even a framework on top of it to handle that (like RichFaces on top of JSF). I had begun a project in PMT in spring framework to make a powerful tag library based on JQuery UI and this project is done successfully.
There are 2 kinds of tags:
  • html tags: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    • form: Renders an HTML 'form' tag and exposes a binding path to inner tags for binding.
    • input: Renders an HTML 'input' tag with type 'text' using the bound value.
    • password: Renders an HTML 'input' tag with type 'password' using the bound value.
    • hidden: Renders an HTML 'input' tag with type 'hidden' using the bound value.
    • select: Renders an HTML 'select' element. Supports databinding to the selected option.
    • option: Renders a single HTML 'option'. Sets 'selected' as appropriate based on bound value.
    • options: Renders a list of HTML 'option' tags. Sets 'selected' as appropriate based on bound value.
    • radiobutton: Renders an HTML 'input' tag with type 'radio'.
    • radiobuttons: Renders multiple HTML 'input' tags with type 'radio'.
    • checkbox: Renders an HTML 'input' tag with type 'checkbox'.
    • checkboxes: Renders multiple HTML 'input' tags with type 'checkbox'.
    • textarea: Renders an HTML 'textarea'.
    • errors: Renders field errors in an HTML 'span' tag.
    • label: Renders a form field label in an HTML 'label' tag.
  • spring tags: <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
    •  htmlEscape: Sets default HTML escape value for the current page.
                  Overrides a "defaultHtmlEscape" context-param in web.xml, if any.
    • escapeBody: Escapes its enclosed body content, applying HTML escaping and/or JavaScript escaping.
                  The HTML escaping flag participates in a page-wide or application-wide setting
                  (i.e. by HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml).
    • message: Retrieves the message with the given code, or text if code isn't resolvable.
                  The HTML escaping flag participates in a page-wide or application-wide setting
                  (i.e. by HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml).
    • theme: Retrieves the theme message with the given code, or text if code isn't resolvable.
                  The HTML escaping flag participates in a page-wide or application-wide setting
                  (i.e. by HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml).
    • hasBindErrors: Provides Errors instance in case of bind errors.
                  The HTML escaping flag participates in a page-wide or application-wide setting
                  (i.e. by HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml).
    • nestedPath: Sets a nested path to be used by the bind tag's path.
    • bind: Provides BindStatus object for the given bind path.
                  The HTML escaping flag participates in a page-wide or application-wide setting
                  (i.e. by HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml).
    • transform: Provides transformation of variables to Strings, using an appropriate
                  custom PropertyEditor from BindTag (can only be used inside BindTag).
                  The HTML escaping flag participates in a page-wide or application-wide setting
                  (i.e. by HtmlEscapeTag or a 'defaultHtmlEscape' context-param in web.xml).
    • url: URL tag based on the JSTL c:url tag.  This variant is fully
              backwards compatible with the standard tag.  Enhancements include support
              for URL template parameters.
    • param: Parameter tag based on the JSTL c:param tag.  The sole purpose is to
              support params inside the spring:url tag.
    • eval: Evaluates a Spring expression (SpEL) and either prints the result or assigns it to a variable.
the form tag has commandName attribute. look this:
<form:form id="studentForm" commandName="student">
...
</form:form> 
It is the name of the model attribute under which the form object is exposed. Defaults to 'command'. model attribute is detemine in controller.
As you remember in Spring MVC(Simple CRUD) sample the controller sets itself to the model attribute and the name is "command":
@ModelAttribute("command")
public BaseController init(HttpServletRequest request, HttpServletResponse response, Model model) {
        this.model = model;
        this.request = request;
        this.response = response;
        ServletRequestDataBinder binder = new ServletRequestDataBinder(this, "command");
        binder.bind(request);
        return this;
    }
code-1

so there is no need to set commandName attribute of form tag in student-edit.jsp because its default is "command".
<form:form id="studentForm">
    <form:hidden path="student.id"/>
    <table>
        <tr>
            <td>name</td>
            <td><form:input path="student.name"/></td>
        </tr>
        <tr>
            <td>average</td>
            <td><form:input path="student.average"/></td>
        </tr>
    </table>
    <input type="submit" value="save" onclick="setFormAction('/student/save.html')"/>
</form:form>
code-2

Ok maybe the major question is what's the need of commandName? commandName do nothing for formTag but most of spring tags have "path" attribute to bind a value from model and set it to model in request time as you can see it in above sample in red. path value is a field of model attribute which is determined commandName attribute of form tag. For example 'path="student.name"' means 'command.student.name' because the default value of commandName attribute is 'command'. command is a type of studentController (look code-1). Finally 'path="student.name"' means "studentController.getStudent().getName()". And in request time it means "studentController.getStudent().setName(input value)".
In Spring MVC(Simple CRUD) I use simple spring tags and tiles as viewResolver. In future posts I'll use more advanced spring tags like: message, bind, security and so on.


all rights reserved by Mostafa Rastgar and Programmer Assistant weblog

Saturday, February 26, 2011

JQuery-Core

Hi
Here I'm going to start jquery training. First of all:
What is jquery?
It is a javascript framework which makes working with javascript easier and more comprehensible. It makes a good APIs for some usual javascript jobs and unify all of methods which are different in every browsers. For example in javascript we are not able to find the position(top and left) of each element. we should write exhausting script code to find it out and finally the behaviour is defferent in some browsers (specially in MSIE). but here in jquery we can call an API to find out it.
var pos = $("#elementId").offset();
alert('top:'+pos.top+' left:'+pos.lef);
you can dowload the latest version of the jquery from here. Both minified and regular versions are avalable in there and every time you can download it. the current verion of jquery is 1.5.
I devide jqurey course to 8 major seasons and in each post i will focus on one of them. The seasons are:
  1. Core
  2. DOM
  3. CSS
  4. JavaScript
  5. Events
  6. Effects
  7. Ajax
  8. Plugins
Ok let's start.
1. Core

1.1 $(String,Element|jQuery)
$(String expr, Element|jQuery context) returns jQuery

This function accepts a string containing a CSS or basic XPath selector which is then used to
match a set of elements.
The core functionality of jQuery centers around this function. Everything in jQuery is based
upon this, or uses this in some way. The most basic use of this function is to pass in an
expression (usually consisting of CSS or XPath), which then finds all matching elements.
By default, $() looks for DOM elements within the context of the current HTML document.

Example:
Finds all p elements that are children of a div element.
$("div > p")
HTML:
<p>one</p> <div><p>two</p></div> <p>three</p>
Result:
[ <p>two</p> ]

Example:
Searches for all inputs of type radio within the first form in the document
$("input:radio", document.forms[0])
 
Example:
This finds all div elements within the specified XML document.
$("div", xml.responseXML)

1.2 $(String)
$(String html) returns jQuery

Create DOM elements on-the-fly from the provided String of raw HTML.

Example:
Creates a div element (and all of its contents) dynamically,  and appends it to the element
with the ID of body. Internally, an element is created and it's innerHTML property set to the
given markup. It is therefore both quite flexible and limited.
$("<div><p>Hello</p></div>").appendTo("#body")

1.3 $(Element|Array<Element>)
$(Element|Array<Element> elems) returns jQuery

Wrap jQuery functionality around a single or multiple DOM Element(s).
This function also accepts XML Documents and Window objects as valid arguments (even
though they are not DOM Elements).

Example:
Sets the background color of the page to black.
$(document.body).background( "black" );

Example:
Hides all the input elements within a form
$( myForm.elements ).hide()

1.4 $(Function)
$(Function fn) returns jQuery

A shorthand for $(document).ready(), allowing you to bind a function to be executed when
the DOM document has finished loading. This function behaves just like
$(document).ready(), in that it should be used to wrap all of the other $() operations on your
page. While this function is, technically, chainable - there really isn't much use for chaining
against it. You can have as many $(document).ready events on your page as you like.
See ready(Function) for details about the ready event.

Example:
Executes the function when the DOM is ready to be used.
$(function(){
 // Document is ready
});

Example:
Uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery
code using the $ alias, without relying on the global alias.
jQuery(function($) {
 // Your code using failsafe $ alias here...
});

1.5 length()
length() returns Number

The number of elements currently matched.

Example:
$("img").length;
HTML:
<img src="test1.jpg"/> <img src="test2.jpg"/>
Result:
2

1.6 size()
size() returns Number

The number of elements currently matched.

Example:
$("img").size();
HTML:
<img src="test1.jpg"/> <img src="test2.jpg"/>
Result:
2

1.7 get()
get() returns Array<Element>

Access all matched elements. This serves as a backwards-compatible way of accessing all
matched elements (other than the jQuery object itself, which is, in fact, an array of elements).

Example:
Selects all images in the document and returns the DOM Elements as an Array
$("img").get();
HTML:
<img src="test1.jpg"/> <img src="test2.jpg"/>
Result:
[ <img src="test1.jpg"/> <img src="test2.jpg"/> ]

1.8 get(Number)
get(Number num) returns Element

Access a single matched element. num is used to access the Nth element matched.

Example:
Selects all images in the document and returns the first one
$("img").get(0);
HTML:
<img src="test1.jpg"/> <img src="test2.jpg"/>
Result:
[ <img src="test1.jpg"/> ]

1.9 each(Function)
each(Function fn) returns jQuery

Execute a function within the context of every matched element. This means that every time
the passed-in function is executed (which is once for every element matched) the 'this'
keyword points to the specific element.
Additionally, the function, when executed, is passed a single argument representing the
position of the element in the matched set.

Example:
Iterates over two images and sets their src property
$("img").each(function(i){
 this.src = "test" + i + ".jpg";
});
HTML:
<img/><img/>
Result:
<img src="test0.jpg"/><img src="test1.jpg"/>

1.10 index(Element)
index(Element subject) returns Number

Searches every matched element for the object and returns the index of the element, if
found, starting with zero.  Returns -1 if the object wasn't found.

Example:
Returns the index for the element with ID foobar
$("*").index( $('#foobar')[0] )
HTML:
<div id="foobar"><b></b><span id="foo"></span></div>
Result:
0

Example:
Returns the index for the element with ID foo within another element
$("*").index( $('#foo')[0] )
HTML:
<div id="foobar"><b></b><span id="foo"></span></div>
Result:
2

Example:
Returns -1, as there is no element with ID bar
$("*").index( $('#bar')[0] )
HTML:
<div id="foobar"><b></b><span id="foo"></span></div>
Result:
-1

1.11 $.extend(Object)
$.extend(Object prop) returns Object

Extends the jQuery object itself. Can be used to add functions into the jQuery namespace
and to add plugin methods (plugins).

Example:
Adds two plugin methods.
jQuery.fn.extend({
 check: function() {
   return this.each(function() { this.checked = true; });
 },
 uncheck: function() {
   return this.each(function() { this.checked = false; });
 }
});
$("input[@type=checkbox]").check();
$("input[@type=radio]").uncheck();

Example:
Adds two functions into the jQuery namespace
jQuery.extend({
 min: function(a, b) { return a < b ? a : b; },
 max: function(a, b) { return a > b ? a : b; }
});

1.12 $.noConflict()
$.noConflict() returns undefined

Run this function to give control of the $ variable back to whichever library first implemented
it. This helps to make  sure that jQuery doesn't conflict with the $ object of other libraries.
By using this function, you will only be able to access jQuery using the 'jQuery' variable. For
example, where you used to do $("div p"), you now must do jQuery("div p").

Example:
Maps the original object that was referenced by $ back to $
jQuery.noConflict();
// Do something with jQuery
jQuery("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';

Example:
Reverts the $ alias and then creates and executes a function to provide the $ as a jQuery
alias inside the functions scope. Inside the function the original $ object is not available. This
works well for most plugins that don't rely on any other library.
jQuery.noConflict();
(function($) {
 $(function() {
   // more code using $ as alias to jQuery
 });
})(jQuery);
// other code using $ as an alias to the other library

1.13 eq(Number)
eq(Number pos) returns jQuery

Reduce the set of matched elements to a single element. The position of the element in the
set of matched elements starts at 0 and goes to length - 1.

Example:
$("p").eq(1)
HTML:
<p>This is just a test.</p><p>So is this</p>
Result:
[ <p>So is this</p> ]

1.14 lt(Number)
lt(Number pos) returns jQuery

Reduce the set of matched elements to all elements before a given position. The position of
the element in the set of matched elements starts at 0 and goes to length - 1.

Example:
$("p").lt(1)
HTML:
<p>This is just a test.</p><p>So is this</p>
Result:
[ <p>This is just a test.</p> ]

1.15 gt(Number)
gt(Number pos) returns jQuery

Reduce the set of matched elements to all elements after a given position. The position of
the element in the set of matched elements starts at 0 and goes to length - 1.

Example:
$("p").gt(0)
HTML:
<p>This is just a test.</p><p>So is this</p>
Result:
[ <p>So is this</p> ]



all rights reserved by Mostafa Rastgar and Programmer Assistant weblog

Wednesday, February 23, 2011

Linux/Unix Common Commands

Hey
Here I am going to review some useful Linux commands. As we are Java programmer and JDK is compatible in most platforms and since most of server platforms are Linux base, so we should know how to work with them. there are some common commands which we need them like copy, cut, remove, service stop, show processes and so on.
I am not going to teach Linux and Linux core. Here I prepare you as a simple user of Linux.
OK let's start:
Note: You can use --help in front of any following command to display help of the specified command. But some practical switches will be available here.
Example: ls --help
Result:
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort.

Mandatory arguments to long options are mandatory for short options too.
  -a, --all                  do not ignore entries starting with .
  -A, --almost-all           do not list implied . and ..
      --author               with -l, print the author of each file
  -b, --escape               print octal escapes for nongraphic characters
      --block-size=SIZE      use SIZE-byte blocks
  -B, --ignore-backups       do not list implied entries ending with ~
  -c                         with -lt: sort by, and show, ctime (time of last
                               modification of file status information)
                               with -l: show ctime and sort by name
                               otherwise: sort by ctime
  -C                         list entries by columns
      --color[=WHEN]         control whether color is used to distinguish file
                               types.  WHEN may be `never', `always', or `auto'
  -d, --directory            list directory entries instead of contents,
                               and do not dereference symbolic links
  -D, --dired                generate output designed for Emacs' dired mode
  -f                         do not sort, enable -aU, disable -lst
  -F, --classify             append indicator (one of */=>@|) to entries
      --file-type            likewise, except do not append `*'
      --format=WORD          across -x, commas -m, horizontal -x, long -l,
                               single-column -1, verbose -l, vertical -C
      --full-time            like -l --time-style=full-iso
  -g                         like -l, but do not list owner
  -G, --no-group             like -l, but do not list group
  -h, --human-readable       with -l, print sizes in human readable format
                               (e.g., 1K 234M 2G)
      --si                   likewise, but use powers of 1000 not 1024
  -H, --dereference-command-line
                             follow symbolic links listed on the command line
      --dereference-command-line-symlink-to-dir
                             follow each command line symbolic link
                             that points to a directory
      --hide=PATTERN         do not list implied entries matching shell PATTERN
                               (overridden by -a or -A)
      --indicator-style=WORD append indicator with style WORD to entry names:
                               none (default), slash (-p),
                               file-type (--file-type), classify (-F)
  -i, --inode                with -l, print the index number of each file
  -I, --ignore=PATTERN       do not list implied entries matching shell PATTERN
  -k                         like --block-size=1K
  -l                         use a long listing format
  -L, --dereference          when showing file information for a symbolic
                               link, show information for the file the link
                               references rather than for the link itself
  -m                         fill width with a comma separated list of entries
  -n, --numeric-uid-gid      like -l, but list numeric user and group IDs
  -N, --literal              print raw entry names (don't treat e.g. control
                               characters specially)
  -o                         like -l, but do not list group information
  -p, --indicator-style=slash
                             append / indicator to directories
  -q, --hide-control-chars   print ? instead of non graphic characters
      --show-control-chars   show non graphic characters as-is (default
                             unless program is `ls' and output is a terminal)
  -Q, --quote-name           enclose entry names in double quotes
      --quoting-style=WORD   use quoting style WORD for entry names:
                               literal, locale, shell, shell-always, c, escape
  -r, --reverse              reverse order while sorting
  -R, --recursive            list subdirectories recursively
  -s, --size                 with -l, print size of each file, in blocks
  -S                         sort by file size
      --sort=WORD            extension -X, none -U, size -S, time -t,
                             version -v, status -c, time -t, atime -u,
                             access -u, use -u
      --time=WORD            with -l, show time as WORD instead of modification
                             time: atime, access, use, ctime or status; use
                             specified time as sort key if --sort=time
      --time-style=STYLE     with -l, show times using style STYLE:
                             full-iso, long-iso, iso, locale, +FORMAT.
                             FORMAT is interpreted like `date'; if FORMAT is
                             FORMAT1<newline>FORMAT2, FORMAT1 applies to
                             non-recent files and FORMAT2 to recent files;
                             if STYLE is prefixed with `posix-', STYLE
                             takes effect only outside the POSIX locale
  -t                         sort by modification time
  -T, --tabsize=COLS         assume tab stops at each COLS instead of 8
  -u                         with -lt: sort by, and show, access time
                               with -l: show access time and sort by name
                               otherwise: sort by access time
  -U                         do not sort; list entries in directory order.
                             In combination with one_per_line format `-1',
                             it will show files immediately and it has no
                             memory limitations.
  -v                         sort by version
  -w, --width=COLS           assume screen width instead of current value
  -x                         list entries by lines instead of by columns
  -X                         sort alphabetically by entry extension
  -1                         list one file per line

SELinux options:

      --lcontext             Display security context.   Enable -l. Lines
                               will probably be too wide for most displays.
      -Z, --context          Display security context so it fits on most
                               displays.  Displays only mode, user, group,
                               security context and file name.
      --scontext             Display only security context and file name.


      --help     display this help and exit
      --version  output version information and exit

SIZE may be (or may be an integer optionally followed by) one of following:
kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.

By default, color is not used to distinguish types of files.  That is
equivalent to using --color=none.  Using the --color option without the
optional WHEN argument is equivalent to using --color=always.  With
--color=auto, color codes are output only if standard output is connected
to a terminal (tty).  The environment variable LS_COLORS can influence the
colors, and can be set easily by the dircolors command.

Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.

Report bugs to <bug-coreutils@gnu.org>.


  1. pwd: To show the current directory where you are in. you can use this command any where.
    Example: [root@testserver ~]# pwd
    Result: /root
  2. clear: To clear the screen.
    Example: [root@testserver ~]# clear
    Result: [root@testserver ~]#
  3. cd: To change the current directory to specified directory.
    1. cd /: return to the root path
    2. cd ..: return to the upper directory
    3. cd .: return to the current directory
    Example: [root@testserver ~]# cd /opt/data
    Result: [root@testserver data]#
  4. ls: To list the directory content.
    1. ls -list: lists the directory content in detail like creation time, size and so on.
    2. ls -f: does not sort.
    3. ls | grep a: lists the directory content containing 'a' in their name
  5. cp source destination: To copy source to destination.
    Example: [root@testserver opt]# cp test.cnf /root/test.cnf
    Result: copies test.cnf from current directory(/opt) to /root directory
  6. cp -r source destination: To copy source directory to destination.
    Example: [root@testserver opt]# cp -r data /root/data2
    Result: copies data folder to /root directory in new name (data2)
  7. mv source destination: To cut(move) source to destination. you can also use it to rename a directory or file.
    Example: [root@testserver opt]# mv data data2
    Result: renames data directory to data2
  8. rm filename: To remove file with specified filename
    Example: [root@testserver opt]# rm /root/test.cnf
    Result: removes test.cnf in /root path
  9. rm -rf directoryname: To remove directory and all containing files and sub-directories recursively(r) without prompting(f)
    Example: [root@testserver opt]# rm -rf /root/data2
    Result: remove data2 directory and all its containing data from /root path
  10. ps aux: To list the running system processes in detail like cpu usage, memory usage, process id and so on.
    Example: [root@testserver opt]# ps aux
    Result:
    USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
    root         1  0.0  0.0  10348   548 ?        Ss   Jan11   0:01 init [5]
    root         2  0.0  0.0      0     0 ?        S<   Jan11   0:00 [migration/0]
    root         3  0.0  0.0      0     0 ?        SN   Jan11   0:00 [ksoftirqd/0]
    root         4  0.0  0.0      0     0 ?        S<   Jan11   0:00 [watchdog/0]
    root         5  0.0  0.0      0     0 ?        S<   Jan11   0:00 [migration/1]
    root         6  0.0  0.0      0     0 ?        SN   Jan11   0:00 [ksoftirqd/1]
    root         7  0.0  0.0      0     0 ?        S<   Jan11   0:00 [watchdog/1]
    root         8  0.0  0.0      0     0 ?        S<   Jan11   0:00 [migration/2]
    root         9  0.0  0.0      0     0 ?        SN   Jan11   0:00 [ksoftirqd/2]
    ...
  11. ps aux | grep somthing: To Filter the list of processes to specified name. It searches in processes detail and variables by specified name and show you in details.
    Example: [root@testserver opt]# ps aux | grep tomcat
    Result:
    root      5593  0.0  9.3 1460380 370892 ?      Sl   Feb19   3:38 /opt/jdk1.6.0_07/bin/java -Djava.util.logging.config.file=/opt/apache-tomcat-6.0.18/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Xms256m -Xmx1024m -XX:MaxPermSize=256m -Djava.endorsed.dirs=/opt/apache-tomcat-6.0.18/endorsed -classpath /opt/apache-tomcat-6.0.18/bin/bootstrap.jar -Dcatalina.base=/opt/apache-tomcat-6.0.18 -Dcatalina.home=/opt/apache-tomcat-6.0.18 -Djava.io.tmpdir=/opt/apache-tomcat-6.0.18/temp org.apache.catalina.startup.Bootstrap start
    root     22672  0.0  0.0  61180   744 pts/5    S+   12:04   0:00 grep tomcat

  12. kill -9 PID: To kill the process with specified PID. you can find PID by ps command then use this command to kill it.
    Note: PID is not fix for processes. A new PID will be assign any time you run some process so you should first catch it by ps command.
    Example: [root@testserver opt]# kill -9 5593
    Result: kills process with id of 5593(tomcat process)
  13. unzip zipfilename: To unzip the zipped file.
    Example: [root@testserver opt]# unzip test.zip
    Result: unzips the test.zip file.
  14. execute a process: you should just write the executive file with its path then press enter to start it. if you want to start it in background of the shell put '&' sign in front of the file name
    Example: [root@testserver bin]# ./catalina.sh run &
    Result: executes catalina.sh in back ground with run switch(the needed parameter of this file). if you don't specify '&' sign it shows you in the current shell and you will not able to write a new command. so you should first stop it. In this state (running the process in current shell) press Ctrl + c to stop it. But if you run it in background, you should kill this process to stop it.
  15. service  --status-all: To list the current services and their status.
    Example: [root@testserver opt]# service  --status-all
    Result:
    acpid (pid 2410) is running...
    anacron is stopped
    atd (pid  2627) is running...
    auditd (pid  2138) is running...
    automount (pid 2476) is running...
    Avahi daemon is running
    Avahi DNS daemon is not running
    hcid (pid 2330) is running...
    sdpd (pid 2336) is running...
    capi not installed - No such file or directory (2)
    conmand is stopped
    cpuspeed is stopped
    crond (pid  2581) is running...
    cupsd (pid  2520) is running...
    cups-config-daemon is obsolete
    dnsmasq is stopped
    dund is stopped
    Usage: /etc/init.d/firstboot {start|stop}
    gpm (pid  2572) is running...
    hald (pid 2419) is running...
    hidd (pid 2453) is running...
    hpiod (pid 2493) is running...
    hpssd (pid 2498) is running...
    Firewall is stopped.
    ipmi_msghandler module not loaded.
    ipmi_si module not loaded.
    ipmi_devintf module not loaded.
    /dev/ipmi0 does not exist.
    Firewall is stopped.
    irattach is stopped
    irqbalance (pid 2220) is running...
    Kdump is not operational
    krb524d is stopped
    mcstransd (pid 1904) is running...
    mdadm is stopped
    mdmpd is stopped
    dbus-daemon (pid 2308) is running...
    multipathd is stopped
    mysqld (pid 21367) is running...
    netconsole module not loaded
    netplugd is stopped
    Configured devices:
    lo eth0
    Currently active devices:
    lo eth0
    NetworkManager is stopped
    rpc.mountd is stopped
    nfsd is stopped
    rpc.rquotad is stopped
    rpc.statd (pid  2269) is running...
    nscd is stopped
    ntpd is stopped
    pand is stopped
    pcscd (pid  2400) is running...
    portmap (pid 2231) is running...
    Process accounting is disabled.
    rdisc is stopped
    restorecond (pid  2157) is running...
    rpc.idmapd (pid 2293) is running...
    saslauthd is stopped
    sendmail (pid  2553) is running...
    setroubleshootd (pid  2320) is running...
    smartd (pid 2719) is running...
    openssh-daemon (pid  2511) is running...
    syslogd (pid  2166) is running...
    klogd (pid  2169) is running...
    Xvnc is stopped
    wdaemon is stopped
    winbindd is stopped
    wpa_supplicant is stopped
    xfs (pid  2610) is running...
    xinetd (pid  2534) is running...
    ypbind is stopped
    yum-updatesd (pid 2850) is running...
  16. service servicename [stop|start|restart]: To stop or start or restart the service with specified service name.
    Example: [root@testserver opt]# service mysqld restart
    Result:
    Stopping MySQL:                                            [  OK  ]
    Starting MySQL:                                            [  OK  ]
  17. vi filename: To edit or even create (if not exist) a file content. It opens the specified file in editor. you can first view it. but if you are going to change it, press Insert key on your keyboard then you can change it. after changing:
    1. Esc then ":w" then Enter: will save the file.
    2. Esc then ":q" then Enter: will quit the editor.
    3. Esc then ":wq" then Enter: will save the file and quit the editor.
    4. Esc then ":q!" then Enter: will quit editor without saving the file.
  18. free: To show memory status like total size, free space and so on.
    Example: [root@testserver opt]# free
    Result:
                 total       used       free     shared    buffers     cached
    Mem:       3979020    3642384     336636          0     256836    1167672
    -/+ buffers/cache:    2217876    1761144
    Swap:      6029304     382832    5646472
  19. df: To show the discs and their status.
    Example: [root@testserver opt]# df
    Result:
    Filesystem           1K-blocks      Used Available Use% Mounted on
    /dev/mapper/VolGroup00-LogVol00
                         230601592   7762296 210936320   4% /
    /dev/sda1               101086     12508     83359  14% /boot
    tmpfs                  1989508         0   1989508   0% /dev/shm
  20. chmod -R MOD directory|file: To define permissions for specified directory or file. if you want to assign the permission to all containing files and sub-directory of the specified directory, you should use -R else it is not necessary. MOD is a 3 or 4 digits. every digits has it own meaning. Take a look the following gadget. click any box and see the result. the result will be the MOD.

    R W X
    Owner
    Group
    Others
    Result:
  21. export variableName="value": to define a variable with specified name and value.
    Example: [root@testserver opt]# export test="/opt/data"
    Result: test variable will be created.
  22. echo $variableName: to show variable value.
    Example: [root@testserver opt]# echo $test
    Result: /opt/data
I think it is enough for today. Maybe I will explain something around it in my future posts like: how to setup something, create a service, run something in start up and so on.


all rights reserved by Mostafa Rastgar and Programmer Assistant weblog