get browser Locale - java

I have a question about the browser Locale. In pricipal, the request.getLocale retrieve the locale from the user's OS. I would like to retrieve the browser Locale independent of user's OS.
The web site has multiable languages (german, italy, english), so that user can switch language manually.
In the html page, there are meta element which show the difference.
<meta http-equiv="content-language" content="de" />
"de" will be changed to en or other language due to user's click.
The question is whether there is a way to retieve this info in java servlet.
Update:
In my LogoutServlet doPost method, I have a logout method which should retrieve the current language from html page of browser.
String locale =request.getLocale().getDisplayLanguage();
It doesn't change to Fr or IT based on the content-language.

Here is answer that could solve one part of your question:
http://www.coderanch.com/t/442889/JSP/java/Reading-META-tag-Servlet
You need to collect the meta tag's data using clientside script and send them to your servlet:
<script type="text/javascript">
function metaKeywords() {
metaCollection = document.getElementsByTagName('meta');
alert('');
for (i=0;i<metaCollection.length;i++) {
var nameAttribute = metaCollection[i].name.search(/foo/);
if (nameAttribute!= -1) {
alert(metaCollection[i].content);
}
}
}
>
</script>

As far as I'm aware, browsers don't have a locale independent of the OS.
You're giving users a way to manually choose languages (great!). To know what language they've chosen, you'll need to do something to send that information back to your server. A cookie would probably be the simplest way, since it will accompany every request. (Keep it small, though, for that same reason.)

Related

Fetchinng JSON data from servlet to display on JSP [duplicate]

I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.

I want to use java variable in single jsp page

<%!
public void runJavaMethod(int id)
{
%>
<%
try{
String icd = request.getParameter("icd");
String inm = request.getParameter("inm");
String istk = request.getParameter("istock");
String sstk = request.getParameter("sstock");
String upr = request.getParameter("uprice");
String spr = request.getParameter("sprice");
r = s.executeQuery("select * from itemsyncdata");
while(r.next())
{
s.executeUpdate("update itemsyncdata set itemcode='"+icd+"',itemname='"+inm+"',instock='"+istk+"',storestock='"+sstk+"',unitprice='"+upr+"',storeprice='"+spr+"' where id='"+a+"'");
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<%!} %>
And I am Calling Function from html like
<input type="submit" id="btnSync" value="Sync" class="button" name="Sync" onclick="<%runJavaMethod(r.getInt(1));%>"/>
So We want runJavaMethod Parameter.
onclick="<%runJavaMethod(r.getInt(1));%>"/>
HTML/Javascript Plays on client side and JSP/Java plays on server side.
Simply you can't. You might misunderstand that JSP and HTML/JavaScript existed on same document. Yes but JSP part compiles on server side itself comes to client.
What you can do is you have to make a server request. Most probably look at Ajax requests.
You are trying to mix up two languages i.e., Java and Javascript/html together i.e., onclick is a Javascript event and you can't call runJavaMethod from Javascript.
In simple words, you can't directly call a Java method (present inside the scriptlet) using Javascript because all of your JSP code produces (becomes) html when it is loaded from the server.
So, if you have to fix the issue, upon onclick, you need to call an URL which hits a servlet/controller method on the server to do the job (i.e., executes the business logic).
One more important point is that Scriptlets are legacy code and I strongly suggest not use them to generate or manage the html content, rather use JSTL so that there will be a clear separation between the concerns (i.e., business logic and user interface requirements).
Also, I strongly suggest you read the JSP best practices from here and follow them.
You are mixing to two different things. JSP is server side code and it's rendered response is the HTML that is send back to the browser.Javascript is pure client side in your case.
If you really want invoke a server side processing than create a simple Java script function with Ajax call and get response back which u can use it.
I suggest send all the logic of JSP in backend class not a good practice to put in the jsp. JSP is ideally for UI design.

Reading in text from a text file using java / jquery without a webserver

I have used the jQuery.Get() as well as the $.Get() methods to do this but this does not seem to work.
<head>
<script type="text/javascript" src="jquery-2.1.3.min.js" > </script>
<script language="javascript">
function Read()
{
alert("start");
jQuery.get('/spec.txt', function(result)
{
alert("get");
if (result == 1)
{
alert("1");
$("body").html("<p>Specials</p>");
document.getElementById("specials").innerHTML = "<H1>Specials</H1>";
}
else if(result == 0)
{
alert("2");
$("body").html("<p>No Specials</p>");
document.getElementById("specials").innerHTML = "<H1>No Specials</H1>";
}
});
}
</script>
</head>
<body>
<button onclick="Read()">Specials</button>
<div id="specials">
</div>
</body>
</html>
I want to have a text file in my webroot folder that will only contain the values of 1 or 0. This will be used to determine if there are specials or not (this text file will be altered from another page). The value of this text file is to be read into the webpage and that will determine the course of action the if statements are programmed to. I have attached the code I am currently using to do this but I can't seem to get the $.get() / jQuery.get() to execute. You will notice I am using the alert() method to check the steps through the code but it does not execute the alert("get") immediately after the jQuery.get().
I am not using a webserver which I am assuming is the issue. I am simply running the index.html off my hard disk in the webroot folder. The IF statements are to fire depending on the value of read in from the text file named spec.txt
Please bare in mind I am new to web coding with jQuery and Java but I'm adept at simple HTML / CSS coding. This is my first attempt at dynamic web content like this instead of a static site. The site will eventually be hosted on a webserver if that helps with your answer.
You can't make ajax requests from file:// protocol. It's a security restriction.
Files loaded with file:// are always considered as coming from different domains, you can't bypass this feature.
But... If you are using chrome and just want to test it locally to put in a webserver later, you can disable this feature by running chrome in a unsafe mode
path/to/chrome.exe --disable-web-security
If you are using firefox. You can type in your URL about:config an then go to
security.fileuri.strict_origin_policy -> false
It's ok for local testing only. Don't expect the users of your application to disable that as well or you will be creating a big security problem. Be aware you are disabling all browser security and it will be open for malicious program
Just install a simple web server and have fun!

after GWT/js redirect, request.setAttribute does't work

In my site I have few languages to choice. I use a servlet, jsp to view, and GWT as a place where is localized button to action (treat it as js). In servlet I'm catching the subdomain which is the language like en, de, fr and so on (for instance en.mydomain.com will give string "en").
Because I use GWT I have to send parameter, to jsp with a current locale which I get from subdomain.
the jsp parameter code looks like bellow
<meta name="gwt:property" content="locale=<%=request.getAttribute( "locale1" )%>">
and servlet send attribiute:
request.setAttribute("locale1", locale);
But in my site (GWT layer) you can change the language just by pushing the button with flag. What happens there? I replacing the subdomain from one language to another.
After push I redirect the url to new one with new subdomain
Window.Location.assign(Window.Location.createUrlBuilder()
.setHost(newURL).buildString());
The url is correct after above action and then the action is walking into servlet where I get language from subdomain which is correct (the new one is fetched) and trying to setAttribute like above code.
But in jsp locale are not replaced. Just previous language still are there. No matter how many times I would perform the action the jsp will not replace the locale (mean en de fr ...)
The question: why it happens and how to fix it?
Rather than passing locale as request attribute for each redirect or new browser window try it using locale as query string or both in combination. It might solve this issue.
Add below script in each jsp page.
<script>
var search = location.search;
if (search.indexOf("locale") == -1) {
var lang = navigator.language != null ? navigator.language
: navigator.browserLanguage;
var lang = lang.replace("-", "_");
document.write("<meta name='gwt:property' content='locale="+lang +"'>");
}
</script>

call a java method when Click on a html button without using javascript

i work on JSP and i want to call a java method(Function) on Click on a html button without using<script></script>.how?
i try to write this code:
<button onclick="<%po.killThread();%>">
<font size="4">Kill</font>
</button>
but it doesn't work... so please help me.
thanks
You're misunderstanding how server-side programming works. When you load that page, the webserver will get to the line <button onclick="<%po.killThread();%>"> and will immediately parse and execute the JSP snippet, in your case po.killThread(), and replace everything between the <% and %> with the return value of that method, if any. And all these happens on server side, before client receives any thing. (Note that this will only happen if that page is not already been loaded and compiled into a Servlet by the server.)
Thus, the HTML that client receives, will be something like, <button onclick="some return value or nothing">, which means that nothing will happen when you press the button. If you want to execute further JSP commands on the button press you will need to make a new request to the server - for example, by redirecting the page.
This will call the function killThread when you open the website.
Try to redirect to another jsp which calls the function.
this will not run at all because after the jsp page is compiled it will return the po.killThread() value but will not call this method
You can see this by viewing the page source
JSP is a server-side technology. Did I say server-side?
In order to understand how JSP works and to clear any misconception, JavaRanch Journal (Vol. 4, No. 2): The Secret Life of JavaServer Pages is a very good read.
An excerpt from the same,
JSP is a templating technology best-suited to the delivery of dynamic text documents in a format that is white-space agnostic.
Template text within a JSP page (which is anything that is not a dynamic element), to include all white-space and line terminators, becomes part of the final document.
All dynamic elements in a JSP are interpreted on the server and once the document is sent to the client, no further dynamic interaction is possible (short of requesting the same or another document).
If you are using JSPs, then to perform some method calles, you will have to write a servlet and then call the method in doPost or doGet method of servlet.
On the other hand, if you want to make things simpler, use JSF framework which will help you achieve your objective as JSF supports event handling.

Categories

Resources