Passing integer values from servlet to jsp - java

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

Related

JSP - Separating HTML forms in JSP Functions

I have my JSP that controls the frame behavior of my page as the following:
<%
print_header();
String especialidade = request.getParameter("especialidade");
String medico = request.getParameter("medico");
String paciente = request.getParameter("paciente");
String data_consulta = request.getParameter("data_consulta");
String convenio = request.getParameter("convenio");
if (especialidade == null) {
print_especialidade_form();
} else if(paciente == null) {
print_agendamento_form();
}
print_footer();
%>
I have the definition of the functions defined in the same JSP, delimited by <%! and %> tags, but the creation of the form, that happens inside of those functions, get executed even if the function isn't called like print_footer(); for instance.
I 'm used to programming in ASP and I could easily do these there, but I'm having a hard time migrating to JSP. What am I doing wrong?

send values from javascript page to servlet page at run-time

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....

Retrieve map attribute from page to page JSP

i am trying to get retrieve attributes which are being put into a map. However i keep getting null when i try to debug it by putting it in an alert. Any help will be appreciated, thank you!
First jsp
<%
//Map newSurvey = new LinkedHashMap();
Map newSurvey = new HashMap();
newSurvey.put("description", request.getParameter("description"));
newSurvey.put("startDate", request.getParameter("start_datetime"));
newSurvey.put("endDate", request.getParameter("end_datetime"));
newSurvey.put("maxParticipant", request.getParameter("max_participant"));
newSurvey.put("minAge", request.getParameter("min_age"));
newSurvey.put("maxAge", request.getParameter("max_age"));
newSurvey.put("preSurveyText", request.getParameter("pre_survey_text"));
request.setAttribute("myMap", newSurvey);
%>
window.location = 'Survey_Questions.jsp';
Second jsp (to retrieve) i used a javascript to see if i am able to retrieve it
function testGet(){
<%
Map myMap = (Map)request.getParameter("myMap");
String description = (String) myMap.get("description");
%>
alert(<%=description%>
}
On first page you are using: request.setAttribute("myMap", newSurvey);.
So you must have to use request.getAttribute("myMap"); on second page.
window.location = 'Survey_Questions.jsp';
Will just redirect to a page and it will not pass your request object to other documents.
Instead you can use below lines of code:
RequestDispatcher rd = request.getRequestDispatcher("Survey_Questions.jsp");
rd.forward(request, response);
RequestDispatcher helps you to forward your request to other pages.
Also, use getAttribute instead of getParameter as you have used setAttribute to set myMap on First.jsp.

Displaying MySQL Query Results from Servlet to JSP

I am trying to store the results of my query in a string, and print them to the bottom of my JSP page by passing that string to it. Right now, the JSP page displays fine initially, but nothing is happening when I click the button to post the command. Earlier when I accessed the servlet from an html page, and printed all my output to out using a PrintWriter, I got the results to display, but they would display on a separate page.
1) Is it a good idea to store out in this way, or should I make it something different than a string?
2) How do I get the results of the query to post to the JSP page?
databaseServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
#SuppressWarnings("serial")
public class databaseServlet extends HttpServlet {
private Connection conn;
private Statement statement;
public void init(ServletConfig config) throws ServletException {
try {
Class.forName(config.getInitParameter("databaseDriver"));
conn = DriverManager.getConnection(
config.getInitParameter("databaseName"),
config.getInitParameter("username"),
config.getInitParameter("password"));
statement = conn.createStatement();
}
catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String out = "\n";
String query = request.getParameter("query");
if (query.toString().toLowerCase().contains("select")) {
//SELECT Queries
try {
ResultSet resultSet = statement.executeQuery(query.toString());
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
for(int i = 1; i<= numberOfColumns; i++){
out.concat(metaData.getColumnName(i));
}
out.concat("\n");
while (resultSet.next()){
for (int i = 1; i <= numberOfColumns; i++){
out.concat((String) resultSet.getObject(i));
}
out.concat("\n");
}
}
catch (Exception f) {
f.printStackTrace();
}
}
else if (query.toString().toLowerCase().contains("delete") || query.toLowerCase().contains("insert")) {
//DELETE and INSERT commands
try {
conn.prepareStatement(query.toString()).executeUpdate(query.toString());
out = "\t\t Database has been updated!";
}
catch (Exception l){
l.printStackTrace();
}
}
else {
//Not a valid response
out = "\t\t Not a valid command or query!";
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/dbServlet.jsp");
dispatcher.forward(request, response);
request.setAttribute("queryResults", out);
}
}
dbServlet.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- dbServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>MySQL Servlet</title>
<style type="text/css">
body{background-color: green;}
</style>
</head>
<body>
<h1>This is the MySQL Servlet</h1>
<form action = "/database/database" method = "post">
<p>
<label>Enter your query and click the button to invoke a MySQL Servlet
<textarea name = "query" cols="20" rows="5"></textarea>
<input type = "submit" value = "Run MySQL Servlet" />
<input type = "reset" value = "Clear Command" />
</label>
</p>
</form>
<hr>
<%=
request.getAttribute("queryResults");
%>
</body>
</html>
dispatcher.forward(request, response);
request.setAttribute("queryResults", out);
It should be like this
request.setAttribute("queryResults", out);
dispatcher.forward(request, response);
Before the request is dispatched the attributes has to be set
1) Is it a good idea to store out in this way, or should I make it something different than a string?
Since this is tabular data, I'd use something that preserves that structure, so that the JSP can piece it apart easily for customized formatting. Bold headers, putting it in an HTML table and stuff. Either some custom bean, or maybe just a List<String[]>.
2) How do I get the results of the query to post to the JSP page?
What you are doing now (request.setAttribute) should work. However, you need to set the attribute before you forward the request.
You could then print the String you now have like this:
<%= request.getAttribute("queryResults") %>
Or if you go with a table-structure
<% List<String[]> rows = request.getAttribute("queryResults"); %>
and then loop over that.
1) Is it a good idea to store out in this way, or should I make it something different than a string?
NO. Don't mix the presentation logic in Java code. Leaverage your JSP for that purpose I would advice you to use JAVA objects and store the row wise values in one object instance. Put all the objects in a collection and use the same in JSP for display. Same goes with column names.
2) How do I get the results of the query to post to the JSP page?
In your current format of queryResults, just print the results using = operator or out.println method in your JSP as:
<hr>
<%=request.getAttribute("queryResults"); %>
or
<% out.println(request.getAttribute("queryResults"));%>
But if you decide t use collection as adviced in answer1, then get the collection back from the request, iterate and print the results, e.g. if you decide to use List<String[]> where String[] maps one row data then:
<TABLE id="results">
<% List<String> columns = (List<String>)request.getAttribute("queryColumns");
List<String[]> results = (List<String[]>)request.getAttribute("queryResults");
out.println("<TR>");
for(String columnName: columns ){
out.println("<TD>"+columnName+"</TD>");
}
out.println("</TR>");
//print data
for(String[] rowData: results){
out.println("<TR>");
for(String data: rowData){
out.println("<TD>"+data+"</TD>");
}
out.println("</TR>");
}
%>
</TABLE>

How to prevent client from accessing JSP page

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

Categories