I've created autocomplete with Jquery UI library and try to get the text box value in java, but not getting the value instead of getting null value. Please help to get value from text box. This is the line String query = (String)request.getParameter("country"); not getting values ?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
input {
font-size: 120%; }
</style>
</head>
<body>
<h3>Feature</h3>
<input type="text" id="country" name="country"/>
<script>
//$("#country").autocomplete("getdata.jsp");
$("#country").autocomplete({
source: "getdata.jsp",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
</script>
</body>
</html>
getdata.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%
String query = (String)request.getParameter("country");
System.out.println("query"+query);
try{
String s[]=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =DriverManager.getConnection("XXXXX");
Statement st=con.createStatement();
ResultSet rs = st.executeQuery("select name from table1 where name like '"+query+"%'");
List li = new ArrayList();
while(rs.next())
{
li.add(rs.getString(1));
}
String[] str = new String[li.size()];
Iterator it = li.iterator();
int i = 0;
while(it.hasNext())
{
String p = (String)it.next();
str[i] = p;
i++;
}
//jQuery related start
int cnt=1;
for(int j=0;j<str.length;j++)
{
if(str[j].toUpperCase().startsWith(query.toUpperCase()))
{
out.print(str[j]+"\n");
if(cnt>=5)// 5=How many results have to show while we are typing(auto suggestions)
break;
cnt++;
}
}
//jQuery related end
rs.close();
st.close();
con.close();
}
catch(Exception e){
e.printStackTrace();
}
%>
it's not a form,so don't get the value use getParameter().
source: "getdata.jsp?country="+$("#country").val(),
Related
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 am trying to implement an ajax call to populate the options of a select drop down based on the input textfield. Any help would be appreciated on this.
This is my method which allows us to get the template for a number .
System.out.println("Getting template for " + no_nego);
//Do the database code or business logic here.
try {
Connection con;
con = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:8081/RSI_MANAGEMENT", "root", "user");
Statement stmt = null;
stmt = con.createStatement();
String tableName = "rsi_demande";
String sql;
sql = "select filename from " + tableName +
" Where (filename IS NOT NULL and no_negociateur=" + getNo_nego() + " ) ";
ResultSet res = null;
res = stmt.executeQuery(sql);
while (res.next()) {
listeTemplateDownload.add(res.getString(1));
}
//setListeTemplateDownload(listeTemplateDownload);
stmt.close();
} catch (Exception ex1) {
ex1.printStackTrace();
}
for (int i = 0; i < 2; i++)
System.out.println(listeTemplateDownload.get(i));
JSONArray json = new JSONArray();
json.addAll(getListeTemplateDownload());
json.toString();
System.out.printf("JSON: %s", json.toString());
return Action.SUCCESS;
}
And here is my jsp page :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
</head>
<body>
<script>
$(function() {
$("#no_nego").change(
function() {
var state = {
"no_nego": $("#no_nego").val()
};
$.ajax({
url: "readDistricts",
data: JSON.stringify(state),
dataType: 'JSON',
contentType: 'application/json',
type: 'POST',
async: true,
success: function() {
var $select = $('#listeTemplateDownload');
$select.html('');
console.log(listeTemplateDownload.size());
for (var i = 0; i < getListeTemplateDownload().size(); i++) {
$select.append(
'<option value= ' + listeTemplateDownload.get(i) + '</option>');
}
}
});
});
});
</script>
<h3>Struts 2 Dynamic Drop down List</h3>
State :
<input type="text" id="no_nego"></select> District :
<select id="listeTemplateDownload"></select>
</body>
</html>
I want that when a user finished set number, the list will be generated dynamically ...
But how can i populate select form with these data?
Solved .
The problem was the append method :
jsp :
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function () {
$('#listeTemplateDownload').html('');
$("#no_nego").change(
function() {
var no_nego = {
"no_nego" : $("#no_nego").val()
};
$.ajax({
url : "readDistricts.action",
data : JSON.stringify(no_nego),
dataType : 'json',
contentType : 'application/json',
type : 'post',
async : true,
success : function(res) {
console.log(res.listeTemplateDownload.length);
for ( var i = 0; i < res.listeTemplateDownload.length; i++) {
$('#listeTemplateDownload').append( '<option value=' + res.listeTemplateDownload[i] + '>' + res.listeTemplateDownload[i] + '</option>');
}
}
});
});
});
</script>
</head>
<body>
<h3>Struts 2 Dynamic Drop down List</h3>
Negociateur n°:
<input type="text" id="no_nego" > Template :
<select id="listeTemplateDownload"></select>
</body>
</html>
<%# page import="java.sql.*" %>
<%# page import="javax.sql.*" %>
<%# page import="java.util.*" %>
<%
Connection con =null;
PreparedStatement pstmt=null;
List<String> list=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "xyz", "abc");
String strQuery = "SELECT batch_id,course_name FROM t_students_batch";
pstmt = con.prepareStatement(strQuery);
rs = pstmt.executeQuery();
list = new ArrayList<String>();
while(rs.next()) {
list.add(rs.getString("batch_id"));
list.add(rs.getString("course_name"));
}
}catch(Exception e) {
System.out.println("Error:: "+e.getMessage());
}
%>
<html>
<head>
<title>pay</title>
</head>
<body>
<form action="payment.jsp" method="get">
BatchId ::<select name="batchid">
<%
for (String temp : list) {
// how to i get this..
out.println("<option>"+ temp +"</option>");
}
%>
<input type="submit" value="continue" action="payment.jsp" />
</select>
</form>
</body>
</html>
output :::
1 java
2 jsp
Total column values are displaying like this
When I click the "1" it's working...
When I click the java or jsp, it will show me a null pointer exception..
I want to take the java value 1 display as it is the logic..
Try this one.
<%
for (int i = 0; i < list.size(); i = i+2) {
out.println("<option value='"+list.get(i) +"'>"+ list.get(i+1) +"</option>");
}
%>
missing value attr , now it should submit value.
<%
for (String temp : list) {
// how to i get this..
out.println("<option value='"+temp +"'>"+ temp +"</option>");
}
%>
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.
I have a Java login application that works and uses a microsoft access database to validate login details. I'm currently in the process of building a java web application and I'm just trying to implement code from my working example.
My problem is that I have 2 input fields here for username and password, (called "name" and "password") But my SQL code which works in the previous example cannot detect the fields on this page called name and password, where the user would input their details respectively.
Any help would be much appreciated!
<%#page import="javax.swing.JOptionPane"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.DriverManager"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Angels & Demons</title>
Home Page
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1><center>Login</center></h1>
<center><form action="login.jsp">
<h2>Please make sure to fill all fields! </h2>
<table>
<tr><td>User:<input name="name" type="text" size="10"></td></tr>
<tr><td>Password:<input name="password" size="10"></td></tr>
<td><input type="submit" value="Submit"></input></td>
</table>
</center>
<%
if ((request.getParameter("name") != null )
&& (request.getParameter("password") != null )
)
{
Connection conn = null;
Statement st = null;
ResultSet rs;
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:AngelsAndDemons";
conn = DriverManager.getConnection(db);
st = conn.createStatement();
String sql = "select user,pass from AngelsAndDemons where user = '"+name+"'and pass = '"+password+"'";
rs = st.executeQuery(sql);
int count = 0;
while(rs.next())
{
count = count + 1;
}
if(count == 1)
{
JOptionPane.showMessageDialog(null,"User found, Access Granted!");
}
else if(count > 1){
JOptionPane.showMessageDialog(null,"Duplicte User, Access Denied");
}
else{
JOptionPane.showMessageDialog(null,"User not found");
}
}
catch(Exception ex)
{
}
}
%>
There was Problem in Login.
<%
%>
}
</form>
</body>
</html>
There are two problems in your code..
1) You want your java code to be executed on button click..so you should check for button click and then write code within it as:
<input type="submit" value="Submit" name="bt"></input></td> //Define a name for button
<%
if(request.getParameter("bt")!=null)
{
if ((request.getParameter("name") != null )
&& (request.getParameter("password") != null ))
{
//your code
}
}
%>
2) You have not stored your username and password in any variable and still accessing them in your query by using the name of your text field which is wrong..Save them in a variable and use that variable in the query as :
String name= request.getParameter("name");
String pass= request.getParameter("password");
String sql = "select user,pass from AngelsAndDemons where user = '"+name+"'and pass = '"+pass+"'";
Do not concatenate Strings. Used PreparedStatements to avoid SQL injection.
Also avoid storing passwords on String variables. Use char[] when possible, and wipe it after using it, to avoid leaving a cleartext password on memory.
Congrats on trying web server development.
First a corrected version.
<%#page contentType="text/html" pageEncoding="UTF-8"
import="java.sql.*"
import="javax.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Angels & Demons</title>
Home Page
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1><center>Login</center></h1>
<%
String name = request.getParameter("name");
String password = request.getParameter("password");
if (name == null || password == null) {
%>
<center>
<form action="login.jsp" method="POST">
<h2>Please make sure to fill all fields! </h2>
<table>
<tr><td>User:<input name="name" type="text" size="10"></td></tr>
<tr><td>Password:<input name="password" size="10"></td></tr>
<td><input type="submit" value="Submit"></input></td>
</table>
</center>
</form>
<%
} else {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:AngelsAndDemons";
try (Connection conn = DriverManager.getConnection(db)) {
String sql = "select count(*) from AngelsAndDemons where user = ? and pass = ?";
try (PreparedStatement st = conn.prepareStatement(sql)) {
st.setString(1, user);
st.setString(2, password);
try (ResultSet rs = st.executeQuery()) {
int count = 0;
if (rs.next()) {
count = rs.getInt(1);
}
if(count == 1) {
%><h2>User found, Access Granted!</2><&
} else if(count > 1) {
%><h2>Duplicate User, Access Denied</2><&
} else {
%><h2>Duplicate User, Access Denied</2><&
}
}
}
} catch (Exception ex) {
%><h2>There was Problem in Login.</2>
<p><%= ex.getMessage() %></p>
<&
}
}
%>
</body>
</html>
With the imports I was a bit lazy and used * - which is bad style.
The page is delivered on a browser request (HTTP GET) back to the browser, the client.
No parameters were in the request, so the form is output.
After the form is submitted by the browser, here as HTTP POST request,
there are parameters.
Now a database query can be done.
Try-with-resources ensure that all is closed (connection, prepared statement and result set). Even on return/break/exception.
A PreparedStatement takes care of escaping (say a Name with an apostrophe in it). And most important prevents hacking, SQL injection (=creating evil SQL). Like a name admin and password xxx' OR 1=1.
Access was in my time not a multiuser database. You might use a Derby or H2 database.
JOptionPane does not work in an HTML page delivered, or even on creating the page on the server. The alternatives is writing on the result page.
You picked a hard topic with many features. Good luck.
As JSPs get soon ugly, unreadable, try servlets, maybe in combinations, pure servlet for coding and delivering results in a JSP page.