how to Encode and decode text in Jsp - java

<%#page import="java.net.URLDecoder"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.net.URLDecoder"%>
<%#page import="java.net.URLEncoder"%>
<html>
<form action="index.jsp">
<body>
First INPUT:
<input name="firstinput" type="text" name="fname">
<br>
<input type="submit" value="Submit">
<%
String first = request.getParameter("firstinput");
String Searchtext=URLDecoder.decode(first,"UTF-8");
out.println(Searchtext);
out.println(URLEncoder.encode(Searchtext,"UTF-8"));
%>
</body>
</form>
</html>
This is My code I want to Encode and Decode text in Jsp Actully I want that when Input Text " ",' ',/ /...any special charter it should print same as it is text like if Input "hello" or hello then it should Print hello or if input 'hello' then also it should Print hello... special charter should Not display please help me i am Unable to do this ...

I think you need this:
String lWithoutSpecials = first.replaceAll("[^\\p{Alpha}]+","");
For me it works great:
String s = "\\Hello\\ \"Hello\" 'Hello'";
String lWithoutSpecials = s.replaceAll("[^\\p{Alpha}]+", "");
System.out.println(lWithoutSpecials);
Output:
HelloHelloHello

You are not using full Unicode but Latin-1, ISO-8859-1. This Latin-1 will browsers
interprete as MS Windows Latin-1, or "Cp-1252"/"Windows-1252". This charset has some special characters like comma like quotes, € (euro), etcetera.
URL encoding/decoding is done automatically. The data entry of the input may
cause numeric HTML entities to arrive at the server, like Ӓ when having a restricted charset like Latin-1. With UTF-8 for the entire Unicode characters you need to add to the <form accept-charset="UTF8"> to prevent substitution by numeric entities.
A HTML 5 form:
<%#page language="java" contentType="text/html; charset=Windows-1252"
pageEncoding="Windows-1252"
import="java.net.URLDecoder"
import="java.net.URLEncoder"
%><!DOCTYPE html>
<html>
<head>
<title>First Input</title>
<meta charset="ISO-8859-1">
</head>
<body>
<form action="index.jsp">
First INPUT:
<input name="firstinput" type="text"
value="${param.firstinput}">
<br>
<input type="submit" value="Submit">
<%
String first = request.getParameter("firstinput");
String searchtext = first;
out.println(searchtext);
%>
</form>
</body>
</html>
It lies saying its charset is the limited ISO-8859-1, but java delivers the larger charset Windows-1252.
The tag <form> must be inside the <body>. If you did that for form margins and such, use CSS styles.

Related

JSoup - Formatting the <option> elements

Let's say I have this HTML :
<html>
<head>
</head>
<body>
<form method="post">
<select name="books">
<option value="111">111</option>
<option value="222">222</option>
</select>
</form>
</body>
</html>
I load it in Jsoup and get the result back :
Document doc = Jsoup.parse(html);
doc.outputSettings().indentAmount(4);
doc.outputSettings().charset("UTF-8");
doc.outputSettings().prettyPrint(true);
String result = doc.outerHtml();
This result is :
<html>
<head>
</head>
<body>
<form method="post">
<select name="books"> <option value="111">111</option> <option value="222">222</option> </select>
</form>
</body>
</html>
The <option> elements are all on the same line!
How can I have Jsoup to format the <option> elements so the result is the same than the input, in this example?
doc.outputSettings().charset("UTF-8");
When parsing just html from a string, the default charset is UTF-8, unless you otherwise set the charset using File or InputStream as your parse input.
Therefore, the charset on OutputSettings will default to the same as input, which is UTF-8, in your case. You only need to set this if you want it to be different from the input.
Document.OutputSettings.charset()
Get the document's current output charset, which is used to control which characters are escaped when generating HTML (via the html() methods), and which are kept intact.
Where possible (when parsing from a URL or File), the document's output charset is automatically set to the input charset. Otherwise, it defaults to UTF-8.
doc.outputSettings().prettyPrint(true);
You don't need to enable pretty print, it is on by default.
Document.OutputSettings.prettyPrint()
Get if pretty printing is enabled. Default is true. If disabled, the
HTML output methods will not re-format the output, and the output will
generally look like the input.
doc.outputSettings().outline(true);
This is the key tag. When this is not set, only block tags are displayed as such (option is not a block tag). When it is enabled, all tags are considered block elements.
Document.OutputSettings.outline()
Get if outline mode is enabled. Default is false. If enabled, the HTML output methods will consider all tags as block.
So your final block of code should look something like this:
Document doc = Jsoup.parse(html);
doc.outputSettings().indentAmount(4).outline(true);
String result = doc.outerHtml();
Output
<html>
<head>
</head>
<body>
<form method="post">
<select name="books">
<option value="111">111</option>
<option value="222">222</option>
</select>
</form>
</body>
</html>

How to write the data dynamically from Jsp to text file using servlet?

I am trying to store the data from jsp page,which has many fields like
type of service
online
offline etc ,based on the selection it has to write the data to the file,
now I am able to store statically where it is storing the selection value and null value for not selected values.
Thanks
i undestand what you are trying to say . find out the code . one JSP is used for Text field and another JSP is used for Storing input field value on text file .
<HTML>
<HEAD>
<TITLE>Please Sign My Guest Book!</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1>Please Sign My Guest Book!</H1>
<FORM ACTION="basic.jsp" METHOD="POST">
Your name:
<INPUT TYPE="TEXT" NAME="TEXT1">
<BR>
<BR>
<BR>
Your comments:
<BR>
<TEXTAREA NAME="TEXTAREA1" ROWS="5" COLS="50"></TEXTAREA>
<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit"><INPUT TYPE="RESET" VALUE="Reset">
</FORM>
</CENTER>
</BODY>
and For Storing Input Filed value on Text File .
<%# page import="java.io.*" %>
<HTML>
<HEAD>
</HEAD>
<BODY>
<H1>Thanks for Adding to the Guest Book!</H1>
Here's what you and others have said:
<BR>
<BR>
<%
String name = request.getParameter("TEXT1");
String text = request.getParameter("TEXTAREA1");
String file = application.getRealPath("/") + "test.txt";
FileWriter filewriter = new FileWriter(file, true);
filewriter.write("<B>Name: </B>" + name + "<BR>");
filewriter.write("<B>Comments: </B><BR>");
filewriter.write(text + "<BR><BR>");
filewriter.close();
%>
<jsp:include page="ch15_04.txt" flush="true"/>
</BODY>
Happy to Help Feel free to give your opinion .

Cannot get the parameters in the server

I got a problem when I try to get parameters from the request, I got nothing but NULL.
The JSP file is like this:
<%# page contentType="text/html; charset=UTF-8" %>
<%# taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%# taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%# taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html:html locale="true">
<head>
<META HTTP-EQUIV="pragma" CONTENT="no-cache">
<META HTTP-EQUIV="cache-control" CONTENT="no-cache">
<META HTTP-EQUIV="expires" CONTENT="0">
<META HTTP-EQUIV="Content-Type" content="text/html; charset=UTF-8">
<META HTTP-EQUIV="Content-Script-Type" content="text/javascript">
<META HTTP-EQUIV="Content-Style-Type" content="text/css">
<link rel="stylesheet" type="text/css" href="css/base.css">
<title>Menu</title>
<SCRIPT language="JavaScript">
<!--
function nextPage(url) {
location.replace(url);
}
function setUrl(url) {
document.forms[0].url.value = url;
}
//-->
</SCRIPT>
</head>
<body tabindex="-1">
<%-- ページ・ボディ --%>
<html:form action="/select.do?apl500_p=1" method="post" target="_self" >
<html:hidden property="url" value ="" />
<table style="width:100%;" border="0">
<tr>
<td style="width:100%;text-align:center">
<font size="5" color="#000000">
<B>Menu</B></font>
</td>
<td style="text-align:right">
<html:submit property="submit_logout" value="Logout" tabindex="-1"/>
</td>
</tr>
</table>
<hr><br>
<div align="center" style="width:90%;height:482px;overflow:auto;margin-left:40px;">
<table border="0">
<tr>
<td style="width:100%;text-align:center">
<html:submit property="btn1" value="アプリケーション1" onclick="setUrl('/aplXXX')" style="width:400px;height=150px;font-size:14pt;"/>
</td>
</tr>
<tr>
<td style="width:100%;text-align:center">
<html:submit property="btn2" value="新共通認証システム(ローカル環境用)テスト" onclick="setUrl('/authTest')" style="width:400px;height=150px;font-size:14pt;"/>
</td>
</tr>
</table>
</div>
<%-- ページ・フッダー --%>
<%# include file="/WEB-INF/jsp/footer.inc" %>
</html:form>
</body>
</html:html>
<% out.flush(); %>
When I used "request.getParameterNames()", I can only get the "apl500_p" parameter, I cannot get the "url" parameter. I used the tomcat7.0.41, but if I use the tomcat5.5.36,it's Ok.
I don't know why. Is there something wrong with tomcat7.0.41?
I used Fiddler2 and I'm sure that the "url" parameter was sent to the server.
Based on the discussion that you had, I suspect that the parameter url is NULL because the character encoding used by the browser is different from the character encoding used by the server.
Before the browser sends a parameter to the server, it URL-encodes the parameter. This encoding method encodes certain characters (e.g, Japanese characters) using percent encoding. Percent encoding method works by first converting the character into bytes, based on the specified character set. After that, it encodes these bytes into a sequence of hexadecimal digits, prefixed by "%" character. This character set is what I mean by character encoding used by the browser.
The server then decodes the retrieved parameter back into its original form. It does this by first decoding the sequence of hexadecimal digits into a sequence bytes. After that, it convert each bytes into a character, based on the specified character set. The problem here is that the server needs to use the same character set as the one used by the browser. It is often that the request does not carry information about the character set used by the browser, causing the server to make a best effort guess. If the guess is incorrect, the decoding process fails silently, and NULL is returned, which is what happened in your case.
Different web servers have different ways to make the guess. Web server may look at the Content-Type header, Content-Language header, Accept header, Accept Language header, configuration file, and so on.
As I am not familiar with both Tomcat versions, I am not able to pin point exactly how to fix the problem. But, you can start by studying how Tomcat figure out the character encoding. In WebSphere Application Server, there is a configuration file that can be modified to specify the default character encoding used by the server.
The parameter apl500_p is not NULL because the URL-encoded-form of 1 is also 1. The server does not have any problem decoding it back.
Try to remove the apl500_p=1 in the form action value
action="/select.do"
This way it will pass all your form elements to the servlet. Adding parameters to the form action prevents this. If you need your apl500_p value, I suggest you make another hidden field like:
<html:hidden property="apl500_p" value ="1" />

JSP Encoder Issue While sending Russian character in QueryString

I have two jsp pages. I am trying to add "Russian" language. Russian characters are shown perfectly on jsp page, but when I try to send this value to another jsp page from parameter then in second jsp page this value is changed to different characters. This problem is only in Russian Language and not in others such as Italy and French.
For example
On demo.jsp page the russian character "приветствие" is shown correctly.
but when I try to send it to another page "test.jsp" then some unknown
characters are shown like "!C<Cä5 Cô>CôCC´OD=Cä5!"
Code:
demo.jsp
String welcometext=langP.get("welcome");
<jsp:include page="<%=test.jsp%>">
<jsp:param name="wlc" value="<%=Encode.hex8Code(welcometext)%>" />
</jsp:include>
In test.jsp
String title = Encode.utfToUnicode(Decode.hex8Decode(request.getParameter("wlc")));
System.out.println(" Russial welcome test "+welcome);
Is there any special code we need to add for Russia while sending them in query parameters??
Please note* the following code are already written else it would have given problem for French and Italy language too..
<%# page contentType="text/html; charset=UTF-8" %>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
Also tried with following but didn't help out!
request.setCharacterEncoding("UTF-8")
Try to add <% request.setCharacterEncoding("UTF-8"); %> to your main jsp page:
Here is my example:
demo.jsp
<%#page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8"); %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Привет</h1>
<jsp:include page="/test.jsp" flush="true">
<jsp:param name="wlc" value="Привет"/>
</jsp:include>
</body>
</html>
test.jsp
<h1>Param values is</h1>
<%
String hello = request.getParameter("wlc");
out.print(hello);
%>
I don't know the better solution but the following code solved this issue. I kept the variable in session attribute.
demo.jsp
session.setAttribute("welcometext", welcometext);
test.jsp
String welcometest=(String) session.getAttribute("welcometext");

Including JSP file within another JSP file

I'm writing a wizard for creating a user in my application with Spring MVC. At each step the controller will set session attributes for the completed wizard fields.
I want the wizard to look the same regardless of which page it's on, except for each page's fields, obviously. For example, menus and links at the top of the page and buttons at the bottom should remain the same.
I have the following JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Create a new User</title>
</head>
<body>
<h1>User Creation Wizard</h1>
Step <c:out value = "${pageNum}"/>/<c:out value = "${pageMax}"/>
<form action="" method="POST">
<jsp:include page="userform${pageView}.jsp"/>
<input name = "currentPage" type = "hidden" value = "${pageNum}"/>
<c:if test = "${pageNum > 1}">
<input name = "prev" type = "submit" value = "Previous" />
</c:if>
<c:if test = "${pageNum < pageMax}">
<input name = "next" type = "submit" value = "Next" />
</c:if>
<c:if test = "${pageNum == pageMax}">
<input name = "submit" type = "submit" value = "Finish" />
</c:if>
</form>
</body>
</html>
In the jsp I'm including, do I need to remove the <html>, <head>, and <body> tags? The above code is based on this example.
Yes, you'd need to remove the <html>, <head> and <body> tags from the included JSP file. As they'd already be present in the including file keeping them would result in invalid HTML.
Only the content that you want to vary would be in the JSP file you're including. Everything else, including the necessary <html>, <head> and <body> tags, would be in the JSP file that does the including.

Categories