How to avoid share of variable across different user in singleton Class - java

public class CompanyServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static org.apache.log4j.Logger log = Logger.getLogger(Company.class);
/**
* This string holds the filename of the file.
*/
String fileName = null;
Details detailsById = null;
Page page = null;
String date = null;
HttpServletRequest request = null;
/**
* This holds the bytes of the file to be written .
*/
Workbook wb = null;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
The class CompanyServlet is a singleton, so the member field request is shared between users. The result is that one user could see another user's data. How to avoid this problem.

Don't keep state in servlets, keep them in the session if you need to store them somewhere.

Related

I am unable to retrieve my method in the doGet to go to my jsp files

#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

Java Servlet Switches execution order [closed]

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..
// ...

Can not refresh not managed object: com.app.restaurant.data.Country[ countryID=null ]

The image contains two methods and i want to pass an id from Country table to Province table
public class DataGeneraterServlet extends HttpServlet {
#EJB
DataGenerator gen;
EntityManager em;
private static final Logger log = Logger.getLogger(MainUtil.class.getSimpleName());
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Running Data Generator Servlet");
try
{
Country c = new Country();
Province p = new Province();
gen.addCountry();
gen.addProvince(c);
gen.addCity(p);
}
catch(Exception e)
{
log.log(Level.OFF,"Couldnt Add to database",e);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Country c = new Country(); //created a new country object but not have an id
Province p = new Province();
gen.addCountry(); //if this method returns a country object it will have an id.
gen.addProvince(c);
gen.addCity(p);
So
Country c = gen.addCountry();
Province p = gen.addProvince(c);
gen.addCity(p);
will give your expected result.
PS: You have to also refactor your EJB methods to return persisted values.

How to get url Home.jsp

When I open the page after login always Home.jsp not found, I do not know what's wrong with my script, this is my code, this is my code :
ControllerLogin :
public class LoginController extends HttpServlet {
public LoginController()
{
sandiBank = "null";
session = null;
mUserDao = new MUserDao();
sandiBIDao = new SandiBIDao();
cabangDao = new CabangDao();
parameterDao = new ParameterDao();
mAccesDao = new MAccesDao();
}
#Override
protected void doGet(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse)
throws ServletException, IOException
{
httpservletrequest.getRequestDispatcher("WEB-INF/login.jsp").forward(httpservletrequest, httpservletresponse);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String user = request.getParameter("user");
String pass = request.getParameter("pass");
MUser mUser = mUserDao.getMUser(user);
if(!mUser.isCheck())
{
RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/login.jsp");
dispatcher.forward(request, response);
} else
{
Cabang cabang = cabangDao.getSandiBank(mUser.getKdCab());
if(cabang.getSandiBank() != null)
sandiBank = cabang.getSandiBank();
RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/home.jsp");
dispatcher.include(request, response);
session = request.getSession(true);
session.setAttribute("userid", user);
session.setAttribute("passwd", pass);
String userid = (String)session.getAttribute("userid");
session.setAttribute("kdcaba", mUser.getKdCab());
session.setAttribute("sndbnk", sandiBank);
System.out.println(session.getAttribute("sndbnk"));
session.setAttribute("sandikd_bank", parameterDao.getSandiBank());
session.setMaxInactiveInterval(3600);
request.setAttribute("sandiBI", sandiBIDao.getSandiBI());
request.setAttribute("mAccesses", mAccesDao.getmAccesses(userid));
dispatcher.forward(request, response);
}
}
private static final long serialVersionUID = 1L;
private MUserDao mUserDao;
private SandiBIDao sandiBIDao;
private MAccesDao mAccesDao;
private CabangDao cabangDao;
private ParameterDao parameterDao;
private String sandiBank;
private HttpSession session;
}
Try replacing
RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/home.jsp");
by
RequestDispatcher dispatcher = request.getRequestDispatcher("home.jsp");
Because login.jsp and home.jsp are in the same directory
Try this instead <li>Home</li>
try
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/home.jsp");
"/" is interpreted as relative to the current context root.
http://www.coderanch.com/t/422371/Servlets/java/HttpServletRequest-getRequestDispatcher-behaving-strangely

RequestDispatcher.forward() to resource under “/WebContent” doesn't work

I am dispatching a request to html resource in Webcontent folder in servlet. But its not dispatching it. Even its not giving any exception. AboutUs is an html page placed in WebContent folder of project. The IDE i am using is eclipse. I am very new to web development. any help will be appreciated.
Thanks in advance.
Servlet Code:
#WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name="";
String pass="";
name=request.getParameter("param1");
pass=request.getParameter("param2");
System.out.println("Name :" +name+"PAss :"+pass);
if (name!=null && pass!=null){
List<User> please = DataAccessUtil.getByEmail(name, pass);
if (please!=null)
{
int count = please.size();
System.out.println("Record Found : " + count);
if(!(count==0))
{
Iterator<User> iterator = please.iterator();
while(iterator.hasNext())
{
User object = (User) iterator.next();
String email = object.getEmail();
HttpSession session = request.getSession();
session.setMaxInactiveInterval(60);
session.setAttribute("email", email);
}
RequestDispatcher r= request.getRequestDispatcher("/AboutUs.html");
r.forward(request, response);
log("please");
}
else{
RequestDispatcher rd= request.getRequestDispatcher("/DR.html");
rd.forward(request, response);
log("please2");
}
}
}
else{
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}

Categories