Does anyone know why I am getting a null pointer error when I call the getResultSet() method from MyServ2 class
here is my DBClass (imports etc omitted)
public DBClass(){
}
public Connection dbConnect(String db_connect_string,
String db_userid, String db_password)
{
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
conn = DriverManager.getConnection(
db_connect_string, db_userid, db_password);
return conn;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
public ResultSet getResultSet(String query){
try{
stmt = conn.createStatement();
result = stmt.executeQuery(query);
} catch(Exception e){
e.printStackTrace();
return null;
}
return result;
}
}
and this is my MyServ2 class
public class MyServ2 extends HttpServlet {
private static final long serialVersionUID = 1L;
private DBClass db;
public MyServ2() {
super();
db = new DBClass();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ResultSet rs = db.getResultSet("Select * from ....ect");
try {
while(rs.next()){
System.out.println(rs.getString(1).toString());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
You're not calling db.dbConnect(), so db.conn will be null.
Related
We need to apply version control for our API, when the user send a request to our API endpoint i.e."http://mycompany/item?version=1", it will forwarded the request to itemServer_V1.java.
To achieve this goal, we have configured our web.xml as follows.
<servlet>
<servlet-name>item</servlet-name>
<servlet-class>com.mycompany.Servlet.ItemRequestHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>item</servlet-name>
<url-pattern>/item</url-pattern>
</servlet-mapping>
We create a table in MySQL database.
database table
ItemRequestHandler is a class which extends HttpServlet, and it supposed to forward the request to ItemServiceV1 or ItemServiceV2 according to the version parameter in the request.
I have finish the ItemService class but I don't know how to forward the request from ItemRequestHandler to ItemService class. Could someone let me know how to do that please?
ItemRequestHandler class is as follows
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException , IOException
{
String version = req.getParameter("version");
String fcd = req.getParameter("fcd");
String client = req.getParameter("client");
//Find the targetClass from database using the above information.
targetClass.doGet(req, res);
}
I find out a solution.
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
System.out.println("LoginRequestHandler doPost");
String className = "";
String version = "";
String fcd = "login";
String compid = "";
RequestWrapper currentReq = new RequestWrapper(req);
version = currentReq.getParameter("Version");
compid = currentReq.getParameter("Compid ");
try {
className = findServletByVersion(compid, version, fcd);
Class<?> serviceClass = Class.forName(className);
Method method = serviceClass.getDeclaredMethod(MethodName.doPost.toString(), HttpServletRequest.class, HttpServletResponse.class);
method.invoke(serviceClass.newInstance(), currentReq, res);
return;
}catch(Exception e) {
System.out.println(e.toString());
} catch (DataNotFound e) {
System.out.println(e.toString());
}
}
}
Code of RequestWrapper
public class RequestWrapper extends HttpServletRequestWrapper {
private String _body;
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
_body = "";
BufferedReader bufferedReader = request.getReader();
String line;
while ((line = bufferedReader.readLine()) != null){
_body += line;
}
}
#Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(_body.getBytes());
return new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
}
Code of findServletByVersion
public String findServletByVersion(String compid, String version, String fcd) throws SQLException, ClassNotFoundException, DataNotFound {
String clsName = "";
Connection con = null;
Statement stmt = null;
User user = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://YourIpAddress:PortNum/"+schemaName,"account","password");
String query = "SELECT * FROM "+compid+".restfcd "
+ "WHERE 1=1 "
+ "AND compid = '"+compid+"'"
+ "AND version = '"+version+"'"
+ "AND fcd = '"+fcd+"'"
+ "ORDER BY compid desc";
System.out.println(query);
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs!=null) {
while (rs.next()) {
clsName = rs.getString("fcdcls");
}
}
if(Func.isEmpty(clsName)) {
throw new DataNotFound("findServletByVersion : no match result!");
}
return clsName;
} catch (SQLException e) {
throw new SQLException("findServletByVersion : SQLException!");
} catch (ClassNotFoundException e) {
throw new ClassNotFoundException("findServletByVersion : ClassNotFoundException!");
} finally {
try {
con.close();
stmt.close();
} catch (SQLException sqlee) {
throw new SQLException("Cannot close conection/statement!");
}
}
}
I have java class LoginValidation and Servlet Login ,am passing values from servlet to java class,but am not getting return values..from servlet to java class...
//normal java class LoginValidation
public class LoginValidation {
String userid="";
String password="";
String que="";
Connection dbConnection = null;
PreparedStatement pst=null;
ResultSet rs=null;
String userid1="";
String password1="";
int pan1=0;
public long valiDate(String userid ,String password){
long flag = 0l;
this.password=password;
this.userid=userid;
dbConnection = JDBCConnection.getDBConnection();
que="select * from shivu";
try {
pst = dbConnection.prepareStatement(que);
rs=pst.executeQuery();
while(rs.next()){
userid1=rs.getString(3);
password1=rs.getString(2);
pan1=rs.getInt(8);
if ((userid.equals(userid1)) && (password.equals(password1))){
flag = pan1;
}else{
flag = 0;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
}
//Servlet Login
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String userid=request.getParameter("userid");
String password=request.getParameter("password");
LoginValidation lv=new LoginValidation();
System.out.println("control flow");
long i=lv.valiDate(userid,password);
System.out.println(i);
if(i>=1){
System.out.println("control flow inside method call");
HttpSession session = request.getSession();
if (session != null)
session.setAttribute("pan", i);
response.sendRedirect("welcome.jsp");
}
else
{
System.out.println("Username or Password incorrect");
response.sendRedirect("login1.jsp");
}
}
}
you can print and see the values inside valiDate method.
while(rs.next()){
userid1=rs.getString(3);
password1=rs.getString(2);
pan1=rs.getInt(8);
// print userid, userid1, password, password1, pan1
if ((userid.equals(userid1)) && (password.equals(password1))){
flag = pan1;
}else{
flag = 0;
}
}
Hello all i have write this servlet to doGet data and Client-side can get some information from database after query and
pointer but when i send a pointer to servlet from client-side there
are no response and http code is 204 can any one help me with that?
thanks
//This Servlet Make User To Get Data from Database (data) Table (replay) Fileds (Callreplay,State)
package server;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
*/
#WebServlet(name = "GetStatus", urlPatterns = {"/GetStatus"})
public class GetStatus extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public GetStatus()
{
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// getting id as parameter
String strID;
strID = request.getParameter("newid");
System.out.println("* Pointer is "+strID);
// connecting to the database
GetStatusFromDB dbManager = new GetStatusFromDB();
dbManager.iniDBManagementLayer("jdbc:mysql://127.0.0.1:3306/data",
"root",
""
);
//System.out.println("** Connection with database OK!");
// getting data from the database
String sql = "SELECT * FROM replay WHERE S_id = " + strID + ";";
dbManager.setFields("status", "comment");
dbManager.sendQuery(sql);
String resp = dbManager.getJSON();
System.out.println("*** Mutaz Method Ok!");
if(resp != null)
{
System.out.println(resp);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json; charset=utf-8");
response.getWriter().print(resp);
// System.out.println("Get Ok !");
}
else
{
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
public void sendQuery(String query) {
// Connection, statement, and ResultSet should not defined as instances
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
InitialContext ctx = new InitialContext();
DataSource ds =
(DataSource)ctx.lookup("java:comp/env/jdbc/jndipool");
conn = ds.getConnection();
st = conn.prepareStatement(query);
rs = st.executeQuery();
processResults(rs);
} catch (NamingException ex) {
// Logger.getLogger(DBManagementLayer.class.getName()).log(Level.SEVERE, null, ex);
this.errorFlag = true;
this.lastError = ex.toString();
} catch (SQLException ex) {
this.errorFlag = true;
this.lastError = ex.toString();
}
finally{
if ( rs != null ) {
try { rs.close(); rs = null;}
catch (SQLException e) {
errorFlag = true; lastError = e.toString(); }
}
Http response code 204 is what is being set by this line
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
So it's likely that dbManager.getJSON() is returning null.
**in this line i most add
try
{
////here most add rs.first();
Gson conv = new Gson();
String status = rs.getString(fieldOne);
String comment = rs.getString(fieldTwo);
String rep = conv.toJson(new StatusForm(status, comment ));
this.statusAsJSON = rep;
} catch (SQLException ex) {
Logger.getLogger(GetStatusFromDB.class.getName()).log(Level.SEVERE, null, ex);
}
this must add
boolean first = rs.first();
and it will be fixed
thanks for evrey body here help me thanks for all programmers here thank you stackoberflow.com Max**
I am trying to make a simple login form. Every thing is working fine, connection is established, query is executed but ResultSet is still empty so always getting redirected to fail.jsp. No error no warning at all.
Servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String password = request.getParameter("password");
modelclass md = new modelclass();
daoclass dao = new daoclass();
md.setName(name);
md.setPassword(password);
System.out.println("this just before the sql query on the main servlet page");
String sql = "Select * from USERADD where name = ? and password= ?";
String result = dao.guser(md, sql);
if (result.equals("success")) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("fail.jsp");
}
}
This is the DAO class which makes connection.
Data Access code(dao.java):
public class daoclass {
public static String username = "NickNeo";
public static String password = "123123";
public static String driver = "com.ibm.db2.jcc.DB2Driver";
public static String url = "jdbc:db2://localhost:50000/CITYLIFE";
public static Connection con = null;
public static PreparedStatement ps = null;
static {
try {
Class.forName(driver);
System.out.println("before connection");
con = DriverManager.getConnection(url, username, password);
System.out.println("Connection Successfullll......!!!!!!");
} catch(Exception e) {
e.printStackTrace();
}
}
public String guser(modelclass obj, String sql) {
try {
System.out.println("entry into try block");
ps=con.prepareStatement(sql);
ps.setString(1, obj.getName());
ps.setString(2, obj.getPassword());
System.out.println("before query");
ResultSet rs = ps.executeQuery();
System.out.println("query executed");
int i = 0;
while(rs.next()) {
System.out.println("entered into while loop");
++i;
}
if (i >= 1) {
return "success";
} else {
System.out.println("this is inside else of while block");
return "fail";
}
} catch(Exception e) {
e.printStackTrace();
}
System.out.println("this is the most outer fail statement");
return "fail";
}
}
the rs is always empty. tried many things but still getting rs as empty. please help
I have my servlet:
public class Authentification extends HttpServlet {
public int id1;
private static final long serialVersionUID = 1L;
public HttpSession session;
Authentification_link auth=new Authentification_link();
public Integer IdUser;
public Authentification() {
super();
}
public void init() {
Codb co= new Codb();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
int IdUser = Integer.valueOf(request.getParameter("id"));
session.setAttribute("ide", IdUser);
try {
if(auth.authen(IdUser)){
session.setAttribute("id", IdUser);
request.getRequestDispatcher("acceuil.jsp").forward(request, response);
System.out.println("found");}
else{
request.getRequestDispatcher("index.jsp").forward(request, response);
System.out.println("not found");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doInteret (HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
IdUser = (Integer) session.getAttribute("IdUser");
Interets inte= new Interets (IdUser);
}
}
The user login to through an id, the authentification works fine, but now I want to get the same user's id so I can include it in this java classe when the user click on a link. For that I added the method doInteret in the servlet and the class Interet.java is like this:
public class Interets {
static Statement St ;
public ResultSet rs;
public Interets(Integer IdUser) throws SQLException, ServletException, IOException{
String res=" ";
try{
ResultSet result = St.executeQuery("SELECT description FROM interets, avoir, consomateur WHERE avoir.id_interet=interets.id_interets AND avoir.id_user=consomateur.code_bar AND consomateur.code_bar="+IdUser+"");
ResultSetMetaData resultMeta = (ResultSetMetaData) result.getMetaData();
while(result.next()){
String Newligne=System.getProperty("line.separator");
for(int i = 1; i <= resultMeta.getColumnCount(); i++){
res=res+Newligne+result.getObject(i).toString();
System.out.println(res);
}
}
}
catch (Exception e) {
System.out.println("Error in Select ");
}
}
}
but I am getting this error:
org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.NoSuchMethodError: pack1.Interets.AfficheInteret()Ljava/lang/String;
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:412)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
try changing your query and print it may be your query is not working
SELECT description FROM interets, avoir, consomateur WHERE avoir.id_interet=interets.id_interets AND avoir.id_user=consomateur.code_bar AND consomateur.code_bar='"+IdUser+"'");