I store my HTML pages in the database, and I use PrintWriter out = response.getWriter (); to show them. I would like to do the same with my JSP pages it is possible to do this using JspWriter
Example: I have this page in my database, I load this page and would like the code to be processed dynamically (inside servlet).
<%# page import = "java.io.*,java.util.*" %>
<html>
<head>
</head>
<body>
<center>
<%
// Get current time
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if (calendar.get(Calendar.AM_PM) == 0) {
am_pm = "AM";
} else {
am_pm = "PM";
}
String CT = hour + ":" + minute + ":" + second + " " + am_pm;
out.println("Current Time is: " + CT + "\n");
%>
</center>
</body>
</html>
No, it is not possible. The servlet writes HTML (in this case) to the response, and your standard client (web browsers) will understand that.
A JSP, however, is a dynamic page and contains code that the container has to compile and run in order to produce the output for the HTTP response. Writing the content of the JSP to the response would (roughly speaking) send Java code to the client.
If you need dynamic content at that level, perhaps you should look into a custom tag library. Documentation can be found here
Related
I am using Paytm for payment gateway integration, and I am using the sample kit which is an example of the JSP implementation.
What I am doing is putting this code inside my servlet method as follows:
int appointmentId = rst_appnt.getInt(1);//unique id
TreeMap< String, String> parameters = new TreeMap<String, String>();
parameters.put("ORDER_ID", String.valueOf(appointmentId));
parameters.put("CUST_ID", "CUST001");
parameters.put("INDUSTRY_TYPE_ID", "Retail");
parameters.put("CHANNEL_ID", "WEB");
//parameters.put("TXN_AMOUNT", String.valueOf(rst_appnt.getDouble(3)));
parameters.put("TXN_AMOUNT", "10");
parameters.put("MID", "WorldP64425807474247");
parameters.put("CHANNEL_ID", "WEB");
parameters.put("INDUSTRY_TYPE_ID", "Retail");
parameters.put("WEBSITE", "worldpressplg");
parameters.put("MOBILE_NO", "9876543210");
parameters.put("EMAIL", "test#gmail.com");
parameters.put("CALLBACK_URL", "http://localhost:8080/Test/pgResponse.jsp");
String checkSum = CheckSumServiceHelper.getCheckSumServiceHelper().genrateCheckSum(PaytmConstants.MERCHANT_KEY, parameters);
StringBuilder outputHtml = new StringBuilder();
outputHtml.append("<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>");
outputHtml.append("<html>");
outputHtml.append("<head>");
outputHtml.append("<title>Merchant Check Out Page</title>");
outputHtml.append("</head>");
outputHtml.append("<body>");
outputHtml.append("<center><h1>Please do not refresh this page...</h1></center>");
outputHtml.append("<form method='post' action='https://pguat.paytm.com/oltp-web/processTransaction' name='f1'>");
outputHtml.append("<table border='1'>");
outputHtml.append("<tbody>");
for (Map.Entry<String, String> entry : parameters.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
outputHtml.append("<input type='hidden' name='" + key + "' value='" + value + "'>");
}
outputHtml.append("<input type='hidden' name='CHECKSUMHASH' value='" + checkSum + "'>");
outputHtml.append("</tbody>");
outputHtml.append("</table>");
outputHtml.append("<script type='text/javascript'>");
outputHtml.append("document.f1.submit();");
outputHtml.append("</script>");
outputHtml.append("</form>");
out.print(outputHtml);
Here it is submitting using form submission in JavaScript as seen in the below code:
outputHtml.append("<script type='text/javascript'>");
outputHtml.append("document.f1.submit();");
outputHtml.append("</script>");
But it seems to be not executing the script sometimes inside the servlet.
So I referred to the Paytm Java example.
But, unfortunately, it does not have any code to call service to Paytm.
Am I doing correct by using JavaScript inside the servlet, or should I use Java API instead of the sample JSP kit?
you just add this syntax but not trigger.
so trigger it on document on load.
outputHtml.append("<script type='text/javascript'>");
outputHtml.append("document.onload=document.f1.submit();");
outputHtml.append("</script>");
or you can submit on body load.
<body onload="document.form.submit()">
My_javascript_page
window.onload = loadResTimeData;
function loadResTimData() {
var e = window.performance.getEntriesByType("resource");
if (window.console) {
console.log("Resource Timming");
var perf_data = "";
var name, load, connection, request, fetch;
for (var i in e) {
if (e[i].name == "document") {
continue;
}
name = e[i].name.replace(/^.*\/|\.$/g, '') + ":";
load = e[i].duration;
request = e[i].responseEnd - e[i].requestStart;
fetch = e[i].responseEnd - e[i].fetchStart;
var s1={"Name": name, "CONNECTION":connection, "REQUEST":request, "LOAD":load, "FETCH":fetch};
var String1=JSON.stringify(s1);
console.log("Resource:" + name);
console.log("User Time:" + load);
console.log("Connection:" + connection);
console.log("Request Time:" + request);
console.log("Fetch Time:" + fetch);
$.ajax({
type:"POST",
url:"Final", //Final is my servlet page
data:String1,
datatype: "json"
});
}
}
}
}
This code calculates different response times when a web page is loaded and sends the data back to the servlet page.
This data i am printing on console(Console.log values), I want to send it to my servlet page in json format.
I tried doing it using jquery ajax, but the value didnot get passed to my servlet page.
Now I came accross various links where many people gave example on how to do it. But problem is
that all examples will be trigerred by clicking on the button. For that i need a form or may be some other thing
But in my application I want the data to be passed to my servlet page once the window.onload function is
trigerred; where I dont need a form or textfield. Also please let me know what exactly do i need to call at my server end(request.getparameter(???))
I am sharing the links i referred.
http://www.mysamplecode.com/2012/04/jquery-ajax-request-response-java.html
http://www.javacodegeeks.com/2014/09/jquery-ajax-servlets-integration-building-a-complete-application.html
JSP_page
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>JSP Page</title>
</head>
<body>
<script language='JavaScript'>
onclick=' window.onload';
Also I had people telling me to use cookies. I created cookies but my servlet page was not able to read it.
Someone suggested I can use hidden fields as well.
You can understand I am a mess right now. Please help as to where am I going wrong or what do i need to do now....
I am getting values from user using a html file which is then used by the servlet to perform certain calculations.And when i execute my web application in the browser it takes values from user but when i click the submit button after getting values,this error is thrown.
"HTTP ERROR 500
Problem accessing /servlet/MvcServlet. Reason:
java.lang.Integer cannot be cast to java.lang.String"
My servlet code is like this:
int gpa=total/c;
req.setAttribute("gpa",gpa);
RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
view.forward(req, resp); `
and my jsp code is:
String gpa = (String) request.getAttribute("gpa");
int r=Integer.parseInt(gpa);
out.println("Your Result is "+ r);
Please help me out for passing my integer value "gpa" in servlet to jsp.
int gpa = (Integer) request.getAttribute("gpa");
The obvious answer would be to obtain the data as Integer and let Java autounbox it to an int. This is notable by this piece of code:
int gpa = (Integer) request.getAttribute("gpa");
But you **should avoid having scriptlets (Java code) directly in your code. So the best bet would be using Expression Language directly in your JSP code:
<!DOCTYPE html>
<html lang="es">
<head>
<!-- head content here -->
</head>
<body>
<!-- other content in your JSP file -->
Your result is: ${gpa}
<!-- There's no need of senseless scriptlet code -->
</body>
</html>
when you send the int value to the jsp you can try this
int gpa = total/c;
String test = ""+gpa;
req.setAttribute("test",test);
RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
view.forward(req, resp);
And then in the jsp you dont have to parse it . Just directly go -
String gpa = (String) request.getAttribute("test");
out.println("Your Result is "+ gpa);
Try this :D
I am attempting to write an example JSP page for myself (very new to jsp), and have gone over an example to write one, but how do I get time to consistently update?
here is my snippet of code:
<body>
<%
java.text.DateFormat df = new java.text.SimpleDateFormat(
"HH:mm:ss:SS z MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
%>
<h1>
Current Date and Time:
<%=df.format(cal.getTime())%>
</h1>
</body>
By the way i'm using a tomcat server to deploy this
function updateYourTime() {
var now = new Date(),
months = ['January', 'February', '...'];
time = now.getHours() + ':' + now.getMinutes(),
date = [now.getDate(),
months[now.getMonth()],
now.getFullYear()].join(' ');
document.getElementById('currentTime').innerHTML = [date, time].join(' / ');
setTimeout(updateYourTime, 1000);//This method will call for every second
}
updateYourTime(); // initial call
see here for details
<div id="currentTime"></time>
do you mean to show clock in your pages?
you can use java script.
here is an example
to show server clock in clients jsp use this javascripcode with java
Add a label where ever you want to show the server Time
<strong>Server Time : </strong><label id="timelable"></label>
And then add the following java script code at the end of the jsp inside the body tag
<script type="text/javascript">
var myVar = setInterval(function(){ myTimer() }, 1000);
var jsVar= <%=java.util.Calendar.getInstance().getTimeInMillis()%>;
var timeZoneOffset=<%=java.util.TimeZone.getDefault().getOffset(System.currentTimeMillis())%>;
jsVar=jsVar+timeZoneOffset;
function myTimer() {
jsVar=jsVar+1000;
var d = new Date(jsVar);
var t=d.toUTCString();
document.getElementById("timelable").innerHTML = t;
}
</script>
Thats it now you will see the server time running in you jsp.
In my web application, I use the .load() function in JQuery, to load some JSP pages inside a DIV.
$("#myDiv").load("chat.jsp");
In chat.jsp, no Java codes is executed unless this client has Logged in, means, I check the session.
String sessionId = session.getAttribute("SessionId");
if(sessionId.equals("100")){
//execute codes
}else{
//redirect to log in page
}
Those java codes that will be executed, they will out.println(); some HTML elements.
I don't want the client to write /chat.jsp in the browser to access this page, as it will look bad, and the other stuff in the main page won't be there, and this could do a harm to the web app security.
How can I restrict someone from accessing chat.jsp directly, but yet keep it accessible via .load() ?
UPDATE:
JavaDB is a class that I made, it connects me to the Database.
This is chat.jsp
<body>
<%
String userId = session.getAttribute("SessionId").toString();
if (userId != null) {
String roomId = request.getParameter("roomId");
String lastMessageId = request.getParameter("lastMessageId");
JavaDB myJavaDB = new JavaDB();
myJavaDB.Connect("Chat", "chat", "chat");
Connection conn = myJavaDB.getMyConnection();
Statement stmt = conn.createStatement();
String lastId = "";
int fi = 0;
ResultSet rset = stmt.executeQuery("select message,message_id,first_name,last_name from users u,messages m where u.user_id=m.user_id and m.message_id>" + lastMessageId + " and room_id=" + roomId + " order by m.message_id asc");
while (rset.next()) {
fi = 1;
lastId = rset.getString(2);
%>
<div class="message">
<div class="messageSender">
<%=rset.getString(3) + " " + rset.getString(4)%>
</div>
<div class="messageContents">
<%=rset.getString(1)%>
</div>
</div>
<% }
%>
<div class="lastId">
<% if (fi == 1) {%>
<%=lastId%>
<% } else {%>
<%=lastMessageId%>
<% }%></div>
<% if (fi == 1) {%>
<div class="messages">
</div>
<% }
} else {
response.sendRedirect("index.jsp");
}%>
</body>
Guys I don't know what Filter means.
UPDATE
If I decided to send a parameter that tells me that this request came from Jquery.
.load("chat.jsp", { jquery : "yes" });
And then check it in chat.jsp
String yesOrNo = request.getParameter("jquery");
Then they can simply hack this by using this URL.
/chat.jsp?jquery=yes
or something like that..
UPDATE
I tried Maksim's advice, I got this when I tried to access chat.jsp.
Is this the desired effect?
In order to achieve this in my application I check for X-Requested-With field in http header the client sends to my page in its request. If its value is XMLHttpRequest, then it's very likely that it came from an ajax request (jQuery appends this header to its requests), otherwise I don't serve the page. Regular (direct) browser requests will leave this header field blank.
In ASP.Net it looks like this, you will have to change your code slightly for JSP:
if (Request.Headers["X-Requested-With"] != "XMLHttpRequest")
{
Response.Write("AJAX Request only.");
Response.End();
return;
}
UPD: After quick googling your code will probably be something like this
if(!request.getHeader("X-Requested-With").equals("XMLHttpRequest")){
out.println("AJAX Request only.");
out.flush();
out.close();
return;
}
UPD2: Looks like request.getHeader("X-Requested-With") returns null in your case change the condition to something like this:
String ajaxRequest = request.getHeader("X-Requested-With");
if(ajaxRequest == null || !ajaxRequest.equals("XMLHttpRequest")){
...
}
Is your code snippet a servlet? If that's so, use a security framework (such as Spring Security) or a javax.servlet.Filter for applying security, then you can apply security to JSPs too.
you should use Filter. Check session in filter code and redirect to login.
according to http://www.c-sharpcorner.com/blogs/2918/how-to-set-a-request-header-in-a-jquery-ajax-call.aspx
JQuery gives you the tools you need to create a request and retrieve a response through it's ajax library. The raw $.ajax call gives you all kinds of callbacks to manipulate http messages.
So you can add a custom request header in your Ajaxa call like this
$.ajax({
type:"POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", "AJAXREQUEST");
},
...........
And then in your servlet check to see if the request has the header Authority equals to AJAXREQUEST. This is how you read request headers http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Request-Headers.html