JSP display first then do business logic - java

My requirement is to display userName and FirstName first then try logic next....but here after some time in try block(few secs for try logic loading/execution) then userName and password displaying in page...How can i display userName/Firstanme then try logic next.
<html>
<head>
</head>
<body>
<%
String lastname= request.getParameter("lastname");
String firstname= request.getParameter("firstname");
%>
<tbody>
<tr>
<td>Firstname</td>
<td>:</td>
<td><%=firstname %></td>
</tr>
<tr>
<td>Lastname</td>
<td>:</td>
<td><%=lastname %></td>
</tr>
</tbody>
<%
try
{
System.out.println("Inside Thread");
Thread.currentThread().sleep(10000);
}
catch(Exception ex1)
{
System.out.println(ex1.getMessage());
}
%>
</body>
</html>

JSP is serverside language, the whole page is rendered, then send back to browser/client.
So with JSP you cannot do this.
You can include javascript in your jsp page, which talks to a webservice that does the logic you want it to do. The webservice can also return data that you can use to update your page...
I suggest you lookup AJAx on the web, a good place to start is:
http://www.w3schools.com/ajax/

Related

how to print list of list and other type of data in jsp

i am trying to fetch data from database in spring mvc, this is my code for fetching data
#Override
public List getOrderDetail(Integer shop_id) {
// TODO Auto-generated method stub
SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(
"SELECT order_id,shop_id,delivery_address,total_amount FROM master_order WHERE shop_id =" + shop_id);
SQLQuery query1 = sessionFactory.getCurrentSession().createSQLQuery(
"SELECT itm.image,itm.name,itm.brand,odr.quantity,itm.offerprice,(itm.offerprice*odr.quantity) AS Total,modr.cust_id FROM master_order modr\r\n"
+ "INNER JOIN tblorder odr ON modr.order_id = odr.order_id INNER JOIN item itm on odr.item_id = itm.item_id WHERE modr.shop_id ="+shop_id);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
query1.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List results = query.list();
List results1 = query1.list();
results.add(results1);
System.out.println(results);
return results;
}
above System.out.println(results); statement give following output
[{shop_id=1, delivery_address=1, abc, xyz, aaa, USA, order_id=6, total_amount=1800}, [{image=Screenshot (19).png, quantity=8, Total=800, name=DhruvRajkotiya, offerprice=100, brand=gsgsrgs, cust_id=2}, {image=Screenshot (19).png, quantity=10, Total=1000, name=qwe, offerprice=100, brand=asdf, cust_id=2}, {image=Screenshot (19).png, quantity=1, Total=100, name=ewq, offerprice=100, brand=gsgsrgs, cust_id=2}]]
i want print order_id as well as {image=Screenshot (19).png, quantity=10, Total=1000, name=qwe, offerprice=100, brand=asdf, cust_id=2} in jsp page
this is my controller code
#RequestMapping(value = "/notifications", method = RequestMethod.GET)
public String notifications(Model model, HttpServletRequest request) {
if (request.getSession().getAttribute("shopkeeper") == null) {
return "redirect:login";
} else {
Shopkeeper sp = (Shopkeeper) request.getSession().getAttribute("shopkeeper");
model.addAttribute("order", shopkeeperService_shopkeeper.getOrderDetail(sp.getSk_id()));
return "shopkeeper/notifications";
}
}
this is my jsp code
<div class="row">
<c:forEach items="${ order}" var="order">
<div class="col-lg-12">
<div class="card">
<div class="card-header" style="padding-bottom: 5px;">
<h6># ${order.shop_id }</h6>
</div>
<div class="card-body">
<div class="col-lg-2" style="float: left;">Image</div>
<div class="col-lg-2" style="float: left;">Product name</div>
<div class="col-lg-2" style="float: left;">Product brand
</div>
<div class="col-lg-1" style="float: left;">Quantity</div>
<div class="col-lg-1" style="float: left;">Unit Price</div>
<div class="col-lg-1" style="float: left;">Total</div>
<div class="col-lg-3" style="float: left;">Approve of
request</div>
</div>
<div class="card-body">
<div class="col-lg-6" style="float: left;">Delivery
Address</div>
<div class="col-lg-6" style="float: left;">Total Amount</div>
</div>
</div>
</div>
</c:forEach>
</div>
i want to print
my question concept is order_id,address,total_amount one time and multiple bought item that can be one or more
how i can print
The way to "send" some data to a JSP page is to set and pass a request (or session) attribute.
From a Servlet, which handles current request, in a doGet() or doPost() method (depending on the HTTP request method used), you can do:
request.setAttribute("attributeName", attributeObject);
request.getRequestDispatcher("<name_of_your_page>.jsp").forward(request, response);
where the attributeName is a string, which will be treated as a reference to the attributeObject on a JSP page.
Then on the JSP page, you can use JSTL library and Expression Language (see this tutorial regarding JSTL and this one regarding JSP & EL in general). To iterate over the list, which has been passed as a request attribute, use <c:forEach> tag from JSTL.
First of all you need to import the core JSTL tags by placing this line on the top of your JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Another useful statement to put under the latter is:
<%# page isELIgnored="false" %>
which tells your web browser to evalue the expressions written in EL instead of including them in HTML body as a plain text.
Provided that you used the string "orders" to name the collection set as attribute, the <c:forEach> tag usage can look similarly as below. You'll probably want to structure it differently and the field names (like order.order_id) can be different in your case, but I think you can get the idea.
<c:forEach item="order" items="${requestScope.orders}">
<p>${order.order_id}</p>
<p>${order.delivery_address}</p>
...
</c:forEach>
You can save the list as a model attribute. For example you want to save the current user:
model.addAttribute("user",user);
and access this attribute in your jsp file inside a div maybe :
<div> ${user.name} </div>
The controller method could look like this:
#RequestMapping( value = "/user", method = RequestMethod.GET )
public String displayUser(final Model model)
{
final User user = userService.findUserById(1); // here you'll provide custom implementation
model.addAttribute("user",user);
return "somejsppage.jsp";
}
If you want to add a List to your model:
final List<User> users = fillUserList(); // your implementation here
model.addAttribute("users",users);
You can access every element in that list via <c:forEach> tag:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<table>
<tr>
<th>First Name</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.firstName}</td>
</tr>
</c:forEach>
</table>
</body>
</html>

How to pass one JSP to another JSP?

I am creating small web apps and I am facing the following problem. I have 2 JSPs and when I click the submit button, it repeats the value every time. What I want is that when I click on the submit button it should give only the corresponding value.
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.io.*,java.util.*" %>
<!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>Class Video</title>
</head>
<body>
<form action="second.jsp" method="post">
<table>
<%
File f=new File("C:/Users/SHAKTI/Desktop/video");
File[] list=f.listFiles();
if(list.length!=0){
String s[]=new String[list.length];
for(int i=0;i<list.length;i++){
s[i]=list[i].toString();
String fi=list[i].getName();
%>
<tr><td><%=fi %></td>
<td><input type="text" name="file" value="<%=s[i] %>">
</td>
<td><input type="submit" name="play" value="Play"></td>
</tr>
<%}}
else{
%>
<tr>
<td>There is no any files in the database...</td>
</tr>
<%
}
%>
</table>
</form>
</body>
</html>
second.jsp
<form action="" method="post">
<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
String id=request.getParameter("file");
out.println("id = "+id);
%>
<input type="submit" name="submit" value="submit>
</form>
First Jsp : Set Value in First Page
request.setAttribute("name",somevalue);
Second Jsp : Retrieve it in Second page
request.getAttribute("name")
use queryString
URl: http://myaddress.com/xyz?name=jill&sex=f
String someName = request.getParameter("name") ;
String sex = request.getParameter("sex") ;
One way is to use session as described by javaBeginner.
you can also create a from on the fly and submit it.
write a function similar to this one and use it in your success:
function submitValues(url, params) {
var form = [ '<form method="POST" action="', url, '">' ];
for(var key in params)
form.push('<input type="hidden" name="', key, '" value="', params[key], '"/>');
form.push('</form>');
jQuery(form.join('')).appendTo('body')[0].submit();
}
There are many options to pass a value from one jsp to another, Here are some
1) Adding that as a hidden variable and specifying the value
<input name="file" type="hidden" value=""/>
2)Adding it to the session and retrieving the session variable
session.setAttribute("file", value);
3)Passing that as a queryParameter
http://......one.jsp?file=""
It is beacause you are iterating the loop here,
for(int i=0;i<list.length;i++){
s[i]=list[i].toString();
String fi=list[i].getName();
so it will print the last element from the loop, to get the name u clicked on the button try this .. Change this line as
<input type="text" name="file" value="<%=s[i] %>">
as,
<td><input type="button" class="btn" data-reqno=value="<%=s[i] %>" value="file name">
And handle it using jQuery like this , so that you can pass the value to next JSP,
<script type="text/javascript">
$(document).ready(function () {
$(".btn").click(
function() {
var selectedFileName = $(this).attr("data-reqno");
var urlToApprove = "/yourApp/req/filename?name=" + selectedFileName;
}
);
});
</script>
And also try to avoid Scriptlets in JSP , you can use JSTL or El for the same purpose .
Hope it helps !!
there are many method to pass variable such as
session.setAttribute()
session.getAttribute
action "xxx.jsp?variable=1"

Prevent SQL statement from executing on JSP page load

How can I have a SQL statement that updates data when a button is clicked, not execute when the page loads?
I have a very simple table that has a player name, a player score, and player id attributes and only one row. When I am on this page, I want the button to execute the update query to increase player score, but it's happening every time the page loads.
Is there a boolean or something I can set to prevent it from adding 1 to the player score on every load?
Please don't ask why I'm using a JSP in this context. It's bad to do, I know, but these are my requirements.
Here is my code:
<%# page contentType="text/html" %>
<%# page import="java.text.DecimalFormat" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<%# page import="java.sql.ResultSet" %>
<%# page import="java.sql.Statement" %>
<%# page import="java.lang*" %>
<!DOCTYPE html>
<html>
<head>
<title>Player scores</title>
<script>
function reloadPage() {
location.reload();
}
</script>
</head>
<body>
<%!
String name = "";
Integer score = 0;
Integer pID = 0;
%>
<form name="form1" method="POST" onsubmit="return false">
<p align="center">
<input type="BUTTON" value="+" onclick="reloadPage();"/>
</p>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");
Statement stmnt = conn.createStatement();
stmnt.executeUpdate("update players set playerScore=playerScore+1 where playerID=1");
} catch (Exception e) {
}
%>
</form>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");
Statement stmnt = conn.createStatement();
ResultSet rs = stmnt.executeQuery("select playerID, playerName, playerScore from players where playerID=1");
if (rs.next()) {
name = rs.getString("playerName");
score = rs.getInt("playerScore");
pID = rs.getInt("playerID");
} else {
name = "-";
score = 0;
pID = 404;
}
} catch(Exception e) {
}
%>
<table align="center">
<tr>
<th>Player name:</th>
<td id="pID"><%=name%></td>
</tr>
<tr>
<th>Player score:</th>
<td id="pN"><%=score%></td>
</tr>
<tr>
<th>Player id:</th>
<td id="pi"><%=pID%></td>
</tr>
<p class="center">
Go back
</p>
</table>
</body>
</html>
The update code always gets executed because you have your code written that way.
This code:
<form name="form1" method="POST" onsubmit="return false">
<p align="center">
<input type="BUTTON" value="+" onclick="reloadPage();"/>
</p>
that calls:
<script>
function reloadPage() {
location.reload();
}
</script>
is just a refresh with no extra parameters. You always perform a GET.
You need to tell the JSP to do something different when you click the + button. You might try something like this (please have a look at this tutorial first):
<form name="form1" method="POST" action="yourJSPWhateverIsCalled.jsp">
<p align="center">
<input type="submit" value="+" name="increaseScore" />
</p>
Then guard your update code with an if:
<%
if (request.getParameter("increaseScore") != null) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");
Statement stmnt = conn.createStatement();
stmnt.executeUpdate("update players set playerScore=playerScore+1 where playerID=1");
} catch (Exception e) {
}
}
%>
Class.forName is needed only once and you could reuse the connection to create the statements but that's another story. Also, a JSP isn't the place to postprocess a form submit (use a plain vanilla servlet).
One other problem with your code is that the JSP is thread UNsafe because of this definition:
<%!
String name = "";
Integer score = 0;
Integer pID = 0;
%>
If you use <%! the code is placed at servlet class level when your JSP gets translated to a servlet and not inside the _jspService method where it belongs. You are basically adding state to your JSP which is thread unsafe because the servlet container can reuse the same servlet instance to handle multiple requests.
Finally, I would strongly suggest you to read a JSP tutorial before continuing. An official tutorial is here.

how I can connect HTML to java to add values in database [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I want to enter data in database entered from jsp file and dont know how to connect them. Can any one suggest me to connect both files and to add the data entered in jsp form ?
This is my jsp and java files...
test1.java
package P1;
import java.sql.*;
class test1 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection con = null;
try {
Class.forName("oracle.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
con = DriverManager.getConnection("jdbc:oracle:thin:#192.168.106.87:1521:ORA11G","fuel_db","foel");
Statement statement = con.createStatement();
String command = "INSERT INTO student (name, rollno, class, mobileno) VALUES (?, ?, ?, ?);";
statement.executeUpdate(command);
con.close();
}
}
test1.html
**
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>FORM</title>
<script type="text/javascript">
<%
String name = request.getParameter("name");
String roll = document.getElementById("rollno");
String clas = document.getElementById("class");
String mobile = document.getElementById("mobileno");
test1 myTest = new test1();
myTest.submitData();
%>
function getvalues()
{
var name = document.getElementById("name");
var roll = document.getElementById("rollno");
var clas = document.getElementById("class");
var mobile = document.getElementById("mobileno");
}
function num(e)
{
var k;
document.all ? k = e.keyCode : k = e.which;
return (!((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8));
}
</script>
</head>
<body>
<form action="test1.java" method="post" >
<table>
<tr>
<td>First Name: </td>
<td><input type="text" name="name" maxlength="10"></td>
</tr>
<tr>
<td>roll:</td>
<td><input type="text" name="rollno" maxlength="5" onkeypress="return num(event)"></td>
</tr>
<tr>
<td>class:</td>
<td><input type="text" name="class" maxlength="10"></td>
</tr>
<tr>
<td>Mobile:</td>
<td><input type="text" name="mobileno" maxlength="10" onkeypress="return num(event)"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" onclick="getvalues()"></td>
</tr>
</table>
</form>
</body>
</html>
**
I won't go by your code. But the example here will be enough.
The standard way of passing/submitting data to the server in the pure Servlets/JSP world is by using HTML form, i.e. the same way as when use other server side languages for example php. And it doesn't matter whether it is a pure HTML page or JSP page. The recommended/most used method of submitting data from the form to the server is POST or GET.
Its standard way to submit data using POST method and respectively to process the submitted data using the doPost() method in your servlet.
for example:
<form name="something" method="post" action="<servlet-name>"> //if u want to change the action to something else then u need to modify your xml file.
<input type="text" name="username"/>
<input type="submit" name="submitit" value="submited"/>
</form>
now in the servlet under the doPost(...) write
if(request.getParameter("submitit").equals("submitted")){
String username=request.getParameter("username");
//now u can run a query and insert ito to database;
}
in the end you can redirect it another page with
`response.sendRedirect();`
or any other way
may i assume that you are using eclipse Java EE ide for development. then u need not worry about integrating them, eclipse would prepare the xml files for you once you create a new Java EE project. and if not then u have to do it manually, i once tried to do it, but I couldn't succeed.
here is a link: that would interset you, i hope: http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/
this is bad thing, but i will edit the code for you. by the way, i am removing the javascript. KISS (keeping it simple silly).. :)
ur jsp page would be:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>FORM</title>
</head>
<body>
<form action="test1" method="post" >
<table>
<tr>
<td>First Name: </td>
<td><input type="text" name="name" maxlength="10"></td>
</tr>
<tr>
<td>roll:</td>
<td><input type="text" name="rollno" maxlength="5"></td>
</tr>
<tr>
<td>class:</td>
<td><input type="text" name="class" maxlength="10"></td>
</tr>
<tr>
<td>Mobile:</td>
<td><input type="text" name="mobileno" maxlength="10"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
and the servlet will be:
import java.sql.*;
class test1 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection con = null;
PreparedStatement pstmt = null;
try {
Class.forName("oracle.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
con = DriverManager.getConnection("jdbc:oracle:thin:#192.168.106.87:1521:ORA11G","fuel_db","foel");
String name = request.getParameter("name");
String roll = document.getElementById("rollno");// idk why roll no is string
String clas_s = document.getElementById("class");
String mobile = document.getElementById("mobileno");
try {
String query= "INSERT INTO student (name, rollno, class, mobileno) VALUES (?, ?, ?, ?);";
pstmt = con.prepareStatement(query);
pstmt.setString(1,name);
pstmt.setString(2,roll);
pstmt.setString(3,clas_s);
pstmt.setString(4,mobile);
pstmt.executeUpdate();
con.close();
}
catch(Exception e) {
e.printStackTrace();}
response.sendRedirect("confirm.jsp");
}
}
donot ask me about the braces.. fix it yourself.
First create some method like submitData(data) in your Java class.
public class test1 {
public void submitData(String name,String rollno,String classData,String mobileno) throws SQLException, ClassNotFoundException {
Connection con = null;
try {
Class.forName("oracle.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
con = DriverManager.getConnection("jdbc:oracle:thin:#192.168.106.87:1521:ORA11G","fuel_db","foel");
Statement statement = con.createStatement();
String command = "INSERT INTO student (name, rollno, class, mobileno) VALUES (" + name + "," + rollno + "," + classData + "," + mobileno + ");";
statement.executeUpdate(command);
con.close();
}
}
In your HTMl page index.html or index.jsp, you need to put a form and then post it to JSP page which has the logic I have mentioned below.
<FORM NAME="form1" ACTION="ProcessData.jsp" METHOD="POST">
In your JSP page you may get data when a form is submitted using POST method. Get all those variables using request.getParameter("name")
Then in your JSP put that java code in <% %> blocks inside body tag. Remember JSP is Java in HTML!
In your ProcessData.jsp
<%
String name = request.getParameter("name");
//add null checks and all
//Similarly get all datamobileno etc
//then call your submitData() method
test1 myTest = new test1();
myTest.submitData(....)
%>
Also take care of naming conventions.
In java
Classes name start with Caps. So class name must be Test1 and not test1.
Functions, variables must be in Camel case like myTest.

Geocortext IMF framework Null reference exception

Still having issues with this problem. Please help if you can.
So I am trying to fix a piece of code using the Geocortex IMF framework. I get an error on line 40 which is basically pulling a null exception. It is a mix of java and html. For some reason I can't seem to find out why the error is pulling up a null. Even if I load the variable with data, it still stops at rs = activeLayer.getRecordset();
Here is the Address Form they fill out and submit
<%# page errorPage="imfError.jsp" %>
<%
/*
Program: afoAddressForm.jsp
Purpose: Displays a page to the user to input address values for a
USAddress type of geocoding query.
Usage: </>
History:
*/
String layerId = request.getParameter("layerid");
String scale = request.getParameter("scale");
if (layerId == null) {
throw new Exception("Missing layerid parameter.");
}
if (scale == null) {
throw new Exception("Missing scale parameter.");
}
%>
<jsp:include page="/imfCopyright.jsp"/>
<html>
<head>
<title></title>
<meta http-equiv="Content-Style-Type" content="text/css">
<link href="../../../imfStyle.css" rel="stylesheet" type="text/css">
<script language="JavaScript" type="text/javascript">
function doNothing() {
}
function submitForm() {
var strStreetName = document.frm.streetName.value;
if (strStreetName == "") {
alert("Please enter street name." );
document.frm.streetNumber.focus();
} else {
document.frm.action = "afoAddress.jsp?streetName="+strStreetName;
document.frm.submit();
}
}
</script>
</head>
<body bgcolor="#FFFFFF" alink="#ff0000" link="#ff0000" vlink="#ff0000">
<form name="frm" action="JavaScript:doNothing()" method="post">
<input type="hidden" name="layerid" value="<%= layerId %>">
<input type="hidden" name="scale" value="<%= scale %>">
<table width="95%" border="0" cellspacing="0" cellpadding="0">
<center>
<tr><td align="left" class="bb11">Zoom To Street<hr></td></tr>
<tr><td height="10"></td></tr>
<tr>
<td align="left" valign="top" class="bn8">
Enter the street name where you wish to centre the map.
If matching streets are found, you will be shown a list
of matching street names for you to choose where to
zoom the map to.
</td>
</tr>
<tr><td height="10"></td></tr>
<tr><td align="center" class="bb8">Street Name</td></tr>
<tr><td align="center" class="bb8"><input name="streetName" size="15" maxLength=40 value=""></td></tr>
<tr><td height="10"></td></tr>
<tr><td align="center" ><input name="btn" type="button" value="Submit" onclick="JavaScript:submitForm()"></td></tr>
<tr><td height="10"></td></tr>
</center>
</table>
</form>
</body>
</html>
Here is what the address form submits to
<%# page import="com.moximedia.aims.*" %>
<%
/*
Program: imfGeocodeUSAddress.jsp
An Internet Mapping Framework (IMF) system script
Copyright 2002 Province of British Columbia - all rights reserved
Purpose: Displays a page of positions matching the address
input by the user for USAddress geocoding styles.
History: 20020610 Cates: original coding
20030724 Cates: send user selection to separate script for labelling.
20040525 Cates: changed frame reference top to parent
20050103 Cates: added type to stylesheet link.
*/
String layerId = request.getParameter("layerid");
String scale = request.getParameter("scale");
String StreetName = request.getParameter("streetName");
AimsMap map = (AimsMap) (session.getAttribute("map"));
AimsFeatureLayer activeLayer = (AimsFeatureLayer) map.getLayers().getLayer(layerId);
AimsRecordset rs = null;
AimsFilter streetFilter = new AimsFilter();
if (activeLayer != null && activeLayer.getFilter()!= null) {
streetFilter = (AimsFilter) activeLayer.getFilter();
}
String query_String="";
if (StreetName == null) {
return;
}else{
StreetName = StreetName.toUpperCase();
query_String = "upper(FENAME) = '" + StreetName +"'";
//query_String = "FENAME like '%" + StreetName +"%'";
streetFilter.setWhereExpression(query_String);
}
// do the query, and whatever we need to do with the data
rs = activeLayer.getRecordset();
rs.clear();
rs.clearFilter();
rs.setMaximumResults(100);
rs.setBufferSize(rs.getMaximumResults());
rs.setFilter(streetFilter);
rs.query();
int count = 0;
rs.moveFirst();
while(!rs.EOF()) {
count++;
rs.moveNext();
}
%>
<jsp:include page="/imfCopyright.jsp"/>
<html>
<head>
<title></title>
<meta http-equiv="Content-Style-Type" content="text/css">
<link href="imfStyle.css" rel="stylesheet" type="text/css">
<script language="JavaScript" type="text/javascript">
function submitForm() {
document.query.submit();
}
</script>
</head>
<body onload="submitForm();">
<form name="query" method="post" action="afoSelectDefaultFind.jsp">
<input type="hidden" name="layerid" value="<%= layerId%>" >
<input type="hidden" name="rec" value="1" >
<input type="hidden" name="total" value="<%=count%>" >
<input type="hidden" name="query_String" value="<%=query_String%>" >
</form>
</body>
</html>
The error is when you hit submit on the form the java.lang.NullPointerException error pops up and put it on line 40 which is rs = activeLayer.getRecordset();. Any help with this would be great.
Well, my guess is that activeLayer is null and then you are calling getRecordset() on a null object reference. Can you try to debug
map.getLayers().getLayer(layerId);
To make sure that it is returning something?
As Chris Thompson points out, the issue is almost certainly that the layer is null. Check that your AXL file has the right layers and layerIds. (Sorry, I know ArcIMS, but I'm not familiar with the Geocortex framework.)
Also, you should add code to check if activeLayer is null and throw a different exception than NullPointerException, since that will make the error that much more obvious to the next programmer that comes along. Interesting that the streetFilter isn't applied if activeLayer is null, so somebody thought about this at some point.

Categories

Resources