Servlet filters special HTML characters and servlet special characters of strings

Source: Internet
Author: User

Servlet filters special HTML characters and servlet special characters of strings

(1) In some cases, when users enter data, we need to determine whether the data is valid, that is, to filter out whether the user input information contains special characters;

(2) directly add the code for your reference:

ServletUtilities class:

package com.lc.ch04Biaodanshuju;import javax.servlet.http.HttpServletRequest;public class ServletUtilities {   public static String filter(String input) {    if (!hasSpecialChars(input)) {      return(input);    }    StringBuffer filtered = new StringBuffer(input.length());    char c;    for(int i=0; i<input.length(); i++) {      c = input.charAt(i);      switch(c) {        case '<': filtered.append("<"); break;        case '>': filtered.append(">"); break;        case '"': filtered.append("""); break;        case '&': filtered.append("&"); break;        default: filtered.append(c);      }    }    return(filtered.toString());  }  private static boolean hasSpecialChars(String input) {    boolean flag = false;    if ((input != null) && (input.length() > 0)) {      char c;      for(int i=0; i<input.length(); i++) {        c = input.charAt(i);        switch(c) {          case '<': flag = true; break;          case '>': flag = true; break;          case '"': flag = true; break;          case '&': flag = true; break;        }      }    }    return(flag);  }}


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><!-- Front end to BadCodeServlet.Taken from Core Servlets and JavaServer Pages 2nd Editionfrom Prentice Hall and Sun Microsystems Press,http://www.coreservlets.com/.(C) 2003 Marty Hall; may be freely used or adapted.--><HTML><HEAD><TITLE>Submit Code Sample</TITLE></HEAD><BODY BGCOLOR="#FDF5E6"><CENTER><H1 ALIGN="CENTER">Submit Code Sample</H1><FORM ACTION="/servlet/coreservlets.BadCodeServlet">  Code:<BR>  <TEXTAREA ROWS="6" COLS="40" NAME="code"></TEXTAREA><P>  <INPUT TYPE="SUBMIT" VALUE="Submit Code"></FORM></CENTER></BODY></HTML>

package com.lc.ch04Biaodanshuju;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class BadCodeServlet extends HttpServlet {  public void doGet(HttpServletRequest request,                    HttpServletResponse response)      throws ServletException, IOException {    response.setContentType("text/html");    PrintWriter out = response.getWriter();    String title = "Code Sample";    String docType =      "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +      "Transitional//EN\">\n";    out.println(docType +                "<HTML>\n" +                "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +                "<BODY BGCOLOR=\"#FDF5E6\">\n" +                "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +                "<PRE>\n" +                getCode(request) +                "</PRE>\n" +                "Now, wasn't that an interesting sample\n" +                "of code?\n" +                "</BODY></HTML>");  }  protected String getCode(HttpServletRequest request) {    return(request.getParameter("code"));  }}




How to filter HTML Tag characters in a string

The following is a method in asp. You can convert it to. net
Function FilterHTML (strToFilter)
Dim strTemp
StrTemp = strToFilter
StrTemp = replace (strTemp ,"""","")
StrTemp = replace (strTemp ,"","")
StrTemp = replace (strTemp ,"","")
StrTemp = replace (strTemp ,"","")
StrTemp = replace (strTemp ,"&","")
Dim n, M' defines three variables
N = inStr (strTemp, "<") 'find the location where the first "<" is located
M = inStr (strTemp, ">") 'locate the first ">" Location
Do while n> 0 and n <m' if n> 0, it indicates that a "<" is found. If n <m, it indicates "<" on the left of ">, the string between "<" and ">" is HTML code and needs to be filtered out.
StrTemp = Left (strTemp, n-1) & Mid (strTemp, m + 1) 'take the string on the Left and the string on the right and connect them together
N = inStr (strTemp, "<") 'find the location of the first "<" in the remaining string
M = inStr (strTemp, ">") 'locate the first position in the remaining string ">"
Loop
FilterHTML = strTemp
End Function

Function used by VC to filter special characters in a string, such as double quotation marks

If you want a sub-function, you just need to change it. It should be done. Press CTRL + Z to finish the input.
# Include <stdio. h>

Int main ()
{
Char a [100], ch;
Int I = 0, j;
While (ch = getchar ())! = EOF)
If (ch> = '0' & ch <= '9') | (ch <= 'Z' & ch> = 'A ') | (ch> = 'A' & ch <= 'Z ')){
A [I] = ch;
I ++;
}
For (j = 0; j <I; j ++)
Printf ("% c", a [j]);
Printf ("\ n ");
Return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.