Servlets and Actions
Hi,
i defined an ActionServlet in the web.xml and some "Actions" in the struts-config.xml.
If all the requests are managed by the servlet defined in the web.xml, in case i had a lot of requests would it be better defined more ActionServlet in the web.xml which refers to different struts-config.xml ?
I think that having more servlet is much better to manage the load of the entire application.
Any suggestions ?
Cheers.
Stefano
"...If all the requests are managed by the servlet defined in the web.xml, in case i had a lot of requests would it be better defined more ActionServlet in the web.xml which refers to different struts-config.xml ?..."
No. Using a single, multi-threaded servlet is the most efficient way to process multiple requests. Only one instance of the ActionServlet is required for the whole app. Bottom line - multiple threads are more efficient than multiple instances.
Similar Messages
-
Servlet and Actions - Apache Struts !
Hi,
i defined an ActionServlet in the web.xml and some "Actions" in the struts-config.xml.
If all the requests are managed by the servlet defined in the web.xml, in case i had a lot of requests would it be better defined more ActionServlet in the web.xml which refers to different struts-config.xml ?
I think that having more servlet is much better to manage the load of the entire application.
Any suggestions ?
Cheers.
StefanoNo need creating more than one ActionServlet : Servlets are Threads so each request made by a client is handled by a different Thread!
-
Using database connection in a servlet and get errors after 8 hours
Hey,
I'm running a poker script using applet/servlets and it works great. But for some reason about about 8 hours that database layer stops working. At first I thought it was the connections to mySQL that were timing out (because im using connection pooling) but after turning pooling off (I now create the connection each time) I'm still seeing that same error (I can create a connection but when I do an action ex. like a select statment I get an error). What i'm wondering could it be that the driver I load with Class.forName() some how unloads it's self after x amount of time not being used? Not sure if that is it but if anyone could give me some insight that would be great. The Error i recieve is below:
INFO: Database Event:DatabaseController: Error executing database query.
ERROR: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: Software caused connection abort: recv failed
STACKTRACE:
java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:104)
at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:144)
at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:172)
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1839)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2288)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2784)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1531)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1622)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2370)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2297)
at com.mysql.jdbc.Statement.executeQuery(Statement.java:1183)
at com.softnet.database.DatabaseController.executeDatabaseQuery(DatabaseController.java:190)
at com.softnet.games.GameServer.validateUser(GameServer.java:438)
at com.softnet.games.GameServer.handleData(GameServer.java:113)
at com.softnet.network.HttpConnectionThread.run(HttpServletListener.java:191)
** END NESTED EXCEPTION **
I know the query is good because it works all other times just not after about 8 hours.
--Z3r0CooLHey,
Thanks for the responces. For the connection pooling I would open 5 connections and keep them open. So i though maybe after 8 hours after not being used they would timeout. Thats why i turned off conection pooling and create a new connection each time. Anyways i'll post the code below incase i made a mistake somewhere.
package com.softnet.database;
/************************ DatabaseControler **************************/
import java.sql.*;
import java.util.*;
import com.softnet.database.DatabaseConnectionPool;
import com.softnet.database.DatabaseSettings;
public class DatabaseController
implements DatabaseListener
//Used to make sure the database driver is loaded
private boolean databaseDriverState = false;
//Used to store a database connection
private Connection databaseConnection = null;
//If to user connection pooling or not
private boolean useConnectionPooling = false;
//Used to hold the connection pool varible
private DatabaseConnectionPool connectionPool = null;
//Used to store database settings
private DatabaseSettings databaseSettings;
//Used to hold the DatabaseController listeners
private List databaseControllerListeners = new ArrayList();
//min number of connections for connection pool
private int minNumberOfConnections = 1;
//max number of connections for connection pool -1 is unlimited
private int maxNumberOfConnections = -1;
//DatabaseController Constructors
public DatabaseController(DatabaseSettings databaseSettings)
this.databaseSettings = databaseSettings;
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
public DatabaseController(DatabaseSettings databaseSettings, boolean useConnectionPooling, int minNumberOfConnections, int maxNumberOfConnections)
this.databaseSettings = databaseSettings;
this.useConnectionPooling = useConnectionPooling;
this.minNumberOfConnections = minNumberOfConnections;
this.maxNumberOfConnections = maxNumberOfConnections;
if(useConnectionPooling == true)
connectionPool = new DatabaseConnectionPool(databaseSettings, minNumberOfConnections, maxNumberOfConnections);
connectionPool.addDatabaseListener(this);
else
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
public DatabaseController() {}
//Database Settings Get/Set
public DatabaseSettings getDatabaseSettings()
return databaseSettings;
public void setDatabaseSettings(DatabaseSettings databaseSettings)
this.databaseSettings = databaseSettings;
//Connection Pooling Get/Set
public boolean getConnectionPooling()
return useConnectionPooling;
public void setConnectionPooling(boolean useConnectionPooling, int minNumberOfConnections, int maxNumberOfConnections)
this.useConnectionPooling = useConnectionPooling;
this.minNumberOfConnections = minNumberOfConnections;
this.maxNumberOfConnections = maxNumberOfConnections;
if(useConnectionPooling == true)
if(connectionPool == null)
connectionPool = new DatabaseConnectionPool(databaseSettings, minNumberOfConnections, maxNumberOfConnections);
connectionPool.addDatabaseListener(this);
else
if(connectionPool != null)
connectionPool.destroyConnections();
connectionPool.removeDatabaseListener(this);
connectionPool = null;
//Return if there connected
public boolean isConnected()
boolean isConnected;
if(databaseConnection != null)
isConnected = true;
else
isConnected = false;
return isConnected;
//Used to connect to database or get a connection for the connection pool
public void connect()
if(databaseDriverState == false)
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
//If we dont have a current connection, make one
if(databaseConnection == null && databaseDriverState == true)
if(useConnectionPooling == false)
try
databaseConnection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
catch (SQLException sqle)
//Raise event
raiseDatabaseEvent("DatabaseController: Error connecting to database. \nERROR: " + sqle.getMessage());
databaseConnection = null;
else
databaseConnection = connectionPool.getConnection();
//Used to disconnect from the database or give back the connection to the connection pool
public void disconnect()
if(databaseConnection != null)
if(useConnectionPooling == false)
try
//Close DB Connection
databaseConnection.close();
catch(SQLException ignore) {}
finally
databaseConnection = null;
else
connectionPool.returnConnection(databaseConnection);
databaseConnection = null;
public ResultSet executeDatabaseQuery(String sSQL)
ResultSet databaseResult = null;
if(databaseConnection != null)
try
Statement databaseStatement = databaseConnection.createStatement();
databaseResult = databaseStatement.executeQuery(sSQL);
catch(SQLException sqle)
//Raise event
raiseDatabaseEvent("DatabaseController: Error executing database query.\nSQL: " + sSQL + "\nERROR: " + sqle.getMessage());
return databaseResult;
public int executeDatabaseUpdate(String sSQL)
int rowsAffected = -1;
if(databaseConnection != null)
try
Statement databaseStatement = databaseConnection.createStatement();
rowsAffected = databaseStatement.executeUpdate(sSQL);
catch(SQLException sqle)
//Raise event
raiseDatabaseEvent("DatabaseController: Error executing database update.\nSQL: " + sSQL + "\nERROR: " + sqle.getMessage());
return rowsAffected;
//Used to load the Database Driver
private boolean loadDatabaseDriver(String databaseDriver)
boolean driverLoaded;
if(databaseDriver.equals("") == false)
try
//Load Database Driver
Class.forName(databaseDriver).newInstance();
driverLoaded = true;
catch (Exception e)
//Raise event
raiseDatabaseEvent("DatabaseController: Error loading database driver. \nERROR: " + e.getMessage());
driverLoaded = false;
else
driverLoaded = false;
return driverLoaded;
//Wrap the DatabaseConnectionPool Error to the DatabaseController
public void databaseEventOccurred(DatabaseEvent de)
raiseDatabaseEvent(de.getErrorMessage());
//Event Handling Code
//Used to add database listeners (Its sync'd so you can change the listeners when firing an event)
public synchronized void addDatabaseListener(DatabaseListener databaseControllerListener)
databaseControllerListeners.add(databaseControllerListener);
//Used to remove a listener from the list (Its sync'd so you can change the listeners when firing an event)
public synchronized void removeDatabaseListener(DatabaseListener databaseControllerListener)
databaseControllerListeners.remove(databaseControllerListener);
//Used to send the raise event to the listeners
private synchronized void raiseDatabaseEvent(String databaseError)
DatabaseEvent databaseEvent = new DatabaseEvent(this, databaseError);
Iterator listeners = databaseControllerListeners.iterator();
while(listeners.hasNext())
DatabaseListener listener = (DatabaseListener) listeners.next();
listener.databaseEventOccurred(databaseEvent);
/********************* DatabaseConnectionPool **************/
package com.softnet.database;
import java.io.*;
import java.sql.*;
import java.util.*;
import com.softnet.database.*;
import com.softnet.database.DatabaseSettings;
public class DatabaseConnectionPool
//min number of connections
private int minNumberOfConnections = 1;
//max number of connections -1 is unlimited
private int maxNumberOfConnections = -1;
//Store the connections
protected Hashtable databaseConnections = null;
//Database Info
protected DatabaseSettings databaseSettings;
//to hold Driver state
private boolean databaseDriverState = false;
//To hold connection checker
private DatabaseConnectionCheck connectionChecker = null;
//Used to hold the DatabaseConnectionPool listeners
private List databaseConnectionPoolListeners = new ArrayList();
public DatabaseConnectionPool(DatabaseSettings databaseSettings, int minNumberOfConnections, int maxNumberOfConnections)
this.databaseSettings = databaseSettings;
this.minNumberOfConnections = minNumberOfConnections;
this.maxNumberOfConnections = maxNumberOfConnections;
//Load Driver
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
//Create connection
createConnections();
public DatabaseConnectionPool(int minNumberOfConnections, int maxNumberOfConnections)
this.minNumberOfConnections = minNumberOfConnections;
this.maxNumberOfConnections = maxNumberOfConnections;
//Database Settings Get/Set
public DatabaseSettings getDatabaseSettings()
return databaseSettings;
public void setDatabaseSettings(DatabaseSettings databaseSettings)
this.databaseSettings = databaseSettings;
//Driver State Get
public boolean getDatabaseDriverState()
return databaseDriverState;
public void createConnections()
if(databaseDriverState == false)
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
//Create all connections and load the minimum in the Hashtable
if(databaseConnections == null)
if(databaseDriverState == true && minNumberOfConnections != 0)
databaseConnections = new Hashtable();
for(int i = 0; i < minNumberOfConnections; i++)
try
databaseConnections.put(DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword()), Boolean.FALSE);
catch(SQLException sqle)
//Problem break loop and destroy any connections
destroyConnections();
//Raise event
raiseDatabaseEvent("DatabaseConnectionPool: Error creating database connections. \nERROR: " + sqle.getMessage());
break;
//If no connection check exists create one
if(connectionChecker == null)
connectionChecker = new DatabaseConnectionCheck(this);
connectionChecker.start();
public Connection getConnection()
Connection connection = null;
boolean errorWithConnection = false;
Enumeration connections = databaseConnections.keys();
synchronized (databaseConnections)
while(connections.hasMoreElements())
errorWithConnection = false;
connection = (Connection) connections.nextElement();
Boolean state = (Boolean) databaseConnections.get(connection);
//If connection is not used, use it.
if(state == Boolean.FALSE)
try
connection.setAutoCommit(true);
catch(SQLException e)
//Problem with connection remove connection and replace it
databaseConnections.remove(connection);
try
connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
catch(SQLException sqle)
errorWithConnection = true;
if(errorWithConnection == false)
// Update the Hashtable to show this one's taken
databaseConnections.put(connection, Boolean.TRUE);
// Return the connection
return connection;
//All connections being used check to max to see if we can make a new one
if(maxNumberOfConnections == -1 || maxNumberOfConnections > databaseConnections.size())
try
connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
catch(SQLException sqle)
errorWithConnection = true;
if(errorWithConnection == false)
databaseConnections.put(connection, Boolean.TRUE);
return connection;
//If not connections free and max connections reached wait for a free connection
return getConnection();
public void returnConnection(Connection connection)
boolean errorWithConnection = false;
//Make sure connection still works
try
connection.setAutoCommit(true);
catch(SQLException e)
//Problem with connection remove connection and replace it
databaseConnections.remove(connection);
try
connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
catch(SQLException sqle)
errorWithConnection = true;
if(errorWithConnection == false)
databaseConnections.put(connection, Boolean.FALSE);
public void destroyConnections()
Connection connection = null;
if(databaseConnections != null)
//Close all connections
Enumeration connections = databaseConnections.keys();
while (connections.hasMoreElements())
connection = (Connection) connections.nextElement();
try
connection.close();
catch(SQLException ignore) {}
//Free up hashtable
databaseConnections = null;
private boolean loadDatabaseDriver(String databaseDriver)
boolean driverLoaded;
if(databaseDriver.equals("") == false)
try
//Load Database Driver
Class.forName(databaseDriver);
driverLoaded = true;
catch (ClassNotFoundException cnfe)
//Raise event
raiseDatabaseEvent("DatabaseController: Error loading database driver. \nERROR: " + cnfe.getMessage());
driverLoaded = false;
else
driverLoaded = false;
return driverLoaded;
//Event Handling Code
//Used to add database listeners (Its sync'd so you can change the listeners when firing an event)
public synchronized void addDatabaseListener(DatabaseListener databaseConnectionPoolListener)
databaseConnectionPoolListeners.add(databaseConnectionPoolListener);
//Used to remove a listener from the list (Its sync'd so you can change the listeners when firing an event)
public synchronized void removeDatabaseListener(DatabaseListener databaseConnectionPoolListener)
databaseConnectionPoolListeners.remove(databaseConnectionPoolListener);
//Used to send the raise event to the listeners
private synchronized void raiseDatabaseEvent(String databaseError)
DatabaseEvent databaseEvent = new DatabaseEvent(this, databaseError);
Iterator listeners = databaseConnectionPoolListeners.iterator();
while(listeners.hasNext())
DatabaseListener listener = (DatabaseListener) listeners.next();
listener.databaseEventOccurred(databaseEvent);
class DatabaseConnectionCheck extends Thread
private DatabaseConnectionPool connectionPool;
DatabaseConnectionCheck(DatabaseConnectionPool connectionPool)
this.connectionPool = connectionPool;
public void run()
try
while(true)
//check threads every 30 seconds
this.sleep(300000);
if(connectionPool.databaseConnections != null)
Connection connection = null;
Enumeration connections = connectionPool.databaseConnections.keys();
synchronized (connectionPool.databaseConnections)
while(connections.hasMoreElements())
connection = (Connection) connections.nextElement();
Boolean state = (Boolean) connectionPool.databaseConnections.get(connection);
//If connection is not used, use it.
if(state == Boolean.FALSE)
try
connection.setAutoCommit(true);
catch(SQLException e)
//Problem with connection remove connection and replace it
connectionPool.databaseConnections.remove(connection);
try
connection = DriverManager.getConnection(connectionPool.databaseSettings.getDatabaseURL(), connectionPool.databaseSettings.getUserName(), connectionPool.databaseSettings.getUserPassword());
catch(SQLException sqle)
connection = null;
// Update the Hashtable with new connection if its not null
if(connection != null)
connectionPool.databaseConnections.put(connection, Boolean.FALSE);
catch(InterruptedException ignored) {}
Basicly the why it works is the connection pool hold the database connections. When the user needs a connection they use the database controller to request a connection (By create a instance and called the connect() method) and the connection is either created or grabed from the connection pool. After the user is done with the connection they call the disconnect() method which closes the connection or returns it to the connection pool.
--Z3r0CooL -
I want to send a response from the servlet and then call another servlet.
Hi,
I want to send a response from the servlet and then call another servlet. can this happen. Here is my scenario.
1. Capture all the information from a form including an Email address and submit it to a servlet.
2. Now send a message to the browser that the request will be processed and mailed.
3. Now execute the request and give a mail to the mentioned Email.
Can this be done in any way even by calling another servlet from within a servlet or any other way.
Can any one Please help me out.
Thanks,
RameshMaybe that will help you (This is registration sample):
1.You have Registration.html;
2.You have Registration servlet;
3.You have CheckUser servlet;
4.And last you have Dispatcher between all.
See the code:
Registration.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Hello registration</TITLE>
</HEAD>
<BODY>
<H1>Entry</H1>
<FORM ACTION="helloservlet" METHOD="POST">
<LEFT>
User: <INPUT TYPE="TEXT" NAME="login" SIZE=10><BR>
Password: <INPUT TYPE="PASSWORD" NAME="password" SIZE=10><BR>
<P>
<TABLE CELLSPACING=1>
<TR>
<TH><SMALL>
<INPUT TYPE="SUBMIT" NAME="logon" VALUE="Entry">
</SMALL>
<TH><SMALL>
<INPUT TYPE="SUBMIT" NAME="registration" VALUE="Registration">
</SMALL>
</TABLE>
</LEFT>
</FORM>
<BR>
</BODY>
</HTML>
Dispatcher.java
package mybeans;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Dispatcher extends HttpServlet {
protected void forward(String address, HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = getServletContext().
getRequestDispatcher(address);
dispatcher.forward(request, response);
Registration.java
package mybeans;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Registration extends Dispatcher {
public String getServletInfo() {
return "Registration servlet";
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext ctx = getServletContext();
if(request.getParameter("logon") != null) {
this.forward("/CheckUser", request, response);
else if (request.getParameter("registration") != null) {
this.forward("/registration.html", request, response);
CheckUser.java
package mybeans;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class CheckUser extends Dispatcher {
Connection conn;
Statement stat;
ResultSet rs;
String cur_UserName;
public static String cur_UserSurname;;
String cur_UserOtchestvo;
public String getServletInfo() {
return "Registration servlet";
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
ServletContext ctx = getServletContext();
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:oci:@eugenz","SYSTEM", "manager");
stat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String queryDB = "SELECT ID, Login, Password FROM TLogon WHERE Login = ? AND Password = ?";
PreparedStatement ps = conn.prepareStatement(queryDB);
User user = new User();
user.setLogin(request.getParameter("login"));
String cur_Login = user.getLogin();
ps.setString(1, cur_Login);
user.setPassword(request.getParameter("password"));
String cur_Password = user.getPassword();
ps.setString(2, cur_Password);
Password = admin");
rs = ps.executeQuery();
String sn = "Zatoka";
String n = "Eugen";
String queryPeople = "SELECT ID, Surname FROM People WHERE ID = ?";
PreparedStatement psPeople = conn.prepareStatement(queryPeople);
if(rs.next()) {
int logonID = rs.getInt("ID");
psPeople.setInt(1, logonID);
rs = psPeople.executeQuery();
rs.next();
user.setSurname(rs.getString("Surname"));
FROM TLogon, People WHERE TLogon.ID = People.ID";
ctx.setAttribute("user", user);
this.forward("/successLogin.jsp", request, response);
this.forward("/registration.html", request, response);
catch(Exception exception) {
}CheckUser.java maybe incorrect, but it's not serious, because see the principe (conception).
Main is Dispatcher.java. This class is dispatcher between all servlets. -
Help With Integrating Servlet and JSP Page?
Hello There
--i made jsp page that contain name and description fields and add button
--and i made servlet that contain the code to insert name and description in the database
--and i want to make that when the user hit the add button
-->the entered name and description is sent to the servlet
and the servlet sent them to database?
here's what i 've done:
the jsp code:
<html:html locale="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
Categories Page
</title>
<html:base/>
</head>
<body style="background-color: white">
<form action="jpage.jsp" method="get">
<h1>
<center>
categories Operations
</center>
</h1>
<h3>
<label>Name</label>
<input type="text" name="name" value="" size="10" />
<label>Description</label>
<input type="text" name="description" value="" size="10" />
<input type="submit" value="Add" name="button" />
</h3>
</form>
</body>
</html:html>the servlet code:
import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.net.*;
class NewServlet1 extends HttpServlet{
Connection conn;
private ServletConfig config;
public void init(ServletConfig config)
throws ServletException{
this.config=config;
public void service (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession(true);
res.setContentType("text/html");
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/struts", "root", "");
PreparedStatement ps;
ps = conn.prepareStatement ("INSERT INTO categories (Name, Description) VALUES(?,?)");
ps.setString (1, "aa");
ps.setString (3, "bb");
ps.executeUpdate();
ps.close();
conn.close();
}catch(Exception e){ e.getMessage();}
public void destroy(){}
}The JSP Code:
<html:html locale="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
Categories Page
</title>
<html:base/>
</head>
<body style="background-color: white">
<form action="actionServlet.do?action=Additem" method="*post*">
<h1>
<center>
categories Operations
</center>
</h1>
<h3>
<label>Name</label>
<input type="text" name="name" value="" size="10" />
<label>Description</label>
<input type="text" name="description" value="" size="10" />
<input type="button" value="Submit">
</h3>
</form>
</body>
</html:html>The Servlet Code:
import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.net.*;
public class NewServlet1 extends HttpServlet implements SingleThreadModel {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
doPost(request,response);
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
String action = request.getParameter("action"); // action = "Additem"
if (action.equals("Additem")) {
String name = request.getParameter("name");
String description = request.getParameter("description");
RequestDispatcher reqDisp = null;
try{
Connection conn;
PreparedStatement ps;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/struts", "root", "");
ps = conn.prepareStatement ("INSERT INTO categories (Name, Description) VALUES(?,?)");
ps.setString (1, name);
ps.setString (3, description);
ps.executeUpdate();
ps.close();
conn.close();
reqDisp= request.getRequestDispatcher("./index.jsp");
reqDisp.forward(request, response);
catch (Exception ex){
System.out.println("Error: "+ ex);
}The web.xml code:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>NewServlet1</servlet-name>
<servlet-class>NewServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>NewServlet1</servlet-name>
<url-pattern>/NewServlet1</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>actionServlet</servlet-name>
<servlet-class>com.test.servlet.NewServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>actionServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app> -
Compiling the java file related to Servlet and Core java files in heirarchy
I am working in Jakarta-Tomcat 4.0.4 with j2sdk1.4.1_01 and i have put all servlet files in package "com.java.servlet"
and other core java files in package "com.java.action" . Also I am imorting java files in package
"com.java.action" to the package "com.java.servlet".
But when I am compiling the servlet files in package "com.java.servlet"
then the servlet files are not compiling because it cannot able to import
java files in package "com.java.action" . I have tried all the options.
If anybody has solution then please respond immediately.I agree with the previous poster, this sounds like a generic compiling problem. FYI: I do not think that packages that start with "com.java." are special or reserved in any way.
You are making a servlet, not a JSP, right? Since this is merely about compiling, you might want to re-post to "Java Programming". -
AppMod pooling with Servlets and JSPs
Issue:
I have a servlet that I need to do some work on a BC4J View Object (myVO), like set the where clause, execute, etc. I want to perform these actions in the servlet, and then forward on to a .jsp page (mypage.jsp). Then I want to use the BC4J Data Tag library to present the data. Normally, the AppMod tag would be used to get ahold of an AppMod, but in my case, I want to use the specific AppMod that I prepared inside the servlet that forwarded to mypage.jsp.
I have looked through the BC4J Data Tag library and it appears that the data tags are getting the AppMod from the page context. I looked at the AppMod tag and I couldn't see exactly where it was sticking the AppMod into the page context, but when I looked at the DataSource tag, it was retrieving the AppMod from the page context. Therefore, I am assuming the AppMod tag is sticking it into the page context.
What I would like to be able to do is perform some work on the AppMod in my servlet, then forward to a .jsp. Once in the .jsp, I would like to reference the AppMod without having to use the AppMod tag, but reference the AppMod directly from the DataSource tag. This would allow me to completely manage the AppMod interaction in my servlet, thus centralizing that logic and avoiding multiple check-ins/check-outs of the AppMod. I could also avoid using stateful management of the AppMod.
Any insights would be much appreciated!
Thx,
EricCore Servlets is pretty good. I have both parts.
One day I'm actually going to read them.you mean these two right?
Core Servlets and Javaserver Pages: Core Technologies, Vol. 2 (2nd Edition) (Core) by Marty Hall, Larry Brown, and Yaakov Chaikin
Core Servlets and JavaServer Pages, Vol. 1: Core Technologies, Second Edition by Marty Hall and Larry Brown
I should buy the Vol 1 first right? -
Connecting servlet and business logic
Hi everybody,
in a server-client like architecture im using a servlet for communication with clients over http (not for creating web pages etc).
i wrote a parser class to get messages from servlet, parse them, and perform necessary actions.
According to the message content, parser must call methods from another java application running on the same machine.
The problem is how it can do that. If only static methods were called, it would be okey, but simply i have to reach the other application from the servlet, and i want to have them decoupled as much as possible.
any suggestions?I'm trying to make a sense of what you're trying to do. You have an already existing application with already existing objs, and you're trying to make a servlet communicate with that application ?
Now, what kind of app is it ? You can instantiate any class from a servlet through a business delegate, as long as the servlet container can find the classes or the jar files (in WEB-INF/classes,WEB-INF/lib or the server's global lib directory). I think you're telling me that you can't do that for some reason(s), and that backend app has already instantiated the objs you need ?
Can you edit that backend app and add a layer that serializes these famous objs you need into .ser files ?
The servlet would then just deserialize those objs, and use them in the parser. Of course, those objs would need to be serializable, and the servlet would still need to be able to access the objs class or jar files.
There are of course other ways to communicate : XML, JNDI, etc...
If you need to start that app from the servlet on the same machine, take a look at the java RunTime and the exec() method call.
If the above does not help, I'm afraid you'll have to make your problem even clearer... -
Servlet and Database Connectivity
Hi,
I have got a basic question. I am connecting to a database through a servlet and displaying a table. What I need to do is have three buttons at the bottom of the table like "ADD", "DELETE" "MODIFY". I am wondering how I can add buttons to the HTML page through the servlet, select a row and click on one of the buttons to MODIFY/DELETE and how to capture the actions of each button when clicked like when "ADD" button is clicked it should pass control to a servlet "add.java". If i plan to include a javascript how can i call from the servlet, is there a way. If anyone could throw me some light or atleast point me in the right direction that would be great.
Thanks
Chakyou can even use buttons!
HTML:
<input type="submit" name="add" value="Add">
<input type="submit" name="modify" value="Modify">
<input type="submit" name="delete" value="Delete">
Servlet:
String addButton = req.getParameter("add");
String modifyButton = req.getParameter("modify");
String deleteButton = req.getParameter("delete");
So when the add-Button is clicked, addButton equals to "add", modifyButton==null and deleteButton==null, and vice versa -
Passing vectors into JSP from Servlet and passing data back to Servlet
I have been building an MVC application.
It has a controller which instantiates classes and evokes methods to
populate vectors. These vectors are then passed into a JSP. This part of the application works fine.
What I am having trouble with is a new JSP I have designed; this will
display the data that is actioned by the FORM action. This is actioned
based on the Search criteria entered by the user. Based on this a further vector is populated and brought back to the JSP as a vector
and this is rendered via the TABLE tag. Again this works fine.
Against each of the rows displayed, I have a print checkbox which can be checked by the user. On checking the records they want to print, they should then hint a Print button which should go back to the Servlet and print the data. THIS IS WHERE I HAVE THE PROBLEM. On going
back to the servlet the checkbox values are not displayed, rather
the values that initially populate the JSP. How do I get these new values back into the vector and hence accessible from the Servlet.
Any help with be very much appreciated.
ChrisThanks for this.
Just to clarify I am not using Struts.
What I am having difficulties with is the fact that:
I can't get the checked values back to the Servlet - they keep the values they have in the bean - so as part of instantiating the bean class I set the value of the item to 'off'. The user will then check
the checkbox which should presumbably set the value to 'on'. This isn't happening because the setter method of the bean is not evoked again
because I don't come into this JSP again - the Servlet has finished here
and now needs to print the records. It can't do this because as
far as it is concerned nothing has changed since it last passed through
the vector to the JSP.
Even when I do the following:
Enumeration paramNames = request.getParameterNames();
String param = null;
while (paramNames.hasMoreElements())
param=(String)paramNames.nextElement();
System.out.println("parameter " + param + " is " +
request.getParameter(param));
what comes back is the valus of 'off' as opposed to 'on'.
The other thing is that 'request.getParameterNames()' only works
with the first record in the vector, i.e. it doesn't fetch any other
records that are rendered in the <TABLE> tag.
In desperation is there anybody out there who can help me.
Thanks
Chris
I am going to assume you are using a MVC framework
like Struts or very similar (I am assuming that from
the language you are using).
When the servlet passes the vector back to the JSP
page and you render the HTML that is passed back the
client your Vector is gone. The Vector is not
available at the HTML level that is being viewed at
the browser.
When the user selects the checkboxes and submits the
page (by clicking the print button) the controller
servlet (called ActionServlet in Struts, yours maybe
called something else) forwards the request to the
appropriate JavaBean and Servlet to process the
request. Either the JavaBean has to recreate the
Vector (not recommended) or the processing Servlet can
(better). You can do this by recreating the Vector
from scratch for the HttpRequest parameters or, at the
time of the initial request, saving Vector to a
session and then updating with the data you get back
from the client (again from the HttpRequest
parameters).
Either way you have to work with
HttpRequest.getParameter(). -
Help needed on Servlets and JSTL
Hi
I am using tomcat 5.5 and JDK 1.5. What are the softwares I have to download for compiling servlets and creating JSTL ?. Help needed.
Thanks
IndyaRajaI tried compling servlet, but it is raising error
that coul not find package javax.servletWhat I did not mention... you need to add those JARs in the Classpath explicitly. You will find them in %TOMCAT_HOME%\common\lib. You atleast need to add servlet-api.jar to your Classpath. :) -
in use:
vRO 5.1
eclipse 3.7.2
vRo plug-sdk 5.1
steps:
1.create a plug-in project from samples(choose solar system)
2.find the dar package and upload it by vRo configuration
3.vRo configuration said upload successfully,but the solar system configuration is not properly configued..
problem:
Problem accessing /config_general/null/Default.action Reason:There is no Action mapped for namespace/ config_general and action name default
How to solve it??
Thanks so much!!There was problem from crm side...its working now..
-
Difference between servlet and filter
difference between servlet and filter
Its not a secret you know; if you just read a little about what they are used for, you answer your own question plus many more to follow.
Servlet: http://en.wikipedia.org/wiki/Java_Servlet
Filter: http://www.oracle.com/technetwork/java/filters-137243.html -
Difference between servlet and ActionServlet
Difference between servlet and ActionServlet..
Anybody replyjsf_VWP5.5.1 wrote:
Difference between servlet and ActionServlet..
Anybody replyAs their name imply, ActionServlets like outdoor activities, whereas Servlets are rather contemplative types.
The only time Servlets exhibit behavior similar to ActionServlets, in under extremely stressful situations, like when a Servlet is being chased by a pit bull. -
How to get the query values from the url in a servlet and pass them to jsp
ok..this is the situation...
all applications are routed through a login page...
so if we have a url like www.abc.com/appA/login?param1=A¶m2=B , the query string must be passed onto a servlet(which is invoked before the login page is displayed)..the servlet must process the query string and then should pass all those values(as hidden values) to the login jsp..then user enters username and pswd, then there should be another servlet which takes all the hidden values of jsp and also username and pswd, authenticates the user and sends the control back to that particular application along with the hidden values...
so i need help on how to parse the query string from the original url in the servlet, pass it out to jsp, and then pass it back to the servlet and back to the original application...damnn...any help would be greatly appreciated...thanksok..this is the situation...Sounds like you have a bad design on your hands.
You're going to send passwords in a GET request as clear text? Nice security there.
Why not start with basic security and work your way up?
%
Maybe you are looking for
-
What is the best way to upgrade a hard drive on my macbook?
How do I get the information on my current internal hard-drive onto another internal hard-drive? Thanks in advance for any and all information.
-
Minimum free space on a hard drive ...
Hello, I am trying to estimate the size of a future drive. In order to keep a hard drive functionning as fast as possible, what is the best % of free space it should always have to be able to defragment or run disk utility at their best ?? I was thin
-
Internal Keyboard is not working ocasionally.
I have a black macbook from mid 2007 that has been running fine except sometimes when I put it to sleep when I try to log back in the keyboard and trackpad are unresponsive. This has happened a few times before I had leopard installed and a couple of
-
i erased my iphone 5 from another iphone 5 ... i cant restore it now... what shall i do... i erased it via find my iphone
-
Primary Key / Foreign Key relationship
Hi Folks, I have a MASTER_TABLE which has master values . This table has two fields, STATUS & STATUS_TEXT, Key field is STATUS. This is a check table for another table INSTANCE_TABLE which also has field STATUS; this is not a key field though. The r