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+"'");
Related
#WebServlet("/")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDAO userDAO;
public void init() {
userDAO = new UserDAO();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getServletPath();
try {
switch (action) {
case "/new":
showNewForm(request, response);
break;
case "/insert":
insertUser(request, response);
break;
case "/delete":
deleteUser(request, response);
break;
case "/edit":
showEditForm(request, response);
break;
case "/update":
updateUser(request, response);
break;
default:
listUser(request, response);
break;
}
} catch (SQLException ex) {
throw new ServletException(ex);
}
}
private void listUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException, ServletException {
List<User> listUser = userDAO.selectAllUsers();
request.setAttribute("listUser", listUser);
RequestDispatcher dispatcher = request.getRequestDispatcher("user-list.jsp");
dispatcher.forward(request, response);
}
private void showNewForm(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
dispatcher.forward(request, response);
}
private void showEditForm(HttpServletRequest request, HttpServletResponse response)
throws SQLException, ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
User existingUser = userDAO.selectUser(id);
RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
request.setAttribute("user", existingUser);
dispatcher.forward(request, response);
}
private void insertUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
String country = request.getParameter("country");
User newUser = new User(name, email, country);
userDAO.insertUser(newUser);
response.sendRedirect("list");
}
private void updateUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String email = request.getParameter("email");
String country = request.getParameter("country");
User book = new User(id, name, email, country);
userDAO.updateUser(book);
response.sendRedirect("list");
}
private void deleteUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
userDAO.deleteUser(id);
response.sendRedirect("list");
}
}
This is my servlet and I believe I am having a problem with my goPost & my doGet.
Currently, my index page is the user-list.JSP, and when I click on any of the buttons on the page to turn it into "/new" etc.
I am not able to switch to the "user-form.JSP".
I have been staring at this thing for a while and am unsure what to move on from here. I will continue to look into this problem, hopefully, I can find something wrong with the Request Dispatcher, but I am not sure.
I am getting:
HTML status report 404 - Not Found
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm having a few problems with two switches from a servlet. I'm trying to load data from those switches on a jsp but it basically just gets on the first switch and the second one isn't executed. I've tried creating only one switch but it will give me errors like Cannot forward after response has been committed and so on. Do you guys know what is the correct approach for this problem?
Thanks!
This is the code:
public class UserControllerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDao userDao;
private ReservationDao reservationDao;
private DBConnection dbConnection;
#Override
public void init() throws ServletException {
super.init();
try {
userDao = new UserDao(dbConnection);
reservationDao = new ReservationDao(dbConnection);
}catch(Exception e) {
throw new ServletException(e);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try {
// read the "command" parameter
String theCommand = request.getParameter("command");
String theCommand2 = request.getParameter("command2");
if(theCommand == null) {
theCommand = "LIST";
}
if(theCommand2 == null) {
theCommand2 = "LIST";
}
switch(theCommand2) {
case "LIST":
listReservations(request, response);
return;
case "ADD":
addReservation(request, response);
return;
case "LOAD":
loadReservation(request, response);
return;
case "UPDATE":
updateReservation(request, response);
return;
case "DELETE":
deleteReservation(request, response);
return;
default:
listReservations(request, response);
}
//route to the appropriate method
switch(theCommand) {
case "LIST":
listUsers(request, response);
break;
case "ADD":
addUser(request, response);
break;
case "LOAD":
loadUser(request, response);
break;
case "UPDATE":
updateUser(request, response);
break;
case "DELETE":
deleteUser(request, response);
break;
default:
listUsers(request, response);
}
}catch(Exception e) {
throw new ServletException(e);
}
}
private void deleteUser(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String theUserId = request.getParameter("userId");
userDao.deleteUser(theUserId);
listUsers(request, response);
}
private void updateUser(HttpServletRequest request, HttpServletResponse response)
throws Exception {
int id = Integer.parseInt(request.getParameter("userId"));
String username = request.getParameter("username");
String password = request.getParameter("password");
String role = request.getParameter("role");
String nume = request.getParameter("nume");
String prenume = request.getParameter("prenume");
String email = request.getParameter("email");
String adresa = request.getParameter("adresa");
UserBean theUser = new UserBean(id, username, password, role,nume,prenume,email,adresa);
userDao.updateUser(theUser);
listUsers(request, response);
}
private void loadUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
String theUserId = request.getParameter("userId");
UserBean theUser = userDao.getUser(theUserId);
request.setAttribute("THE_USER", theUser);
RequestDispatcher dispatcher =
request.getRequestDispatcher("/update-user-form.jsp");
dispatcher.forward(request, response);
return;
}
private void addUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
String username = request.getParameter("username");
String password = request.getParameter("password");
String role = request.getParameter("role");
String nume = request.getParameter("nume");
String prenume = request.getParameter("prenume");
String email = request.getParameter("email");
String adresa = request.getParameter("adresa");
UserBean theUser = new UserBean(username, password, role,nume,prenume,email,adresa);
userDao.addUser(theUser);
listUsers(request, response);
}
private void listUsers(HttpServletRequest request, HttpServletResponse response)
throws Exception {
List<UserBean> users = userDao.getUsers();
request.setAttribute("USER_LIST", users);
RequestDispatcher dispatcher = request.getRequestDispatcher("/list-users.jsp");
dispatcher.forward(request, response);
return;
}
//Reservations Methods
private void deleteReservation(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String theReservationId = request.getParameter("reservationId");
reservationDao.deleteReservation(theReservationId);
listReservations(request, response);
}
private void updateReservation(HttpServletRequest request, HttpServletResponse response)
throws Exception {
int idReservation = Integer.parseInt(request.getParameter("reservationId"));
int idUser = Integer.parseInt(request.getParameter("userId"));
String dataCheckin = request.getParameter("dataCheckin");
String dataCheckout = request.getParameter("dataCheckout");
int nrPersoane = Integer.parseInt(request.getParameter("nrPersoane"));
int nrCamere = Integer.parseInt(request.getParameter("nrCamere"));
ReservationBean theReservation = new ReservationBean(idReservation, idUser, dataCheckin, dataCheckout,nrPersoane,nrCamere);
reservationDao.updateReservation(theReservation);
listReservations(request, response);
}
private void loadReservation(HttpServletRequest request, HttpServletResponse response) throws Exception {
String theReservationId = request.getParameter("reservationId");
ReservationBean theReservation = reservationDao.getReservation(theReservationId);
request.setAttribute("THE_RESERVATION", theReservation);
RequestDispatcher dispatcher =
request.getRequestDispatcher("/update-reservation-form.jsp");
dispatcher.forward(request, response);
return;
}
private void addReservation(HttpServletRequest request, HttpServletResponse response) throws Exception {
int userId = Integer.parseInt(request.getParameter("userId"));
String dataCheckin = request.getParameter("dataCheckin");
String dataCheckout = request.getParameter("dataCheckout");
int nrPersoane = Integer.parseInt(request.getParameter("nrPersoane"));
int nrCamere = Integer.parseInt(request.getParameter("nrCamere"));
ReservationBean theReservation = new ReservationBean(userId, dataCheckin, dataCheckout,nrPersoane,nrCamere);
reservationDao.addReservation(theReservation);
listReservations(request, response);
}
private void listReservations(HttpServletRequest request, HttpServletResponse response)
throws Exception {
List<ReservationBean> reservations = reservationDao.getReservations();
request.setAttribute("RESERVATION_LIST", reservations);
request.getRequestDispatcher("/list-users.jsp").forward(request, response);
return;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
gets on the first switch and the second one isn't executed
Your first switch contains return statements. Change them to break statements.
switch(theCommand2) {
case "LIST":
listReservations(request, response);
break; // not return.
case "ADD":
addReservation(request, response);
break; // not return..
// ...
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;
}
}
Hi I'm writting java servlet which should get DVDs depends on which user is logged in. I have method
public List<Dvd> getDvdsByUserId(String user_id) throws SQLException {
List<Dvd> dvds = new ArrayList<Dvd>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM sedivyj_dvd where user_id = ?;");
preparedStatement.setString(1, user_id);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Dvd dvd = new Dvd();
dvd.setId(resultSet.getInt("id"));
dvd.setUser_id(resultSet.getString("user_id"));
dvd.setName(resultSet.getString("name"));
dvd.setBorrower(resultSet.getString("borrower"));
dvd.setMail(resultSet.getString("mail"));
dvd.setBorrow_date(resultSet.getString("borrow_date"));
dvd.setBorrow_until(resultSet.getString("borrow_until"));
dvds.add(dvd);
}
} catch (SQLException e) {
throw e;
} finally {
cleanUp(connection, preparedStatement);
}
return dvds;
}
and I don't know how to set up logged user id in servlet's doGet method:
dvds = this.dvdDao.getDvdsByUserId();
loginServlet
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDao userDao;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
DbSettings dbSettings = new DbSettings();
dbSettings.setServer(config.getServletContext().getInitParameter("dbServer"));
dbSettings.setPort(Integer.valueOf(config.getServletContext().getInitParameter("dbPort")));
dbSettings.setUser(config.getServletContext().getInitParameter("dbUser"));
dbSettings.setPassword(config.getServletContext().getInitParameter("dbPassword"));
dbSettings.setDatabase(config.getServletContext().getInitParameter("dbDatabase"));
try {
this.userDao = new UserDao(dbSettings);
} catch (ClassNotFoundException e) {
throw new ServletException("Unable to initialize DB driver", e);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if (getLoggedUser(request, response) != null) {
response.sendRedirect("/list");
return;
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/login.jsp");
dispatcher.forward(request, response);
} catch (Exception e) {
getServletContext().log("error", e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if (getLoggedUser(request, response) != null) {
response.sendRedirect("/list");
return;
}
String nickname = request.getParameter("nickname");
String password = request.getParameter("password");
if (nickname != null && password != null) {
User user = userDao.getByLogin(nickname);
if (user != null && UserUtil.checkLogin(user, password)) {
HttpSession session = request.getSession(true);
Long userId = user.getId();
session.setAttribute("userId", userId);
session.setAttribute("loggedUser", user);
request.getSession().setAttribute("nickname", nickname);
response.sendRedirect("/list");
} else {
request.setAttribute("message", "Login se nepovedl.");
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/login.jsp");
dispatcher.forward(request, response);
}
} else {
response.sendRedirect("/login");
}
} catch (Exception e) {
getServletContext().log("error", e);
}
}
public User getLoggedUser(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(true);
User user = (User) session.getAttribute("loggedUser");
return user;
}
}
Does anybody have an idea please?
Get Logged User Id In Servlet Using Session.
HttpSession session=request.getSession(true);
session.setAttribute("user", userLoggedId);
Later You can retrieve Session Data :
HttpSession session=request.getSession(true);
String userId=(String)session.getAttribute("user");
According to my understand of your requirement first you validate whether username and password are matching then you pass the control to the servlet so on the request set the userid .Then you can acquire the userid in the doGet() method using the request.getParameter() method.
This can be done in many ways.
I think you are using form because in servlet you are calling doget().So while calling the servlet from the form pass the userid also and in servlet you can use userid=request.getParameter("user");
The other way is to keep the user in session
After the login if you are calling any servlet or jsp page then keep the user there in session like this way
session.setAttribute("username","username");
and in the servlet you can retrieve by using
session.getAttribute("username");
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.