I have created a servlet file 'LoginServlet.java' and a bean file 'SimpleBean.java' and placed them in a same folder.When i compiled the bean file it compiled successfully but when i compile the servlet file i get error 'cannot find symbol' and it indicates the bean class which i instantiated inside the servlet class.
LoginServlet.java
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.*;
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/writer");
PrintWriter pw = response.getWriter();
String name = request.getParameter("username");
String password = request.getParameter("password");
String code = request.getParameter("code");
SimpleBean bean = new SimpleBean();
//admin login
if (name.equals("admin") && password.equals("admin")) {
RequestDispatcher rd = request.getRequestDispatcher("adminservlet");
rd.forward(request, response);
} else { //general login
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/" + code, "root", "");
PreparedStatement pst = con.prepareStatement("SELECT * FROM demo_teacher WHERE name = ?");
pst.setString(1, name);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
HttpSession session = request.getSession(true);
session.setAttribute("user", name);
ArrayList rows = new ArrayList();
do {
List row = new ArrayList();
row.add(rs.getString("name"));
row.add(rs.getString("login_time"));
row.add(rs.getString("logout_time"));
rows.add(row);
} while (rs.next());
request.setAttribute("resultSet", rows);
RequestDispatcher rd = request.getRequestDispatcher("profile.jsp");
rd.forward(request, response);
} else {
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
SimpleBean.java
public class SimpleBean {
String name;
String loginTime;
String logoutTime;
public void setName(String n) {
name = n;
}
public void setLoginTime(String t) {
loginTime = t;
}
public void setLogoutTime(String t2) {
logoutTime = t2;
}
public String getName() {
return name;
}
public String getLoginTime() {
return loginTime;
}
public String getLogoutTime() {
return logoutTime;
}
}
Command Prompt:
Since you are compiling from the command line, review your classpath. Ensure it contains the directory where the .class files are being stored (in this case, it is the current directory):
set CLASSPATH=.;%CLASSPATH%
Related
Hello i am new to stackoverflow.Recently i developed a project with login,Registration page using java servlets and database.Yesterday my code runs with correct only(if i put wrong credentials,it shows"Data not found ,click on register")..Today i run the same code,with putting wrong credentials,it automatically login without validating.Please resolve my issues.Hereby i attached my code
MyShopDAOimplcode
package login.sg.registration;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class ShopDAOimpl implements ShopDAO {
static Connection con;
static PreparedStatement ps;
#Override
public int insertShopName(Shop s) {
int status=0;
try {
con=MyConnectionProvider.getCon();
ps=con.prepareStatement("insert into shop123 (id,shopName,password,ownerName,address) values(?,?,?,?,?)");
ps.setString(1, s.getId());
ps.setString(2, s.getShopname());
ps.setString(3, s.getPassword());
ps.setString(4, s.getName());
ps.setString(5, s.getAddress());
//System.out.println("new comment" + s.getShopname());
status=ps.executeUpdate();
System.out.println("insert ps " + ps);
con.close();
}catch(Exception e) {
System.out.println(e);
}
return status;
}
#Override
public Shop getShop(String Shopname, String pass) {
Shop s= new Shop();
try {
con=MyConnectionProvider.getCon();
//System.out.println("after connection");
ps=con.prepareStatement("select * from shop123 where shopname=? and password=?");
ps.setString(1, Shopname);
ps.setString(2, pass);
//System.out.println(ps);
System.out.println(Shopname);
ResultSet rs=ps.executeQuery();
while(rs.next()) {
s.setShopname(rs.getString(1));
s.setPassword(rs.getString(2));
s.setName(rs.getString(3));
}
}catch(Exception e) {
System.out.println(e);
}
return s;
}
}
my LoginRegister code
package login.sg.registration;
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("/LoginRegister")
public class LoginRegister extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginRegister() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ShopDAO S= new ShopDAOimpl();
String submitType=request.getParameter("submit");
if(submitType.equals("login")){
String shopName=request.getParameter("name");
// System.out.println(shopName);
String password=request.getParameter("password1");
Shop s=S.getShop(shopName, password);
System.out.println(s.getShopname()+s.getPassword());
request.setAttribute("message", s.getName());
request.getRequestDispatcher("Home.jsp").forward(request, response);
}else if(submitType.equals("register")) {
//System.out.println("register now function starts");
Shop s = new Shop();
s.setShopname(request.getParameter("shopname"));
//System.out.println("test comment " +request.getParameter("shopname"));
s.setPassword(request.getParameter("password1"));
s.setName(request.getParameter("name"));
s.setAddress(request.getParameter("address"));
s.setId(request.getParameter("id"));
request.getParameter ("password1");
S.insertShopName(s);
request.setAttribute("successMessage","Registration Sucessfull!!!...login using your credentials");
request.getRequestDispatcher("login.jsp").forward(request, response);
}else {
request.setAttribute("message","Data Not Found,click on Register !!!");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
Your code should look like this:
Shop s = S.getShop(shopName, password);
System.out.println(s.getShopname() + s.getPassword());
if (null != s.getName()) {
request.setAttribute("message", s.getName());
request.getRequestDispatcher("Home.jsp").forward(request, response);
} else {
request.setAttribute("message", "Data Not Found,click on Register !!!");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
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<>();
I'm getting the above error while using servlet I've written. the war file is set on Tomcat ver 7.0.39 installed on cPanel. the servlet compiled and tested on local machine no problem. I've learnet that there is a problem that has something to do with the cPanel/PHP config. I tried to play with the cPanel configuration but no luck
I feel that it has nothing to do with the java code but I'll put the fileUploadServlet anyhow
EDIT: I was able to upload a very small-sized file so it has something to do with file size \ long procssing time
package servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
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;
import javax.servlet.http.Part;
import convertor.TextAnalayzer;
import exception.ZoharException;
import beans.ParashaBean;
import beans.UserBean;
import jdbcHandler.JDBCZhoarHandler;
import util.ParashaName;
import util.XmlUrelParaser;
#WebServlet(urlPatterns = { "/upload" }, loadOnStartup = 1)
#MultipartConfig
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 8626646959046203428L;
private JDBCZhoarHandler appHandler = new JDBCZhoarHandler();
public static final String ERROR_PARAMETER = "error";
public static final String COMMAND_PARAMETER = "command";
public static final String USER_ATTRIBUTE = "user";
public static final String HANDLER_ATTRIBUTE = "handler";
#Override
public void init() throws ServletException {
super.init();
try {
getServletConfig().getServletContext().setAttribute("list",
appHandler.viewParashot());
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String command = request.getParameter(COMMAND_PARAMETER);
String nextPage = "/login.jsp";
if ("convert".equals(command)) {
nextPage = this.upload(request, response);
} else if ("login".equals(command)) {
nextPage = this.login(request, response);
} else {
}// do nothing!!
this.getServletConfig().getServletContext()
.getRequestDispatcher(nextPage).forward(request, response);
}
private String login(HttpServletRequest request,
HttpServletResponse response) {
String name = request.getParameter("userName");
String password = request.getParameter("password");
JDBCZhoarHandler handler = new JDBCZhoarHandler();
try {
UserBean user = handler.getUser(name, password);
HttpSession session = request.getSession(true);
session.setAttribute(HANDLER_ATTRIBUTE, handler);
session.setAttribute(USER_ATTRIBUTE, user.getId());
return "/uploadFile.jsp";
} catch (Exception e) {
request.setAttribute(ERROR_PARAMETER, e.getMessage());
return "/login.jsp";
}
}
private String upload(HttpServletRequest request,
HttpServletResponse response) {
// view artifacts
HttpSession session = request.getSession(false);
ParashaName parashaName = new ParashaName();
JDBCZhoarHandler handler = (JDBCZhoarHandler) session
.getAttribute(HANDLER_ATTRIBUTE);
List<ParashaBean> list = null;
try {
list = handler.viewParashot();
} catch (SQLException e1) {
request.setAttribute(ERROR_PARAMETER, e1.getMessage());
}
session.setAttribute("list", list);
// Processing file
if ("convert".equals(request.getParameter("command"))) {
OutputStream out = null;
InputStream filecontent = null;
try {
// Create path components to save the file
XmlUrelParaser xml = new XmlUrelParaser();
SimpleDateFormat format = new SimpleDateFormat(
"dd-MM-yy_HH-mm-ss");
final Part filePart = request.getPart("file");
if (filePart.getSize() == 0) {
throw new ZoharException("you must upload a file first");
}
final String fileName = xml.getUR("incomingFilesDir")
+ session.getAttribute(USER_ATTRIBUTE)
+ parashaName.convert(Integer.parseInt(request
.getParameter("parasha")))
+ format.format(new Date()) + ".docx";
out = new FileOutputStream(new File(fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
TextAnalayzer ta = new TextAnalayzer();
Integer ID = (Integer)session.getAttribute("user");
ta.analayze(fileName,
Integer.parseInt(request.getParameter("parasha")),
Boolean.parseBoolean(request.getParameter("orginal")),
ID);
request.setAttribute(ERROR_PARAMETER, "Upload complete");
return "/uploadFile.jsp";
} catch (Exception e) {
request.setAttribute(ERROR_PARAMETER, e.getMessage());
} finally {
try {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
} catch (IOException e) {
request.setAttribute(ERROR_PARAMETER, e.getMessage());
}
}
}
return "/login.jsp";
}
}
This is a resault of memory lack. Better memory-managing code solved the problem.
<%# page import ="java.util.*" %>
<%# page import ="book.*" %>
ArrayList movies = (ArrayList) request.getAttribute("movieinfo");
if(movies!=null){
for(int i=0;i<movies.size();i++){
movie b = (movie) movies.get(i);
out.println("<tr>");
out.println("<td>" + b.getMovieID() + "</td>");
out.println("<td>" + b.getMovieTitle() + "</td>");
out.println("<td>" + b.getReleaseDate() + "</td>");
out.println("<td>" + b.getDescription() + "</td>");
out.println("<td>" + b.getImage() + "</td>");
}
}
Hi i am trying to loop through the arraylist of movies. However i am getting an error:
movie is a java value bean
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 80 in the jsp file: /index.jsp
movie cannot be resolved to a type
77:
78: if(movies!=null){
79: for(int i=0;i<movies.size();i++){
80: movie b = (movie) movies.get(i);
81: out.println("<tr>");
82: out.println("<td>" + b.getMovieID() + "</td>");
83: out.println("<td>" + b.getMovieTitle() + "</td>");
Thanks for the help. Please let me know if i should put of additional information from other beans e.g. the utility bean
src/movie/movie.java
package movie;
import java.util.Date;
public class movie {
private int MovieID;
private String MovieTitle;
private String Description;
private String Image;
private Date ReleaseDate;
public int getMovieID() {
return MovieID;
}
public void setMovieID(int movieID) {
MovieID = movieID;
}
public String getMovieTitle() {
return MovieTitle;
}
public void setMovieTitle(String movieTitle) {
MovieTitle = movieTitle;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public Date getReleaseDate() {
return ReleaseDate;
}
public void setReleaseDate(Date releaseDate) {
ReleaseDate = releaseDate;
}
}
src/movie/MovieDB.java
package movie;
import java.sql.*;
import java.util.ArrayList;
public class MovieDB {
public ArrayList movies (String query){
ArrayList movies= new ArrayList();
try {
// step 1 : load JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
//step2 : define Connection URL
String connURL = "jdbc:mysql://localhost:3306/sp_movie?user=root&password=root";
//step3 establish connection url
Connection conn = DriverManager.getConnection(connURL);
String sql="{call "+query+"}";
CallableStatement cs=conn.prepareCall(sql);
ResultSet rs=cs.executeQuery();
while(rs.next()){
movie movies1 = new movie();
movies1.setMovieID(rs.getInt("Movie_ID"));
movies1.setMovieTitle(rs.getString("Movie_Title"));
movies1.setReleaseDate(rs.getDate("Release_Date"));
movies1.setImage(rs.getString("Image"));
movies1.setDescription(rs.getString("Description"));
movies.add(movies1);
}
} catch (Exception e){
} finally {
try {
} catch (Exception e) {}
}
return movies;
}
}
src/movie/Moviesearch.java
package movie;
import java.io.IOException;
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;
/**
* Servlet implementation class Moviesearch
*/
#WebServlet("/Moviesearch")
public class Moviesearch extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Moviesearch() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String search = (String) request.getAttribute("search");
String searchtype = (String) request.getAttribute("searchtype");
String query = null;
if (searchtype.equals("title")){
query = "titlesearch('"+search+"')";
}else if(searchtype.equals("genre")){
query = "genresearch('"+search+"')";
}else if(searchtype.equals("actor")){
query = "actorsearch('"+search+"')";
}
ArrayList movies = null;
try{
String userid = request.getParameter("userid");
MovieDB getinfo = new MovieDB();
movies = getinfo.movies(query);
request.setAttribute("movieinfo",movies);
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
} catch (Exception e){
} finally {
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Look at your movie class definition . It is packaged inside movie package.
package movie; // full class name will be movie.movie
import java.util.Date;
public class movie { ......
}
You should import the movie class as :
<%# page import ="movie.movie" %>
Even then writing Java code inside JSP is highly discouraged . Read How to avoid Java Code in JSP-Files?.
For your purpose you can use JSTL's <c:forEach> loop.
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;