Servlet-Cannot get a list in doGet methos - java

I wanted to create a servlet that shows Studentlist which is from SQL Server. However, when I click show button the server returns:
HTTP Status 500 - Cannot invoke "model.StudentList.getList()" because "list" is null
controller.StudentServlet.java
package controller;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Student;
import model.StudentList;
/**
* Servlet implementation class StudentServlet
*/
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public StudentServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
StudentList list = null;
try {
list = new StudentList();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<Student> myStudents = list.getList();
request.setAttribute("MYSTUDENTS", myStudents);
RequestDispatcher dispatcher = request.getRequestDispatcher("list.jsp");
dispatcher.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
model.StudentList.java
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class StudentList {
private static ArrayList<Student> list = new ArrayList<>();
public StudentList() throws SQLException {
Connection conn = null;
PreparedStatement p = null;
ResultSet rs = null;
String dbURL = "jdbc:sqlserver://localhost:1433;databaseName=Workshop1";
String user = "quan167";
String pass = "12345";
conn = DriverManager.getConnection(dbURL, user, pass);
int id = 0;
String name = "";
String gender = "";
String date = "";
String sql = "select * from Student";
try {
p = conn.prepareStatement(sql);
rs = p.executeQuery();
// Condition check
while (rs.next()) {
id = rs.getInt("id");
name = rs.getString("name");
gender = rs.getString("gender");
date = rs.getString("dob");
list.add(new Student(id, name, gender, date));
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
public ArrayList<Student> getList() {
return list;
}
}
and model.Student.java which has: id(int), name(String), gender(String), dob(String) stands for date of birth.
But this works out just fine in this test class
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class tst {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement p = null;
ResultSet rs = null;
String dbURL = "jdbc:sqlserver://localhost:1433;databaseName=Workshop1";
String user = "quan167";
String pass = "12345";
conn = DriverManager.getConnection(dbURL, user, pass);
StudentList list = null;
try {
list = new StudentList();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<Student> myStudents = list.getList();
System.out.println(myStudents);
}
}
Anyone knows the solution? Thank you.
Edit: I knew where the problem is. So basically I have not put the sqlijdbc4.jar in WEB-INF.lib

Change the following lines:
public class StudentList {
private static ArrayList<Student> list = new ArrayList<>();
to these lines:
public class StudentList {
public ArrayList<Student> list = new ArrayList<>();

Related

android studio (using REST API) login avd not working

now i'm making login activity using REST API.
we get column values from table in sqldeveloper.
but when I click the button(login_btn), it doesn't work.
here is the code below.
This is LoginRequest.
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class LoginRequest extends StringRequest {
final static private String URL = "http://localhost:8080/Termproject/employees";
private Map<String, String> map;
public LoginRequest(String empEml, String pass, Response.Listener<String> listener) {
super(Method.POST, URL, listener, null);
map = new HashMap<>();
map.put("EMAIL", empEml);
map.put("PASSWORD", pass);
}
#Override
protected Map<String, String>getParams() throws AuthFailureError {
return map;
}
}
And this code below is MainActivity.java.
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText inputEmail = findViewById(R.id.email_txt);
EditText inputPass = findViewById(R.id.pw_txt);
Button login_btn = findViewById(R.id.login_btn);
String InputEml = inputEmail.getText().toString();
String InputPwd = inputPass.getText().toString();
login_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject( response );
String empEml = jsonObject.getString( "EMAIL" );
String pass = jsonObject.getString( "PASSWORD" );
if(empEml.equals(inputEmail)&&pass.equals(inputPass)) {
System.out.println(empEml);
System.out.println(pass);
Intent intent = new Intent( getApplicationContext(),menu_select.class );
//intent.putExtra( "EMAIL", empEml );
//intent.putExtra( "PASSWORD", pass );
//intent.putExtra( "UserName", UserName );
startActivity( intent );
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest( InputEml, InputPwd, responseListener );
RequestQueue queue = Volley.newRequestQueue( MainActivity.this );
queue.add( loginRequest );
}
});
}
}
and this code below is servlet code to get data from table(jdbc).
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Date;
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Servlet implementation class RESTEmployees
*/
#WebServlet(description = "database employees table", urlPatterns = { "/employees" })
public class RESTEmployees extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RESTEmployees() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log("doGet");
int empNbr = getId(request);
log(String.format("EMPLOYEE_ID=%d \n", empNbr));
try {
Connection conn = getConnection();
PreparedStatement st;
if (empNbr > 0) {
st = conn.prepareStatement("select * from employees where EMPLOYEE_ID = ?");
st.setInt(1, empNbr);
} else {
st = conn.prepareStatement("select * from employees");
}
ResultSet rs = st.executeQuery();
JSONArray arr = new JSONArray();
while (rs.next()) {
JSONObject o = new JSONObject();
o.put("EMPLOYEE_ID", rs.getInt("EMPLOYEE_ID"));
o.put("FIRST_NAME", rs.getString("FIRST_NAME"));
o.put("LAST_NAME", rs.getString("LAST_NAME"));
o.put("EMAIL", rs.getString("EMAIL"));
o.put("PHONE", rs.getString("PHONE"));
o.put("HIRE_DATE", rs.getDate("HIRE_DATE")); //date type을 string으로 받아야 함
o.put("MANAGER_ID", rs.getInt("MANAGER_ID"));
o.put("JOB_TITLE", rs.getString("JOB_TITLE"));
arr.put(o);
}
rs.close();
st.close();
conn.close();
JSONObject body = new JSONObject();
body.put("DATA", arr);
log(body.toString());
PrintWriter out = response.getWriter();
out.print(body);
out.flush();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log("doPost");
try {
JSONObject obj = new JSONObject(readBody(request.getInputStream()));
String sql = "update EMPLOYEES set FIST_NAME=?, LAST_NAME=?, EMAIL =? PHONE = ? HIRE_DATE = ? JOB_TITLE = ? ROLE = ? where EMPLOYEE_ID=?";
Connection conn = getConnection();
PreparedStatement st = conn.prepareStatement(sql);
String empFNm = obj.getString("FIRST_NAME");
String empLNm = obj.getString("LAST_NAME");
String empEml = obj.getString("EMAIL");
String empPho = obj.getString("PHONE");
String hireDt = obj.getString("HIRE_DATE"); //String 타입으로 받음
String job = obj.getString("JOB_TITLE");
String role = obj.getString("ROLE");
System.out.format("Updating EMPLOYEES(%s, %s, %s, %s, %s, %s, %s)\n", empFNm, empLNm, empEml, empPho, hireDt, job, role);
st.setString(1, empFNm);
st.setString(2, empLNm);
st.setString(3, empEml);
st.setString(4, empPho);
st.setDate(5, Date.valueOf(hireDt)); //타입 date로 변환함
st.setString(6, job);
st.setString(7, role);
st.executeUpdate();
conn.close();
} catch (ClassNotFoundException | SQLException | ParseException e) {
throw new ServletException(e);
}
}
protected void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log("doPut");
try {
JSONObject obj = new JSONObject(readBody(request.getInputStream()));
System.out.println("New Employee: "+obj);
String sql = "insert into EMPLOYEES(FIRST_NAME,LAST_NAME,EMAIL, PHONE, HIRE_DATE, JOB_TITLE, ROLE) values (?, ?, ?, ?,?,?,?)";
Connection conn = getConnection();
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, obj.getString("FIRST_NAME"));
st.setString(2, obj.getString("LAST_NAME"));
st.setString(3, obj.getString("EMAIL"));
st.setString(4, obj.getString("PHONE"));
st.setString(5, obj.getString("HIRE_DATE"));
st.setDate(5, Date.valueOf("HIRE_DATE"));
st.setString(6, obj.getString("JOB_TITLE"));
st.setString(7, obj.getString("ROLE"));
st.executeUpdate();
conn.close();
} catch (ClassNotFoundException | SQLException | ParseException e) {
throw new ServletException(e);
}
}
/**
* REST API for deleting specified EMPLOYEE data
* employee number를 auto increment로 할 지 어떻게 할 지
*/
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log("doDelete");
int empNbr = getId(request);
log("DELETE: EMPLOYEE_ID = " + empNbr);
// Delete tuple from EMPLOYEE table
try {
String sql = "delete from EMPLOYOEE where EMPLOYEE_ID=?";
Connection conn = getConnection();
PreparedStatement st = conn.prepareStatement(sql);
st.setInt(1,empNbr);
st.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
/**
* Extract ID from the request URL
*
* #param request Servlet request parameter
* #return integer representation of ID in URL
*/
private int getId(HttpServletRequest request) {
String uri = request.getRequestURI();
log("Request URI:" + uri);
Pattern reId = Pattern.compile("/employees/([0-9]+)");
Matcher matcher = reId.matcher(uri);
return matcher.find() ? Integer.parseInt(matcher.group(1)) : -1;
}
/**
* Read the content of the HTTP request and convert it into a string
*
* #param is HTTP Body에 대한 InputStream
* #return String representation of the HTTP request content
* #throws IOException thrown when any error occurs while I/O operations
*/
private String readBody(InputStream is) throws IOException {
char[] buffer = new char[1024];
StringBuilder content = new StringBuilder();
Reader in = new InputStreamReader(is, StandardCharsets.UTF_8);
for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0;) {
content.append(buffer, 0, numRead);
}
System.out.println("HTTP Body: " + content.toString());
return content.toString();
}
private Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.OracleDriver");
return DriverManager.getConnection("jdbc:oracle:thin:url", "username", "userpass");
}
}
I want the code work - compare the value of EMPLOYEES table and input string, and then if the value of email and inputemail equals and the value of password and inputpassword equals, make login succeed and go to next activity(menu_select).
But when I click the login_btn, it does nothing.
What is wrong with this code?

How to insert values in database using function in java servlet and jsp

I am trying to add, update and delete using function but value is not inserted.
please help me for this. the value does not insert into database it gives error
in database values is not insert after saving the records
i have tried following code
package main;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
*
* #author abc
*/
public class TenantOperation {
private Connection conn;
public TenantOperation()
{
conn = ConnectionDb.getConnection();
}
public void addTenant(TenantClass tenantclass) {
try {
String sql = "INSERT INTO tenantmaster(flatno,ownername,contactno,flattype,buildingname) VALUES (?, ?, ?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, tenantclass.getFlatno());
ps.setString(2, tenantclass.getOwnername());
ps.setString(3, tenantclass.getMob());
ps.setString(4, tenantclass.getFlattype());
ps.setString(5, tenantclass.getBuildingname());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void removeTenant(int tenantId) {
try {
String sql = "DELETE FROM tenantmaster WHERE tenantid=?";
PreparedStatement ps = conn
.prepareStatement(sql);
ps.setInt(1, tenantId);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
Here I have accessed that addtenant(). i have connect that function in this class
package main;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author abc
*/
public class TenantHandler extends HttpServlet {
private static String insert= "/tenantadd.jsp";
private static String Edit = "/tenantadd.jsp";
private static String TenantRecords = "/tenantadd.jsp";
private TenantOperation tenantOperation;
public TenantHandler()
{
super();
tenantOperation = new TenantOperation();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String redirect="";
String flatno = request.getParameter("flatno");
String action = request.getParameter("action");
if(action.equalsIgnoreCase("insert"))
{
int no = Integer.parseInt(flatno);
TenantClass tenantclass = new TenantClass();
tenantclass.setFlatno(no);
tenantclass.setOwnername(request.getParameter("ownername"));
tenantclass.setMob(request.getParameter("mob"));
tenantclass.setFlattype(request.getParameter("flattype"));
tenantclass.setBuildingname(request.getParameter("buildingname"));
tenantOperation.addTenant(tenantclass);
redirect = TenantRecords;
// request.setAttribute("tenantList", tenantOperation.getAllTenants());
//System.out.println("Record Added Successfully");
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

How to get array of images in servlet? [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 8 years ago.
I am uploading more images using single upload button such as below code,
Updated based on Answer :
package TeachChapter;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
/**
* Servlet implementation class ImageUploadToDB
*/
#WebServlet("/ImageUploadToDB")
public class ImageUploadToDB extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ImageUploadToDB() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Entered successfully:");
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
Map<String, InputStream> fileMap = new HashMap<String, InputStream>();
if (ServletFileUpload.isMultipartContent(request)) {
// get the request content and iterate through
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (items != null) {
System.out.println("if0 successfully:");
final Iterator iter = items.iterator();
while (iter.hasNext()) {
System.out.println("while successfully:");
final FileItem item = (FileItem) iter.next();
// this is for non-file fields
if (item.isFormField()) {
System.out.println("if1 successfully:");
// logic for setting non-file fields
} else {
// item.getName() - gives file name
fileMap.put(item.getName(), item.getInputStream());
System.out.println("else successfully:");
}
}
}
}
try {
System.out.println("try connection successfully:");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
Set<String> keySet = fileMap.keySet();
for (String fileName : keySet) {
System.out.println("for successfully:");
String sql ="INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)" ;
PreparedStatement statement;
statement = con.prepareStatement(sql);
statement.setString(1, "mani");
statement.setString(2, "vasu");
statement.setBlob(3, fileMap.get(fileName));
int row = statement.executeUpdate();
System.out.println("inserted successfully:");
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("errror is:"+e);
}
}
}
OP :
Entered successfully:
try connection successfully:
I know above code totally wrong but i want to get that all uploaded images in servlet page for insert into mysql.
Please Help me out.
Had faced a similar issue - probably you could build upon it further.
This is a generic solution - where you don't know the number of attachments in the input request. It caters to a multi-part request as below.
// imports
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
// code flow
// HttpServletRequest request
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
private Map<String, InputStream> fileMap = new HashMap<String, InputStream>();
if (ServletFileUpload.isMultipartContent(request)) {
// get the request content and iterate through
items = fileUpload.parseRequest(request);
if (items != null) {
final Iterator iter = items.iterator();
while (iter.hasNext()) {
final FileItem item = (FileItem) iter.next();
// this is for non-file fields
if (item.isFormField()) {
// logic for setting non-file fields
} else {
// item.getName() - gives file name
fileMap.put(item.getName(), item.getInputStream());
}
}
}
}
//Here i will insert that images on by one to DB
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
Set<String> keySet = fileMap.keySet();
for (String fileName : keySet) {
String sql = "INSERT INTO contacts (photo) values (?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setBlob(1, fileMap.get(fileName));
int row = statement.executeUpdate();
}
fileMap will contain all the files you have sent in the request.
If you don't bother for file names, you can change the implementation from HashMap to ArrayList and modify the for loop accordingly.

I have a trouble with my Login Authentication Servlet

i have a problem with my login authentication login.jsp
I have a class UsuarioLogin:
package br.com.cad.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import br.com.cad.basica.Contato;
public class UsuarioLogin {
private Contato usuario;
public UsuarioLogin(Contato usr)
{
usuario=usr;
}
public boolean verificaLogin(){
if(usuario.getEmail()!=null && usuario.getSenha()!=null)
{
try
{
ConnectDb con = new ConnectDb();
String strsql="SELECT PF_EMAIL, PF_SENHA FROM DADOS_CADASTRO WHERE PF_EMAIL = ? and PF_SENHA = ?;";
PreparedStatement stmt = con.getConnection().prepareStatement(strsql);
stmt.setString(1, usuario.getEmail());
stmt.setString(2, usuario.getSenha());
boolean logado = false;
ResultSet rs=stmt.executeQuery();
rs.close();
stmt.close();
return logado;
}
catch (SQLException e)
{
e.printStackTrace();
return false;
}
}
return false;
}}
and my Servlet LoginAuthentication:
package br.com.cad.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import br.com.cad.basica.Contato;
import br.com.cad.dao.UsuarioLogin;
public class LoginAuthentication extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
} finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String email=request.getParameter("email");
String senha=request.getParameter("password");
RequestDispatcher rd = null;
Contato user = new Contato();
user.setEmail(email);
user.setSenha(senha);
UsuarioLogin ul = new UsuarioLogin(user);
if(ul.verificaLogin())
{
HttpSession sessao = request.getSession();
sessao.setAttribute("USER",email);
rd=request.getRequestDispatcher("logado.jsp");
rd.forward(request,response);
}
else
{
request.setAttribute("msg", "Usuário ou senha inválidos");
rd=request.getRequestDispatcher("login.jsp");
rd.forward(request,response);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
But i don't know how i got a user or password invalid if i entered a valid e-mail and pass!!! please somone can help me?
I guess the loganto is the boolean flag indicating that a user is logged in or not.
The problem in your code is that you execute the Select query but you never check if a record was found. You can do it like this:
ResultSet rs=stmt.executeQuery();
while(rs.next()){
loganto=true; //a valid record was found so return true
}
rs.close();
return loganto;

Servlets and JSP blank

hi all I've typed out a page that queries the database then inputs something into the database but when I go to load the servlet/jsp page its comes back blank and am unsure what is happening or why? I'm coding in eclipse and after looking at the console and not getting anything printing out I figured there was something wrong with my code but I cannot see the problem.
Here is my servlet
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class TutorAssign
*/
#WebServlet("/TutorAssign")
public class TutorAssign extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TutorAssign() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
private void sendBack(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
//Set data you want to send back to the request (will be forwarded to the page)
//Can set string, int, list, array etc.
String sql = "SELECT l.id,s.name,l.day,l.time,l.room" +
" FROM subject s, lab l " +
" WHERE s.user_id="+(Integer)session.getAttribute("id");
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got boobs");
System.out.println(session.getAttribute("id"));
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery(sql);
System.out.println(res);
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
if (res.next()){
do{
list1.add(res.getString(1));
list2.add(res.getString(2)+" "+res.getString(3)+" "+res.getString(4)+" "+res.getString(5));
}while(res.next());
System.out.println("Outside");
String[] arr1 = list1.toArray(new String[list1.size()]);
String[] arr2 = list2.toArray(new String[list2.size()]);
System.out.println(list1);
request.setAttribute("res1", arr1);
request.setAttribute("res2", arr2);
}
}catch (SQLException e) {
}
catch (Exception e) {
}
//Decides what page to send the request data to
RequestDispatcher view = request.getRequestDispatcher("TutorAssign.jsp");
//Forward to the page and pass the request and response information
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int user_id = Integer.parseInt(request.getParameter("id"));
int lab_id = 0;
String message = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got connection");
System.out.println(user_id);
Statement s = con.createStatement();
String sql = "INSERT INTO user_lab" +
" (user_id, lab_id)" +
" VALUES" +
" ('" + user_id + "'," +
" '" + lab_id + "')";
System.out.println(sql);
int i = s.executeUpdate(sql);
if (i==1) {
message = "Successfully assigned a tutor.";
response.sendRedirect("Lecturer_labs");
}
s.close();
con.close();
}
catch (SQLException e) {
message = "Error." + e.toString();
boolean error = true;
}
catch (Exception e) {
message = "Error." + e.toString();
boolean error = true;
}
if (message!=null) {
PrintWriter out = response.getWriter();
out.println("<B>" + message + "</B><BR>");
out.println("<HR><BR>");
}
}
// TODO Auto-generated method stub
}
I noticed that your doGet method has not been implemented.
I would assume that your sendBack code is not being called
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sendBack(request,response);
}
You have several empty catch blocks. This means that if the program encounters some problem the error will be silently swallowed and you don't know what code got executed and what code was skipped, so the outcome is unknown. At least log the error in the catch block, like this (very basic example, using java.util.logging
} catch (SQLException e) {
logger.log(Level.INFO,"SQL Error encountered",e);
} catch (Exception e) {
logger.log(Level.INFO,"Other error encountered",e);
}
Start by getting your error handling right, and study the errors the program encounters.
Aside from that problem, as the others point out your doGet isn't implemented - so if you call the page with GET it won't do anything because doGet is empty. It should do something on POST though.

Categories