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
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've got an error I can't seem to correct on my own
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
if (session.getAttribute("username") != null) {
if ((boolean)session.getAttribute("usertype") == true) {
int userID = Integer.parseInt(request.getParameter("id"));
UserDAO dao = new UserDAO();
User user = dao.ReturnUserID(userID);
dao.DeleteUser(user);
dao.Close();
response.sendRedirect("/SupTracking/admin");
}
response.sendRedirect("/SupTracking/index");
}
response.sendRedirect("/SupTracking/index");
}
I get an error in the response.sendRedirect("/SupTracking/admin"), saying that I can't use sendRedirect() because response is already sent.
The error should have been pretty straightforward, except that i don't understand WHERE i have sent anything in this code...
Here is the exact stack trace :
java.lang.IllegalStateException: Impossible d''appeler "sendRedirect()" après que la réponse ait été envoyée
org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:494)
com.SupTracking.servlets.admindeluser.doGet(admindeluser.java:39)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
what am I doing wrong?
Add a return statement after each redirection. Otherwise you redirect many times if one or both if conditions are true.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
if (session.getAttribute("username") != null) {
if ((boolean)session.getAttribute("usertype") == true) {
int userID = Integer.parseInt(request.getParameter("id"));
UserDAO dao = new UserDAO();
User user = dao.ReturnUserID(userID);
dao.DeleteUser(user);
dao.Close();
response.sendRedirect("/SupTracking/admin");
return;
}
response.sendRedirect("/SupTracking/index");
return;
}
response.sendRedirect("/SupTracking/index");
}
You can only call sendRedirect once for the response object. You should change your logic so you know it will only be called once like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
if (session.getAttribute("username") != null) {
if ((boolean)session.getAttribute("usertype") == true) {
int userID = Integer.parseInt(request.getParameter("id"));
UserDAO dao = new UserDAO();
User user = dao.ReturnUserID(userID);
dao.DeleteUser(user);
dao.Close();
response.sendRedirect("/SupTracking/admin");
}
else
{
response.sendRedirect("/SupTracking/index");
}
}
else
{
response.sendRedirect("/SupTracking/index");
}
}
Your problem is:
if ((boolean)session.getAttribute("usertype") == true) {
int userID = Integer.parseInt(request.getParameter("id"));
UserDAO dao = new UserDAO();
User user = dao.ReturnUserID(userID);
dao.DeleteUser(user);
dao.Close();
response.sendRedirect("/SupTracking/admin");******Called Here**********
}
response.sendRedirect("/SupTracking/index");*******Also Called Here**********
You can't redirect multiple times the response can only redirect to one page.
Because your sendRedirect() is called many times on response object as your conditions are becoming true.
Try this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
if (session.getAttribute("username") != null) {
if ((boolean)session.getAttribute("usertype") == true) {
int userID = Integer.parseInt(request.getParameter("id"));
UserDAO dao = new UserDAO();
User user = dao.ReturnUserID(userID);
dao.DeleteUser(user);
dao.Close();
}
}
response.sendRedirect("/SupTracking/index");
}
I am working in Netbeans IDE and i have wrote JS-code for sending HTTP Request to server:
var idFilterJS;
var isIE;
var eventsTable;
var req;
function applyFilter(){
idFilterJS = getRadioValue();
var url = "http://applyfilter?action=applyfilterXML&id=" + idFilterJS;
req = initRequest();
req.open("GET", url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.onreadystatechange = applyFilterCallBack;
req.send(null);
}
function getRadioValue() {
var inputs = document.getElementsByName("filter");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
return inputs[i].value
}
}
}
function initRequest(){
if (window.XMLHttpRequest) {
if (navigator.userAgent.indexOf('MSIE') != -1){
isIE = true;
}
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
The code above, I invoke from .jsp:
<div id="filters-list">
<form name="applyfilter" action="applyfilter">
<fieldset>
<legend>Filters</legend>
<%
for (int i = 0; i < userFilters.size(); i++) {
%>
<input type="radio" name="filter"
value="<%=userFilters.get(i).getId()%>"><%=userFilters.get(i).getName()%>
<br/>
<%
}
%>
<button onclick="applyFilter();">Apply</button>
<!--<button onclick="deleteFilter();">Delete filter</button>-->
</fieldset>
</form>
</div>
This is servlet:
public class ApplyFilterServlet extends HttpServlet {
private ServletContext context;
private List<EventTransfer> eventsTransfer = null;
private HttpSession session = null;
#Override
public void init() throws ServletException {
this.context = getServletContext();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
session = request.getSession();
String action = request.getParameter("action");
Integer targetId = null;
try {
targetId = Integer.parseInt(request.getParameter("id"));
}
catch (NumberFormatException e){
context.getRequestDispatcher("/error.jsp").forward(request, response);
}
StringBuffer stringBuffer = new StringBuffer();
}
}
And web.xml for mapping:
<servlet>
<servlet-name>ApplyFilterServlet</servlet-name>
<servlet-class>controller.ApplyFilterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ApplyFilterServlet</servlet-name>
<url-pattern>/applyfilter</url-pattern>
</servlet-mapping>
Next, I had a breakpoint in ApplyFilterServlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
session = request.getSession();
String action = request.getParameter("action");
}
So, "request.getParameter("action");" returns null. Why?
You can pass any data as get-string in send method, instead of null
function applyFilter(){
idFilterJS = getRadioValue();
var url = "applyfilter";
var data = "action=applyfilterXML&id=" + idFilterJS
req = initRequest();
req.open("GET", url, true);
req.onreadystatechange = applyFilterCallBack;
req.send(data);
}
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");