Determining Base URL using JSP - java

In the browser (IE and Firefox) if you have a relative link and your URL is: http://domain/somepath/lastfolder/
the relative link becomes:
http://domain/somepath/lastfolder/linkdocname.html
if the URL is http://domain/somepath/lastdoc the relative link becomes:
http://domain/somepath/linkdocname.html
http://domain/somepath/lastfolder/ becomes:
http://domain/somepath/lastfolder/linkdocname.html
Is there a way to replicate this using JSP without writing a special function?
I tried to get the base URL using:
baseURL = request.getScheme() + "://" + request.getServerName() + ":"
+ request.getServerPort()+ request.getRequestURI();
but that gets me the whole path of the requst URI and doesn't drop off the last bit if it doesn't end in a "/" Then if I try:
baseURL = request.getScheme() + "://" + request.getServerName() + ":"
+ request.getServerPort() + request.getContextPath();
that gives me everything up to the web container folder but not any of the folders after that.

In your last string building attempt you are missing a port number, even though you specified ":"
Try this:
new URL(request.getScheme(), request.getServerName(),
request.getServerPort(), request.getContextPath());
You can also build the string yourself and remove default ports if needed:
public String getBaseUrl(HttpServletRequest request) {
if (( request.getServerPort() == 80 ) || ( request.getServerPort() == 443 )) {
return request.getScheme() + "://" + request.getServerName() +
request.getContextPath();
} else {
return request.getScheme() + "://" + request.getServerName() + ":" +
request.getServerPort() + request.getContextPath();
}
}

Related

How can I solve two errors adding "?useUnicode"?

I am connecting to a MySQL database but I got an error about timezone. So I solved it by adding useLegacyDatetimeCode=false&serverTimezone=UTC:
String url = "jdbc:mysql://" + host + ":" + port + "/" + db_isim +
"?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
Now I need to add this too: ?useUnicode=true&characterEncoding=utf8
Is there a way for this?
(Not very good at English so basic explanation or just the code will be good)
I need to add this code for Turkish characters. I tried adding next to it but the connection went lost.
You can type the code in the following format and if you encounter a problem in the connection make sure the variables used within the code or make sure to add jdbc library
String url = "jdbc:mysql://" + host + ":" + port + "/" + db_isim + "?useUnicode=true&useJDBCCompliantTimezoneShift=true&characterEncoding=utf8&useLegacyDatetimeCode=false&serverTimezone=UTC";
Have you tried :
String url = "jdbc:mysql://" + host + ":" + port + "/" + db_isim
+ "?useUnicode=true&"
+ "useJDBCCompliantTimezoneShift=true&"
+ "useLegacyDatetimeCode=false&"
+ "serverTimezone=UTC&"
+ "characterEncoding=utf8";

How make getRequestURI and queryString in jsp

I am using this:
<li ${(requestScope['javax.servlet.forward.request_uri']=='/example') ? "class='active';" : ""}>
And this code activates my link to me but I've written such code to be active: ${(requestScope['javax.servlet.forward.request_uri'] +="?"+ requestScope['javax.servlet.forward.query_string']=='/example/?buy=e') ? "class='active';" : ""}
But I am getting an error.
Can I get your solution suggestions?
Try this below.
String uri = request.getScheme() + "://" +
request.getServerName() +
("http".equals(request.getScheme()) && request.getServerPort() == 80 || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? "" : ":" + request.getServerPort() ) +
request.getRequestURI() +
(request.getQueryString() != null ? "?" + request.getQueryString() : "");
Note:
This snippet above will get the full URI, hiding the port if the default one was used, and not adding the "?" and the query string if the latter was not provided.

Using JSON data as a String object in Java

I am using HTTP Client to send different kinds of requests (GET, PUT, POST, DELETE) where I am sending the JSON as a data to post with different requests.
I have a JSON data like:
{ "createdByID": "100000", "createdByName": "Admin", "modifiedByID": "100000", "modifiedByName": "Admin" }
Now, to store this JSON into a string, I have to add double quotes wherever necessary so that this can be stored as
String jsonData = "{" + "\"" + "createdByID" + "\"" + ":" + "\"" + "100000" + "\"" + "," + "\"" + "createdByName" + "\"" + ":" + "\"" + "Admin" + "\"" + "," + "\"" + "modifiedByID" + "\"" + ":" + "\"" + "100000" + "\"" + "," + "\"" + "modifiedByName" + "\"" + ":" + "\"" + "Admin" + "\"" + "}"
Does anyone use any tool/utility to convert the JSON data such that it can be stored in a string object?
Please share if anyone has already done this
Hey if you store the json as a sting in your code then only you need to add double codes.
Try to read json from a text file , then you don't need to add double quotes and other stuffs.
More over java does not consider double quotes after compiling your code.

POST data to other URI with URL change in REST (POST and Redirect)

I need to POST data and at the same time redirect to that URL in REST environment. I can do this for normal strings, but the requirement is to POST specific Object.
The way I do it for normal string is -
public Response homePage(#FormParam("username") String username,
#FormParam("passwordhash") String password) {
return Response.ok(PreparePOSTForm(username)).build();
}
private static String PreparePOSTForm(String username)
{
//Set a name for the form
String formID = "PostForm";
String url = "home";
//Build the form using the specified data to be posted.
StringBuilder strForm = new StringBuilder();
strForm.append("<form id=\"" + formID + "\" name=\"" +
formID + "\" action=\"" + url +
"\" method=\"POST\">");
strForm.append("<input type=\"hidden\" name=\"" + "username" +
"\" value=\"" + username + "\">");
strForm.append("</form>");
//Build the JavaScript which will do the Posting operation.
StringBuilder strScript = new StringBuilder();
strScript.append("<script language=\"javascript\">");
strScript.append("var v" + formID + " = document." +
formID + ";");
strScript.append("v" + formID + ".submit();");
strScript.append("</script>");
//Return the form and the script concatenated.
//(The order is important, Form then JavaScript)
return strForm.toString() + strScript.toString();
}
But this method is not sending Objects. I need a work around to send complex Objects. Please help me with this issue.
Thanks in advance.

Create HTML in java with background image

I have created an html string in which I need to set the background image.
protected void onPostExecute(HashMap<String,String> hPlaceDetails){
String backgroundImage = ??????
String name = hPlaceDetails.get("name");
String icon = hPlaceDetails.get("icon");
String vicinity = hPlaceDetails.get("vicinity");
String lat = hPlaceDetails.get("lat");
String lng = hPlaceDetails.get("lng");
String formatted_address = hPlaceDetails.get("formatted_address");
String formatted_phone = hPlaceDetails.get("formatted_phone");
String website = hPlaceDetails.get("website");
String rating = hPlaceDetails.get("rating");
String international_phone_number = hPlaceDetails.get("international_phone_number");
String url = hPlaceDetails.get("url");
String mimeType = "text/html";
String encoding = "utf-8";
String data = "<html>"+
"<body background="+backgroundImage+"><img style='float:left' src="+icon+" /><h1><center>"+name+"</center></h1>" +
"<br style='clear:both' />" +
"<hr />"+
"<p>Vicinity : " + vicinity + "</p>" +
"<p>Location : " + lat + "," + lng + "</p>" +
"<p>Address : " + formatted_address + "</p>" +
"<p>Phone : " + formatted_phone + "</p>" +
"<p>Website : " + website + "</p>" +
"<p>Rating : " + rating + "</p>" +
"<p>International Phone : " + international_phone_number + "</p>" +
"<p>URL : <a href='" + url + "'>" + url + "</p>" +
"</body></html>";
// Setting the data in WebView
mWvPlaceDetails.loadDataWithBaseURL("", data, mimeType, encoding, "");
}
Note: I have my background image (background9.png) in the location MyProject/res/drawable-xhdpi. Please suggest how I need to set
<body background="+backgroundImage+">
Instead of using \res\drawable-xhdp\background9.png as the path as you mentioned in your comment, you should use:
<body background='file:///android_res/drawable/background9.png'>
I've just tested this and it works perfectly.
Please add a tag for android to clarify your question.
Anyway, you need to get a reference for your parent layout, by using findViewById(R.id.yourActivitysParentLayout)
You need then to set it's background using a ResourceManager. From the top of my head, the method name you will need is yourparent.setBackgroungDrawable(drawable). The drawable can be obtained from a resource manager instance.
This can all be avoided by setting it's background in the xml if possible by using android:background="#drawable/background9" //sorry not sure if .png is needed. xhdp is not though.

Categories