When I write code in <%, I can use javax.naming, but when I write code in <%!, I get an error that javax.naming does not exist.
some examples:
<% Javax.naming.InitialContext ic = new Javax.naming.InitialContext(); %> fine
<%! void foo() { Javax.naming.InitialContext ic2 = new Javax.naming.InitialContext(); } %> error
The exact error:
rptCountsRecon_jsp.java:22: package Javax.naming does not exist
Javax.naming.Context init = new Javax.naming.InitialContext();
I am sortof new to Java and am very new to JSP.
EDIT: added the foo method to the second example, because it may help understand my issue. Also added the exact error from Tomcat.
EDIT 2: tried adding the prefix to Context, and got a similar error.
EDIT 3: Side question... The current code gives the following error:
try
{
javax.naming.Context init = new javax.naming.InitialContext();
Context ctx = (Context) init.lookup("java:comp/env");
String jndiName = getServletContext().getInitParameter("jndiName");
DataSource ds = (DataSource) ctx.lookup(jndiName);
Connection dbConn = ds.getConnection();
PreparedStatement pstmnt = dbConn.prepareStatement(sql);
for(int i=0; i!=binds.size(); ++i)
pstmnt.setString(i+1, binds.elementAt(i)); //binds index starts at 1 -_-
return pstmnt.executeQuery();
} catch (Exception e) {
//out.println("A naming exception occured... I don't know how to get the info of it.");
return null;
}
rptCountsRecon_jsp.java:28: unreported exception java.sql.SQLException; must be caught or declared to be thrown
Connection dbConn = ds.getConnection();
First of all this type code should be in a servlet, not in a JSP.
Declaration (<%!):
<%!
javax.naming.InitialContext ic2 = new javax.naming.InitialContext();
%>
ic2 is a member variable. And the reason that you can't do ic2 = new javax.naming.InitialContext(); there is because the constructor throws javax.naming.NamingException.
Imagine something as follows:
public class JspServlet {
//there is no way to handle that exception here
javax.naming.InitialContext ic2 = new javax.naming.InitialContext();
//...
Scriptlet (<%):
<%
javax.naming.InitialContext ic = new javax.naming.InitialContext();
%>
And the reason that it can be done there (within scriplet) is because everything in the scriplet goes inside a try block of the generated JSP service method.
Imagine something as follows:
public class JspServlet {
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try {
javax.naming.InitialContext ic = new javax.naming.InitialContext();
} catch (Exception e) {
//...
}
I think it will make more sense if you read more about JSP lifecycle.
I agree with what Bhesh posted. But, you could do the following.
<%!
public void jspInit(){
try{
javax.naming.InitialContext ic2 = new javax.naming.InitialContext();
} catch (javax.naming.NamingException ne){
// do something when exception occurs
}
}
%>
The JSP container calls the jspInit method when it loads the page.
Related
I'm setting up a dhtmlx grid for loading data using grid.render_table method in java, no rendering is done, I'm new in this
I've tried to implement the PHP 'contact_manager' demo that comes with dhtmlx in java, but grid.render_table does not populate the grid
try (PrintWriter out = response.getWriter())
{
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("jdbc/PsFlowWeb");
conn = ds.getConnection(username, password);
GridConnector gc = new GridConnector(conn);
gc.enable_log("temp.log", false);
LogManager.getInstance().log("any text here");
gc.render_table("TCiudades","csCodigoCiudad","csCodigoCiudad,csDescripcionCiudad,csTipoRiesgo");
}
catch (Throwable e) { e.printStackTrace(); }
I expect the grid be populated with data from server obtained by using grid.render_table method
Could you please, check your log file and the response coming from your data request.
I created a JDBC connection pool (jdbc/WILLIAMSON) in Glassfish server using JNDI in Netbeans, I want to use this in all servlets so instead of writing the following code in every servlet
InitialContext context = new InitialContext();
//The JDBC Data source that we just created
DataSource datasource = (DataSource)
context.lookup("jdbc/WILLIAMSON");
Connection connection = null;
connection = ds.getConnection();
I created a class DBCONN and tried to call an object of this class in every servlet but getting error "variable context might not have been initialized". See my code is below:
public final class DBCONN {
private static final InitialContext context;
private static final DataSource datasource;
static{
try {
context = new InitialContext();
datasource=(DataSource) context.lookup("jdbc/WILLIAMSON");
} catch (NamingException ex) {
Logger.getLogger(DBCONN.class.getName()).log(Level.SEVERE,
null, ex);
}
}
private DBCONN() {
// I am confused how to use this method, pls guide me
}// ERROR HERE VARIABLE context MIGHT NOT HAVE BEEN INITIALIZED
public static Connection getConnection() throws SQLException {
return datasource.getConnection();
}
}
I'm calling the datasource.getConnection() in servlet HOME.java
DBCONN datasource = new DBCONN();
Connection connection = null;
connection = datasource.getConnection();// I am accessing a static
method so warning coming accessing static method getConnection(), how
to avoid it???
Change the line to private static InitialContext context = null;. The compiler is warning you that under certain circumstances, context might not be created.
static{
context = new InitialContext();
try {
datasource=(DataSource) context.lookup("jdbc/WILLIAMSON");
} catch (NamingException ex) {
Logger.getLogger(DBCONN.class.getName()).log(Level.SEVERE, null, ex); }
I'm trying to call a method that connects that is on a Bean on a jsp file. The method will make a request to a RMI Server and return a string. At this point the method is just return a pre-defined string for test.
This is the bean method:
public String getListProjects() throws RemoteException {
this.dataToSend = new Object[2];
this.dataToSend[1] = 0;
this.postCard = new ClientRequest("2", this.dataToSend, "tempo");
try{
this.postCard = this.connectToRMI.getActualProjects(this.postCard);
}catch(Exception e){
e.printStackTrace();
}
return "Hello";
}
And this is the jsp code:
<h1>Projectos Actuais</h1>
<h2><%
fundstarter.model.ConnectToRMIBean aux = new fundstarter.model.ConnectToRMIBean();
try{
aux.getListProjects();
}catch(Exception e){
e.printStackTrace();
}
%>
</h2>
I'm guiding my self from another code, and the method is called like this. But in my case it's not working, and I can't figure out what is wrong.
Since you've tagged this struts2, assuming the getListProjects() is on the Action, in JSP use:
<s:property value="listProjects" />
If instead it is on a bean, declare the bean in the Action, and expose it through a getter:
private MyBean bean;
public MyBean getBean(){
return bean;
}
and in JSP use the dot notation:
<s:property value="bean.listProjects" />
P.S: always avoid Scriptlets (<% %>), they're evil.
Quoting and fixing your latest change on edit with some comments:
<h1>Projectos Actuais</h1>
<h2><%
try{
fundstarter.model.ConnectToRMIBean aux = new fundstarter.model.ConnectToRMIBean();
//Send result into generated HTML page with out.print!
out.print(aux.getListProjects());
}catch(Exception e){
e.printStackTrace();
}
%>
</h2>
As per the flow of Struts there should be field in beanclass with same name of getter & setter. For an example if your method name is getListPorjects then in your bean class there should be a private string variable name listprojects.
Also your method will update with following to way to return listprojects.
example:
public String getListProjects() throws RemoteException {
this.dataToSend = new Object[2];
this.dataToSend[1] = 0;
this.postCard = new ClientRequest("2", this.dataToSend, "tempo");
try{
this.postCard = this.connectToRMI.getActualProjects(this.postCard);
listprojects = "hello"
}catch(Exception e){
e.printStackTrace();
}
return listprojects;
}
Calling bean variable should be with ID over the JSP page.
<jsp:useBean id="aux" class="com.path.to.ConnectToRMIBean" scope="request" />
----
yours stuff
-----
<h1>${aux.listProjects}
hope this will help you. good luck
You are just missing the way <% %> and <%= %> are used in JSP. to print in <% %> tags use
<% out.println("Your results"); %>
and for <%= %>
<%=
String.valueOf(1+2);
%>
i am new to web programming. i am trying to connect database using jsp with odbc. i have already written a java code for this. now i need to run on Tomcat server. so i choose JSP to do this job.But this is showing me void type not allowed here and erors. how to run this code using jsp. what are my mistakes. please help me to solve in this.
now this is my code
<%#page import="java.sql.*"%>
<%#page import="java.util.*" %>
<%#page import="java.util.logging.Level"%>
<%#page import="java.util.logging.Logger"%>
<%!
int i=0,j=0,k=0;
Connection conn=null;
Connection connection=null;
static int count=0;
String Cname[]=null;
String Title[]=null;
Statement stmt1=null;
ResultSet NumOfRows=null;
Statement stmt2=null;
ResultSet SpreadsheetValues=null;
Statement stmt3=null;
ResultSet rs3=null;
int RowCount;
//this static function required to connect excel database
static
{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("Exception in connecting to DB"+e.getMessage());
}
}
// connect Sql database
void ConnectSqlDB() {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:ServerDB","sa","sqladmin");
System.out.println("MSSQL connected " +"<br>");
}catch(Exception e){
e.printStackTrace();
System.out.println("Exception in connecting to DB"+e.getMessage());
}
}
void ConnectExcelDB() throws SQLException{
conn=DriverManager.getConnection("jdbc:odbc:spreadsheetdb","","");
}
void getRowcount() throws SQLException{
stmt1=conn.createStatement();
String Qs1="select count(*) from [Sheet1$]";
NumOfRows=stmt1.executeQuery(Qs1);
while(NumOfRows.next()){
Rowcount=NumOfRows.getInt(1);
}
NumOfRows.close();
}
void getExcelValues() throws SQLException{
stmt2=conn.createStatement();
String Qs2="select * from [Sheet1$]";
SpreadsheetValues=stmt2.executeQuery(Qs2);
Cname=new String[Rowcount];
Title=new String[Rowcount];
while(SpreadsheetValues.next()){
// Assigning Spread sheet values to String array
Cname[j]=SpreadsheetValues.getString("Cname");
Title[j]=SpreadsheetValues.getString("Title");
j++;
}
}
SpreadsheetValues.close();
stmt2.close();
conn.close();
SpreadsheetValues=null;
stmt2=null;
conn=null;
}
%>
<%=ConnectSqlDB()%>
<%=ConnectExcelDB()%>
<%=getRowcount()%>
<%=getExcelValues()%>
When you are using a method in a JSP Expression, then your method should return a value. I see all of your methods have a return type of void i.e. returning nothing. Change your methods to return appropriate value.
NOTE
I understand that you are currently learning JSP etc but keep in mind that writing contorl/application logic in a view technology like JSP is a bad practice. Try reading the MVC pattern.
Do not use <%= %> (Expression) to invoke void methods and you should have to avoid Java code in JSP (read SO thread).
<%
ConnectSqlDB();
ConnectExcelDB();
getRowcount();
getExcelValues();
%>
<p>Total Records : <%=RowCount%>
<p>Array element at 0 index <%=name[0]%>
<%
for(String v:name)
{
out.println("<br/>" + v);
}
%>
I print a list directly in the servlet using the print writer and the list prints.
When I try to put in the jsp however the list doesn't print whether I use JSTL or scriptlets.
I tried to test in JSTL and scriptlet if the object is null and turns out that it is!
Why does this happen and how can I fix this?
Servlet code that works
for (Artist artist:artists){
resp.getWriter().println(artist.getName());
}
Servlet code that puts object in the request
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
ApplicationContext ctx =
new ClassPathXmlApplicationContext("com/helloworld/beans/helloworld-context.xml");
ArtistDao artistDao = (ArtistDao) ctx.getBean("artistDao");
List<Artist> artists = null;
try {
artists = artistDao.getAll();
} catch (SQLException e) {
e.printStackTrace();
}
req.setAttribute("artists", artists);
try {
req.getRequestDispatcher("index.jsp").forward(req, resp);
} catch (ServletException e) {
e.printStackTrace();
}
scriptlet code that suddenly finds the object null
<%
List<Artist> artists = (List<Artist>) request.getAttribute("artists");
if (artists == null) {
out.println("artists null");
}
else {
for (Artist artist: artists){
out.println(artist.getName());
}
}
%>
Even the jstl code seems to agree
<c:if test="${artists eq null}">
Artists are null
</c:if>
<c:forEach var="artist" items="${artists}">
${artist.name}
</c:forEach>
For my app I am using weblogic, spring 2.5.6 and ibatis.
I think it depends on the web server. But without changing your previous directory structure,
try putting the list in session like this
req.getSession(false).setAttribute("artists", artists);
and in your jsp,
write
List<Artist> artists = (List<Artist>) request.getSession(false).getAttribute("artists");
I think my approach will work for all web servers.
Maybe the app server is resetting your request object. You can work around this by creating a new request object, that wraps your original request, and pass that to the reqest dispatcher.
e.g.
MyHttpRequest myRequest = new MyHttpRequest(req);
myRequest.setAttribute(...);
req.getRequestDispatcher("index.jsp").forward(myRequest, resp);
And the MyHttpReqest code:
class MyHttpRequest extends HttpServletRequestWrapper
{
Map attributes = new HashMap();
MyHttpRequest(HttpRequest original) {
super(original);
}
#Override
public void setAttribute(Object key, Object value) {
attributes.put(key, value);
}
public Object getAttribute(Object key) {
Object value = attributes.get(key);
if (value==null)
value = super.getAttribute(key);
return value;
}
// similar for removeAttribute
}
I just discovered inadvertently while trying to fix my directory structure in WebContent/
My previous directory structure was
WEB-CONTENT/
- META-INF/
- WEB-INF/
index.jsp
Then I tried to create a folder jsp in WEB-CONTENT and placed index.jsp there. It works!
My current directory structure now is
WEB-CONTENT/
- META-INF/
- WEB-INF/
- jsp/
-index.jsp
I don't know why it works but it did.
Anyone here with any idea why?