Please have a look at the below code
<%--
Document : index
Created on : Feb 7, 2014, 1:03:15 PM
--%>
<%#page import="java.util.Map"%>
<%#page import="java.util.Iterator"%>
<%#page import="analyzer.DataHolder"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.List"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1><center>Web Site Analizer</center></h1>
<br/>
<form action=http://localhost:8080/WebSiteAnalizer/SiteAnalizer method=post>
Enter the Percentage (0-100): <input type="Text" name="percentage">
<br/><br/><br/>
Enter the Words (Separated from New Line (/n)): <br/>
<textarea name='wordList' value='wordList'></textarea>
<br/><br/>
<input type="submit" value="Submit">
</form>
<%#page import="java.util.List" %>
<%#page import="java.util.ArrayList" %>
<%#page import="java.util.HashMap" %>
<%
List<DataHolder> dataHolder = (ArrayList)request.getAttribute("list");
HashMap hashMap = (HashMap)request.getAttribute("wordMap");
if(hashMap==null)
{
out.println("Hashmap null");
}
if(dataHolder!=null && dataHolder.size()>0)
{
out.println("</br>");
out.println("<table border='1'><th>Primary Key</th><th>Original Hash</th><th>Matching Words</th><th>Non Matching words</th>");
for(int i=0;i<dataHolder.size();i++)
{
DataHolder d = dataHolder.get(i);
int primaryKey = d.getPrimaryKey();
String originalHash = d.getOriginalHash();
ArrayList matchingWords = d.getMatchingWords();
ArrayList unMatchingWords = d.getUnmatchingWords();
StringBuffer matchingWordsStr = new StringBuffer("");
StringBuffer unMatchingWordsStr = new StringBuffer("");
//Populating Strings
for(int m=0;m<matchingWords.size();m++)
{
Iterator iter = hashMap.entrySet().iterator();
while(iter.hasNext())
{
Map.Entry mEntry = (Map.Entry)iter.next();
if(mEntry.getValue().equals(matchingWords.get(m)))
{
//out.println(matchingWords.get(m)+" : "+true);
matchingWordsStr.append(mEntry.getKey());
matchingWordsStr.append(",");
}
}
}
for(int u=0;u<unMatchingWords.size();u++)
{
Iterator iter = hashMap.entrySet().iterator();
while(iter.hasNext())
{
Map.Entry mEntry = (Map.Entry)iter.next();
if(mEntry.getValue().equals(unMatchingWords.get(u)))
{
//out.println(matchingWords.get(m)+" : "+true);
unMatchingWordsStr.append(mEntry.getKey());
unMatchingWordsStr.append(",");
}
}
}
out.println("<tr>");
out.println("<td>");
out.println(String.valueOf(primaryKey));
out.println("</td>");
out.println("<td>");
out.println(originalHash);
out.println("</td>");
out.println("<td>");
out.println(matchingWordsStr);
out.println("</td>");
out.println("<td>");
out.println(unMatchingWordsStr);
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");
}
%>
</body>
</html>
This code generates a table, but it is really huge, which means the width is too much to fit to the screen. The reason for that is, the String values this code enters into the columns are very lengthy. May be 5000 to 10000 words and everything in one column is being displayed in one line. For an example, if "Original Hash" is 10000 characters, then the entire thing is displayed in one line. So is there anyway that I can make the length of this make suit for the screen?
Also please note that I am a developer and not a designer. I very rarely work on scripting languages.
use this css to break the really long word-
td{
word-wrap:break-word;
}
You may need to also set the table-layout to fixed see Set the table column width constant regardless of the amount of text in its cells?. Also for performance you probably want to change it from individual printlns to single a println that takes a string of all your html.
Related
So I have this simple list made in a java servlet, and I would like to display it within a JSP page. Servlet code:
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
ArrayList<String> myList = new ArrayList<String>();
myList.add("cat");
myList.add("dog");
myList.add("frog");
request.setAttribute("list", myList);
String nextJSP = "/index.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
}
}
However it won't print in the following JSP file:
<%#page import="java.io.*" %>
<%#page import="java.net.*" %>
<%#page import="java.util.*" %>
<%#page import="java.util.List" %>
<%#page import="java.util.ArrayList" %>
<%#page language="java" import="myPackage.*" %>
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<% List<String> myList = (ArrayList<String>)
request.getAttribute("list"); %>
<% out.println(myList); %>
</body>
</html>
Any help would be appreciated!
The HTTP 500 error is come from this line:
<% List<String> myList = (ArrayList<String>)
request.getAttribute("list"); %>
It has extra (),remove it and make it as below,then the HTTP 500 will diappear,instead you will got a warning Type safety:Unchecked cast from Object to ArrayList<String>,but it doesn't matter
For how to print the ArrayList,if you have import JSTL tag in your jsp page,you can do it as below,previous answer has metioned:
<c:forEach var="li" items="${list}">
<c:out value="${li}"/>
</c:forEach>
If you do not want to use JSTL, you can use java code to print it:
<% for(int i=0;i<myList.size();i++){
out.println(myList.get(i));
} %>
Okay, your are having a HTTP 500 error message and I would suspect that it is coming from the following part of your code:
<% out.println(myList); %>
Keep in mind that the out used here is not System.out and does not behave the same way. Instead try (replace the line mentionned above by the following):
<% Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
out.println(<iterator.next());
}
%>
You could use core tag foreach as
<c:forEach var="list" items="${YourList}">
<c:out value="${list}"/>
</c:forEach>
How can I get the average salary of all employees in the selected company?
I first select the company and then pass the id and based on that id, i get all employees in there and display their info in a table. The goal is to get the average salary of everyone in this group.
<%#page import="data.Employee"%>
<%#page import="data.Company"%>
<%#page import="java.util.List"%>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="company" type="data.Company" scope="request"/>
<% List<Employee> employees = company.getEmployees();
double sum=0.0;
%>
<table border="1">
<tr>
<td>ID</td>
<td>Name</td>
<td>Salary</td>
</tr>
<%
for(int i=0; i <employees.size(); i++){
sum += employees.get(i).getSalary();
%>
<tr>
<td><%=employees.get(i).getId()%></td>
<td><%=employees.get(i).getNom()%></td>
<td><%=employees.get(i).getSalary()%></td>
</tr>
<% } %>
</table>
//get the average salary of all employees ::: This is working based on JChris's answer
<p>Average salary of all employees in this company:<%=sum/(double)employees.size()%> </p>
//this is returning zero.
<p> New average method: <%=company.getAverageSalary()%></p>
You could sum the salaries up and then divide by the number of employees:
<% List<Employee> employees = company.getEmployees();
double sum=0.0;
%>
<table border="1">
<tr>
<td>ID</td>
<td>Name</td>
<td>Salary</td>
</tr>
<%
for(int i=0; i <employees.size(); i++){
sum += employees.get(i).getSalary();
%>
<tr>
<td><%=employees.get(i).getId()%></td>
<td><%=employees.get(i).getNom()%></td>
<td><%=employees.get(i).getSalary()%></td>
</tr>
<% } %>
</table>
//get the average salary of all employees
<p>Average salary of all employees in this company:<%=sum/(double)employees.size()%> </p>
Having said that, I urge you to reconsider before going down that road. Having code inside your JSP will severely hinder your chances of maintaining it if it gets any bigger than 1-2 pages.
All your business logic should happen in your code (e.g. inside your servlets) and in JSPs only display the information.
I want to export data to Excel sheet
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#include file="connection.jsp" %>
<!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>Insert title here</title>
</head>
<body>
<%
String ht = (String)session.getAttribute("ht");
%>
<table border="1">
<%
pst = con.prepareStatement("select * from attendance where ht='"+ht+"'");
res = pst.executeQuery();
if(res.next())
{
String uname = res.getString(2);
%>
<b>Student Name:<%=uname%></b>
<%
String hlt = res.getString(1);
%>
<b>Hallticket:<%=hlt%></b>
<tr><th>CG</th><th>CD</th><th>MPI</th><th>HCI</th><th>WT</th><th>MPI-Lab</th><th>CT=Lab</th><th>WT-Lab</th></tr>
<%
String cg = res.getString(3);
String cd = res.getString(4);
String mpi = res.getString(5);
String hci = res.getString(6);
String wt = res.getString(7);
String mpi_lab = res.getString(8);
String ct_lab = res.getString(9);
String wt_lab = res.getString(10);
%>
<tr>
<td align="center"><%=cg%></td>
<td align="center"><%=cd%></td>
<td align="center"><%=mpi%></td>
<td align="center"><%=hci%></td>
<td align="center"><%=wt%></td>
<td align="center"><%=mpi_lab%></td>
<td align="center"><%=ct_lab%></td>
<td align="center"><%=wt_lab%></td>
</tr>
<br/><br/>
<%
}
%>
</table>
</body>
</html>
I want the data that is retrieved from database and displayed in table should be printed on excel sheet
Please can any one tell me how to do it ... :(
I used mysql databse.
Try using a servlet to do the Excel writing.
You could use it as a JSP:Include in your existing page if you wanted
to.
From the servlet you'll have to do something like this:
ServletOutputStream out = resp.getOutputStream();
resp.setContentType("application/vnd.ms-excel")
/*
* get data
*/
if (data != null) {
for (int i=0; i data.length; i++) {
String dataRow = "";
for (int j = 0; j data[0].length; j++) {
dataRow += data[i][j] + "\t";// add tab delimiter
}
out.println(dataRow);// print data
}
} else {//Bad data...
out.println("No data to report.");
}
out.flush();
Hope it helps you. :)
You must add following lines to your jsp page which you want to export to excel:
response.setContentType("application/xls");
response.setHeader("Content-Disposition", "attachment;filename=File.xls");
Or you must learn about POI
And you must change if(res.next()) with while(res.next())
I have to create an HTML table in which I will have images to display. further I want to pass this path to the next servlet page. for this I have created a separate method in javascript. Now the problem is this, whenever I click on any image it passes the same path everytime. please give me any solutions for this problem or tell me any alternate of passing the path to next page.
my code is--->
<%#page import = "java.util.*" %>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<link href="Style.css" rel="stylesheet" type="text/css"/>
<title>Home</title>
</head>
<body>
<center>
<h3>${requestScope.payment}</h3>
<jsp:include page="Header.jsp"/>
<jsp:include page="Menu2.jsp"></jsp:include>
<form method="post" action="ProductFeatures" id="myform">
<table border="1" bordercolor="green" bgcolor="yellow" align="center" id="store" >
</table>
</form>
<%
ArrayList<String> l = null;
if(request.getAttribute("list") instanceof ArrayList<?>){
l = (ArrayList<String>)request.getAttribute("list");
}
%>
<script type="text/javascript">
window.onload = function(){
var path = new Array();
var imagepath = new Array();
var table = document.getElementById("store");
var j=0;
var k=0;
var row = null;
<%for(int i=0;i<l.size();i++) {%>
path.push("<%=l.get(i)%>");
<%}%>
for(i=0;i<path.length;i++){
imagepath[i] =path[i].replace ("F:java_projectsApplication4images","F:\\java_projects\\Application4\\images\\");
}
for(i=0;i<path.length;i++){
if(i%4==0){
row = table.insertRow(j);
k=0;
j++;
}
var data = imagepath[i];
var cell = row.insertCell(k);
var image = document.createElement("img");
image.setAttribute("src",imagepath[i]);
image.setAttribute("height","160");
image.setAttribute("width","120");
image.setAttribute("onclick",function(){getDetails(data);});
cell.appendChild(image);
row.appendChild(cell);
k++;
}
};
function getDetails(imagepath){
document.write(imagepath);
if(path.length>10){
var form = document.getElementById("myform");
var input = document.createElement("input");
input.type="hidden";
input.value=imagepath;
input.name="imagepath";
form.appendChild(input);
form.submit();
}
}
</script>
<jsp:include page="Footer.jsp"/>
</center>
</body>
</html>
Here in this code in function getDetails variable imagepath always contains the same value. please somebody tell me wheres the bug in this code. I am not getting it properly.
Change the following line:
image.setAttribute("onclick",function(){getDetails(data);});
into:
image.setAttribute("onclick",(function(d){return function(){getDetails(d);}}(data));
Also, the line:
row.appendChild(cell);
is redondant because the cell was inserted with row.insertCell(k)
Hi I'm creating a quiz application in jsp and am using different jsp pages for every question. I'd like to keep a score after each question is answered. My problem is that I'm picking random answers from a database, within which lies the correct answer too. Since I can't guess which letter the correct answer will appear on, could you suggest what I should do? I am posting the first and second question jsp's to give you an idea of how I'm doing it:
q1.jsp
<%#page import="java.util.Random"%>
<%#page import="java.util.ArrayList"%>
<%#page import="org.me.jsp.beans.WordBean"%>
<%#page import="java.util.List"%>
<!--This JSP acts as the first question in a multiple choice quiz, with the user
asked to submit their answer to the question-->
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id = "wordData" scope = "request"
class = "org.me.jsp.beans.WordDataBean" />
<html>
<head>
<title>Big Java Quiz, question 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%if (request.getParameter("choice").equals("N")) {
out.print("<meta http-equiv='refresh' content='0;url=options.jsp'/>");
}
//Redirects user back to index if they did not want to take quiz%>
<form action="q2.jsp" method="POST">
<%
List<WordBean> wordList = wordData.getWordList();
List<String> answersList = new ArrayList<String>();
Random random = new Random();
Random forAnswers = new Random();
WordBean goodOne = wordList.get(random.nextInt(wordList.size()));
//take it out from the list
wordList.remove(goodOne);
//add it to the answers list
answersList.add(goodOne.getGermanName());
WordBean fakeOne = wordList.get(random.nextInt(wordList.size()));
//take it out from the list
wordList.remove(fakeOne);
//add it to the answers list
answersList.add(fakeOne.getGermanName());
WordBean fakeTwo = wordList.get(random.nextInt(wordList.size()));
//take it out from the list
wordList.remove(fakeTwo);
//add it to the answers list
answersList.add(fakeTwo.getGermanName());
%>What is the English word for the German word <%=goodOne.getEnglishName()%>?<br>
<%
char letter = 'A';
for (String answer : answersList) {
%>
<input type="radio" name="q1Answer" value=""/><label for="<%=letter%>"><%=letter%>)<%=answersList.get(forAnswers.nextInt(3))%> />
<% //point to the next letter
letter++;
}
%>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
q2.jsp
<%--
Document : q2
Created on : 06-May-2012, 18:54:32
Author : encore
--%>
<!--This JSP acts as the second question in a multiple choice quiz, with the user
asked to submit their answer to the question-->
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Big Java Quiz, question 2</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%int score = 0;
if(request.getParameter("q1Answer").equals("C"))
score++; //Increments score if answer submitted was correct%>
<form action="q3.jsp" method="POST">
Your current score is: <%out.print(score);%>/20
<input type="hidden" name="q2Score" value="<%out.print(score);%>"/>
<!--Hidden button allows score to be accessed by next JSP-->
<b>Question 2.</b> When an exception is generated it is said to have been _________?<br/><br/>
<input type="radio" name="q2Answer" value="A"/><label for="A">A) Built</label><br/>
<input type="radio" name="q2Answer" value="B"/><label for="B">B) Thrown</label><br/>
<input type="radio" name="q2Answer" value="C"/><label for="C">C) Caught</label><br/>
<input type="radio" name="q2Answer" value="D"/><label for="D">D) Detected</label><br/><br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Note: the form of the second question will obviously be changed to something else, currently I'm concentrating on getting the score .
In the page for Q1, where you should know the correct answer, put it in the session and then retrieve it in the next page.