In jsp, if you need to process complex data, defining a java method above is a very effective solution, and pushing the responsibility for processing data to this method, then the main process of the jsp page will not be affected. Of course, you can also use js definition methods for processing. js seems to be better at defining such methods to process Foreground Data, however, sometimes garbled characters or errors that cannot find objects may occur during data dumping between jsp and js. Therefore, the less the mutual value between them, the better.
Let's take a look at the method for defining a string in jsp:
Copy codeThe Code is as follows:
<%!
String splitString (String str, int ){
If (str! = Null & str. trim (). length ()> 0 & a> 0 ){
// Obtain the length of the string in bytes
Int length = str. getBytes (). length;
// All excluding Chinese Characters
If (str. length () = length ){
// If the truncation length is less than the string length, substring. Otherwise, this string will be taken.
If (a <str. length ()){
Return str. substring (0, );
} Else {
Return str;
}
} // Contains Chinese Characters
Else {
StringBuffer sb = new StringBuffer ();
// Intercept the algorithm to traverse the string and monitor the Value
For (int I = 0; I <str. length () & a> 0; I ++ ){
// If it is a Chinese character, calculate two lengths.
If (str. charAt (I)> = '\ u4e00' & str. charAt (I) <=' \ u9fa5 '){
// If it is a Chinese character and not the last character, add it. Otherwise, no
If (a> 1 ){
Sb. append (str. charAt (I ));
A-= 2;
}
// It is not a Chinese character but a single length.
} Else {
Sb. append (str. charAt (I ));
A --;
}
}
Return sb. toString ();
}
}
Return "incorrect input ";
}
%>
The function of this method is to input a string and length, and return the truncated string. The length will be measured in the form of two Chinese characters and one letter or number. If the last one is a Chinese character, in this case, the Chinese character will be discarded and there will never be a half Chinese character.
Note the following when defining methods in jsp:
1, use <%! %> This label is a flag for defining variables or methods in jsp.
2. If you need to use the built-in object out In the method, you must pass it in the parameter list of the method and let the method run out of an IO exception.
3. Do not define the scope of the method. It is used internally. Use the default range directly.