Method outlined is POST but is passed as a GET - java

I'm creating a very simple login page using JSP for the first time and I'm getting an error. I've specified that the form method is POST meaning the data won't be passed within the URL. However it does and the POST function isn't called. What's more is that the same page is reloaded and if I enter the data in one more time the POST function is then called and it's intended function is carried out. I don't understand.
Before filling out form
After filling out form
HTML Page:
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login page</title>
<link rel="stylesheet" type="text/css" href="css/index.css">
</head>
<body id="body">
<div id="main">
<h1 id="bruh">LOGIN</h1>
<form action="login" method="POST">
<input class = "textFields" id="tfUsername" type="text" name="username" placeholder="Username"><br>
<input class = "textFields" id="tfPassword" type="password" name ="password" placeholder="Password"><br>
<input type="submit" value="LOGIN">
</form>
<div id="bottom">
<p class="text">Not a member? Sign up now</p>
</div>
</div>
</body>
</html>
Servlet:
package com.jame;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class loginServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("this is the username: " + username);
System.out.println("this is the password: " + password);
if(username.contentEquals("test") && password.contentEquals("test")) {
res.sendRedirect("login.html");
System.out.println("login successful");
}
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>com.jame.loginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>

Fix your redirect to a JSP page instead of an HTML file. Hopefully, when your POST request is received by the Servlet, it will redirect you to a JSP page to welcome the user with its username.
Create a JSP Page (home.jsp) with the following:
<html>
<head>
<title>Your App Name</title>
</head>
<body>
<center>
<h1>Welcome!</h1>
<ul>
<li><p><b>Username: </b>
<%= request.getParameter("username")%>
</p></li>
</ul>
</body>
</html>
In your Servlet, change the redirect.
Change this:
if(username.contentEquals("test") && password.contentEquals("test")) {
res.sendRedirect("login.html");
System.out.println("login successful");
}
to:
if(username.contentEquals("test") && password.contentEquals("test")) {
res.sendRedirect("home.jsp");
System.out.println("login successful");
}

Related

Setting ArrayList as an attribute in servlet and accessing in jsp

I'm trying to set a Array list of String to an attribute of session in servlet, and try to access this Array list of Attributes in jsp.
But just one value(last value) access in jsp.
i want to access All list of attribute.
i searched too much here and there but i don't found about my question.
form jsp:
<form action="/CompleteServlet" method="get">
<%String completeTasks=((ArrayList<String>)session.getAttribute("todoList")).get(i);%>
<input type="hidden" name="completeTasks" value="<%=completeTasks%>" />
<input type="submit" value="Completed">
</form>
from CompleteServlet :
String v=req.getParameter("completeTasks");
HttpSession session=req.getSession();
ArrayList<String> arrOfCompleteTask = new ArrayList<>();
arrOfCompleteTask.add(v);
session.setAttribute("completeTasks", arrOfCompleteTask);
req.getRequestDispatcher("/complete.jsp").forward(req,resp);
form complete.jsp
<%
int size=((List<String>)session.getAttribute("tryCom")).size();
for(int i=0;i<size;i++)
{%>
<%=((List<String>)session.getAttribute("tryCom")).get(i)%>``
<%}%>
With some edits like declaring i you used in Scriptlets of form jsp could actually work but since I hear it's very not recommended I will offer another solution which is JSTL.
jsfile.jsp
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Any title</title>
</head>
<body>
<table>
<tr>
<c:forEach begin="0" end="${fn:length(completeTasks) - 1}" var="index">
<td><c:out value="${completeTasks[index]}" /></td>
</c:forEach>
</tr>
</table>
</body>
</html>
form.jsp
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form</title>
</head>
<body>
<form
action="<c:out value="${pageContext.servletContext.contextPath}" />/CompleteServlet"
method="get">
<input type="text" name="new-task" value="add new task" /> <input
type="submit" value="Completed" />
</form>
</body>
</html>
Sclass.java
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.*;
public class Sclass extends HttpServlet {
private static final long serialVersionUID = 7806370535291118571L;
public void init() throws ServletException {
// Do required initialization
System.out.println("init()");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doGet() called");
HttpSession session= request.getSession();
String submittedTask = (String) request.getParameter("new-task");
System.out.println(submittedTask);
#SuppressWarnings("unchecked")
ArrayList<String> arrOfCompleteTask = (ArrayList<String>) session.getAttribute("completeTasks");
if (arrOfCompleteTask == null)
arrOfCompleteTask = new ArrayList<>();
System.out.println(arrOfCompleteTask.size());
if (arrOfCompleteTask.size() >= 1)
{
for (int i = 0 ; i < arrOfCompleteTask.size(); ++i) {
System.out.println(arrOfCompleteTask.get(i));
}
}
if (submittedTask != null)
{
arrOfCompleteTask.add(submittedTask);
}
session.setAttribute("completeTasks", arrOfCompleteTask);
request.getRequestDispatcher("/jfile.jsp").forward(request,response);
}
public void destroy() {
System.out.println("destroy()");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>TestServlet</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>sname</servlet-name>
<servlet-class>Sclass</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sname</servlet-name>
<url-pattern>/CompleteServlet</url-pattern>
</servlet-mapping>
</web-app>
You cannot do it like this, where is "i" declared even??:
<form action="/CompleteServlet" method="get">
<%String completeTasks=((ArrayList<String>)session.getAttribute("todoList")).get(i);%>
<input type="hidden" name="completeTasks" value="<%=completeTasks%>" />
<input type="submit" value="Completed">
</form>
Scriptlets (these things: <% %>), have been discouraged against since 2010. There's a whole list of reasons why you should avoid using them when you can.
What you should to do is this:
<form action="/CompleteServlet" method="get">
<input type="hidden" name="completeTasks" value="${todoList}" />
<input type="submit" value="Completed">
</form>
And then you either get the last value for completeTasks in CompleteServlet or set the last value before you send it in the form view. The latter being the simpler option. The former involves taking the completeTasks as a String and then making it an ArrayList by splitting each value, usually with a comma. With something like this:
String v=req.getParameter("completeTasks");
ArrayList<String> myList = new ArrayList<String>(Arrays.asList(v.split(",")));

Java EE - HTTP Error 404 - resource is not available - after hitting "Submit" button on page [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
My web program will allow a user to enter first name and last name and after the user press the submit button, it will print the first name and last name.
I receive an HTTP error 404 after the user presses the "Submit" button.
Error
This is my File structure
My codes
PrintFormContent.java
package form;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
#WebServlet("/PrintFormContent")
public class PrintFormContent extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public PrintFormContent() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fname = request.getParameter("name");
String lname = request.getParameter("lname");
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>First Name</p>" + fname);
out.print("<p>Last Name</p>" + lname);
}catch(IOException e){
e.printStackTrace();
} }
}
index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<form id="PrintFormContent" name="PrintFormContent" role="form"
action="/testForm/form/PrintFormContent" method="POST">
<div class="form-group row">
<label for="fname" class="col-md-2">First Name</label>
<div class="col-md-4">
<input type="text" class="form-control" id="fname"
placeholder="Enter First Name" name="fname" />
</div>
</div>
<div class="form-group row">
<label for="lname" class="col-md-2">First Name</label>
<div class="col-md-4">
<input type="text" class="form-control" id="lname"
placeholder="Enter Last Name" name="lname" />
</div>
</div>
<div style="text-align: center;">
<button id="btn" type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>testForm</display-name>
<servlet>
<servlet-name>PrintFormContent</servlet-name>
<servlet-class>PrintFormContent</servlet-class>
</servlet>
<welcome-file-list>
<welcome-file>/testForm/program/form/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Please Help.
you declared your servlet to PrintFormContent but you send your request to /testForm/form/PrintFormContent. You need to change it in the form-declaration:
<form id="PrintFormContent" name="PrintFormContent" role="form"
action="/PrintFormContent" method="POST">
btw. don't forget to change parameter name in the servlet to fname:
String fname = request.getParameter("fname");
try to add this to web.xml, somehow your anotation seems not to work
<servlet-mapping>
<servlet-name>PrintFormContent</servlet-name>
<url-pattern>/PrintFormContent</url-pattern>
</servlet-mapping>
check this, maybe you have the same problem: webservlet-annotation-doesnt-work-with-tomcat-8

Why if I press F5 the servlet session ends?

When I login from index.jsp, I can see the confirmation saying that the login was successful but if I press the F5 button the previous session is not considered and new session is created... so I have to login again and again if I press F5...
How can I make the session persistent?
index.jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%# page session="true"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title> Practica3 </title>
<link rel="stylesheet" type="text/css" href="css/structure.css" />
<script type="text/javascript" src="jquery/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".menu").click(function(event) {
$('#content').load('Content',{content: $(this).attr('id')});
});
});
</script>
</head>
<body>
<!-- Begin Wrapper -->
<div id="wrapper">
<!-- Begin Header -->
<div id="header">
This is the Header
</div>
<!-- End Header -->
<!-- Begin Navigation -->
<div id="navigation">
<jsp:include page="menu3.jsp" />
</div>
<!-- End Navigation -->
<!-- Begin Faux Columns -->
<div id="faux">
<!-- Begin Left Column -->
<div id="leftcolumn">
</div>
<!-- End Left Column -->
<!-- Begin Content Column -->
<div id="content">
<jsp:include page="login.jsp" />
</div>
<!-- End Content Column -->
<!-- Begin Right Column -->
<div id="rightcolumn">
</div>
<!-- End Right Column -->
</div>
<!-- End Faux Columns -->
<!-- Begin Footer -->
<div id="footer">
This is the Footer
</div>
<!-- End Footer -->
</div>
<!-- End Wrapper -->
</body>
</html>
menu.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="false"%>
<script type="text/javascript">
$(document).ready(function() {
$(".menu").click(function(event) {
$('#content').load('Content',{content: $(this).attr('id')});
});
});
</script>
<%HttpSession session = request.getSession(true);
System.out.println("cargamos menu.jsp");
System.out.println(" (menu.jsp)Sesion:"+session);
System.out.println("Sesion(user):"+session.getAttribute("user"));
if ((session != null) && (session.getAttribute("user")!=null)) {
%>
<table>
<tr>
<td> <a class="menu" id="logout.jsp" href=#> Logout </a> </td>
</tr>
</table>
<% }
else {%>
<table>
<tr>
<td> <a class="menu" id="form.jsp" href=#> Registration </a> </td>
<td> <a class="menu" id="login.jsp" href=#> Login </a> </td>
</tr>
</table>
<%}; %>
login.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="models.BeanLogin" %>
<script type="text/javascript" src="jquery/jquery-1.7.1.js"></script>
<script type="text/javascript" src="jquery/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#registerForm").validate({
submitHandler: function(form) {
$('#content').load('logincontroller',$("#registerForm").serialize());
}
});
}
);
</script>
</head>
<body>
<%
BeanLogin login = null;
if (request.getAttribute("login")!=null) {
login = (BeanLogin)request.getAttribute("login");
}
else {
login = new BeanLogin();
}
%>
<form id=registerForm action="/Practica3/logincontroller" method="POST">
<table>
<tr>
<td> User id </td>
<td> <input type="text" name="user" value="<%=login.getUser() %>" id="user" class="required" minlength="5"/> </td>
<%
if ( login.getError()[0] == 1) {
%>
<td class="error"> Invalid username or password. </td>
<%
}
%>
</tr>
<tr>
<td> Password </td>
<td><input type="password" name="password" placeholder="Password"
value="<%=login.getPassword()%>" id="password" class="required" minlength="8" /></td>
</tr>
<tr>
<td> <input name="submit" type="submit" value="Enviar"> </td>
</tr>
</table>
</form>
loginOk.jsp:
<script type="text/javascript">
$(document).ready(function() {
$('#navigation').load('menu.jsp');
});
</script>
Logged in!
loginController.jsp:
/**
* Servlet implementation class logincontroller
*/
public class logincontroller extends HttpServlet {
private static final long serialVersionUID = 1L;
private static DAO Dao;
/**
* #throws Exception
* #see HttpServlet#HttpServlet()
*/
public logincontroller() throws Exception {
super();
Dao = new DAO();
// 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
BeanLogin login = new BeanLogin();
BeanUtilities.populateBean(login, request);
try {
if (login.isComplete() && checkLogin(login)) {
HttpSession session = request.getSession();
session.setAttribute("user",login.getUser());
System.out.println("Se ha hecho el login."+session.toString());
System.out.println("User:"+session.getAttribute("user"));
session.setMaxInactiveInterval(10);
RequestDispatcher dispatcher = request.getRequestDispatcher("loginOk.jsp");
if (dispatcher != null) dispatcher.forward(request, response);
} else {
request.setAttribute("login",login);
RequestDispatcher dispatcher = request.getRequestDispatcher("/login.jsp");
if (dispatcher != null) dispatcher.forward(request, response);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* #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);
}
protected boolean checkLogin(BeanLogin bean) throws SQLException{
String query = "SELECT id,password FROM ts1.users;";
ResultSet rs = Dao.executeQuerySQL(query);
while(rs.next()){
if (rs.getString(1).equals(bean.getUser()) && rs.getString(2).equals(bean.getPassword())){
return true;
}
}
int[] errors = bean.getError();
errors[0]++;
bean.setError(errors);
return false;
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Practica3</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>Content</display-name>
<servlet-name>Content</servlet-name>
<servlet-class>controllers.Content</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Content</servlet-name>
<url-pattern>/Content</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>formcontroller</display-name>
<servlet-name>formcontroller</servlet-name>
<servlet-class>controllers.formcontroller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>formcontroller</servlet-name>
<url-pattern>/formcontroller</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>logincontroller</display-name>
<servlet-name>logincontroller</servlet-name>
<servlet-class>controllers.logincontroller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>logincontroller</servlet-name>
<url-pattern>/logincontroller</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>closesession</display-name>
<servlet-name>closesession</servlet-name>
<servlet-class>controllers.closesession</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>closesession</servlet-name>
<url-pattern>/closesession</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>logoutcontroller</display-name>
<servlet-name>logoutcontroller</servlet-name>
<servlet-class>controllers.logoutcontroller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>logoutcontroller</servlet-name>
<url-pattern>/logoutcontroller</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>-1</session-timeout>
</session-config>
</web-app>
The method setMaxInactiveInterval() accepts time as seconds. You are setting the maximum inactive time for the session to 10 seconds. Set it to a time more than that.
I assume that you press F5 on the page that loginController forwards to, which is supposed to be loginOK.jsp. And you might think that you refreshed the page loginOK.jsp, which is absolutely not. In fact, you just refreshed the loginController servlet.
The reason is that in your loginController, you use forward instead redirect. The url on your browser when your loginOK.jsp shows up is still loginController instead of loginOK.jsp. When you refresh this page, loginController gets refreshed. As a result a fresh request is created for loginController, a new login object is created. When you check/validate that login object in your loginController, it will fail the check/validation. Therefore, loginController forwards to login.jsp by your else statement.
One possible solution is to use redirect instead of forward:
response.sendRedirect(...);
However, I suggest that you redesign the login flow following the MVC pattern and do not put java snippet/code in your jsp page.
Good luck.

Sign In page using SQL SERVER, JAVA, Servlets, Eclipse

Here is my code, it is connecting to database, in the console I could see the msg "connected" but the problem is after giving the user credentials it is not navigating to the next page(welcome.jsp) and it just shows a msg that "username or password error" could someone help me out
LoginServlet.java
package com.amzi.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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;
public class LoginServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String p=request.getParameter("userpass");
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://WMDENTW1\\SQLEXPRESS:1433;" +
"database=FullTextDB;" +
"user=root;" +
"password=root123";
Connection conn = DriverManager.getConnection(connectionUrl);
System.out.println("Connected.");
PreparedStatement pst = conn.prepareStatement("select User, Password from dbo.AdminLogin where User=? and Password=?");
pst.setString(1, n);
pst.setString(2, p);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
out.println("page opened");
RequestDispatcher rd=request.getRequestDispatcher("WebContent/welcome.jsp");
rd.forward(request,response);
} else {
out.print("<p style=\"color:red\">Sorry username or password error</p>");
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.include(request,response);
}
} catch (Exception e) {
e.printStackTrace();
}
out.close();
}
}
index.JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Application</title>
</head>
<body>
<form action="LoginServlet" method="post">
<fieldset style="width: 300px">
<legend> Login to App </legend>
<table>
<tr>
<td>User ID</td>
<td><input type="text" name="username" required="required" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="userpass" required="required" /></td>
</tr>
<tr>
<td><input type="submit" value="Login" /></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
Welcome.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
<h3>Login successful!!!</h3>
<h4> Hello, <%=session.getAttribute("name")%></h4>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" version="2.5"> <servlet> <servlet-name>login</servlet-name> <servlet-class>com.amzi.servlets.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>
</web-app>
In response your your request to clarify my comment, instead I shall write it as an answer.
IN your doPost method, you have this line:
PrintWriter out = response.getWriter();
After that, you use out to write directly to the response, such as in these lines:
out.println("page opened");
and
out.print("<p style=\"color:red\">Sorry username or password error</p>");
However, you then go and forward to a JSP:
RequestDispatcher rd=request.getRequestDispatcher("WebContent/welcome.jsp");
rd.forward(request,response);
But that does the same thing - after processing the JSP it sends the result to the response PrintWriter, just have you have done.
You really shouldn't do both. Just use the JSPs.
Secondly, your message 'username or password error' indicates that the query returned no rows, so the username/password you used is probably wrong. I can't see anything wrong with the JDBC code or query.

#WebServlet don't work. getting null value in getAttribute in jsp

I'm trying to set a list into request attribute to print it in the jsp file. but getAttrubute in showMentors.jsp giving null value.
is the problem is the controller or web.xml?
any help please?
I think the controller dose not working.
Controller.java
#WebServlet("/Controller")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
private static SessionFactory factory = null;
//set managers
Mentors mentorsManager = Mentors.getInstance();
public static SessionFactory getSessionFactroy() {
try{
if(factory == null)
factory = new AnnotationConfiguration().configure().buildSessionFactory();
}
catch(HibernateException e){
System.err.println(e.getMessage());
}
finally{
return factory;
}
}
/**
* #see HttpServlet#HttpServlet()
*/
public Controller() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();//writer of the response
String pathBuffer = request.getPathInfo();//the url
switch(pathBuffer){ //switch for the url
case "/showMentors":
List<Mentor> c = mentorsManager.getAllMentors();
request.getSession().setAttribute("mymentors", c); // sending the coupons that the view will use
request.getServletContext().getRequestDispatcher("showMentors.jsp").forward(request, response);
break;
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
version="3.1"
metadata-complete="false"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<display-name>WebPerachProject</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Controller</servlet-name>
<servlet-class>com.sakhnin.implementations.Controller</servlet-class>
</servlet>
<servlet>
<servlet-name>index</servlet-name>
<jsp-file>/jspFiles/index.jsp</jsp-file>
</servlet>
<servlet>
<servlet-name>Mentor</servlet-name>
<jsp-file>/jspFiles/Mentor.jsp</jsp-file>
</servlet>
<servlet>
<servlet-name>showMentors</servlet-name>
<jsp-file>/jspFiles/showMentors.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>index</servlet-name>
<url-pattern>/jspFiles/index.jsp</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>showMentors</servlet-name>
<url-pattern>/jspFiles/showMentors.jsp</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Mentor</servlet-name>
<url-pattern>/jspFiles/Mentors.jsp</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>/jspFiles/*</url-pattern>
</servlet-mapping>
</web-app>
showMentors.jsp
<%#page import="java.util.List"%>
<%# page import="com.sakhnin.classes.*"%>
<%# page import="com.sakhnin.implementations.*"%>
<%# page language="java" contentType="text/html; charset=windows-1255"
pageEncoding="windows-1255"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>All mentors</title>
<link type="text/css" rel="stylesheet" href="../styleFile/ourStyle.css" />
<link type="text/css" rel="stylesheet" href="../styleFile/bootstrap.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
</head>
<body>
<div data-role="header" data-theme="b">
<h1>Show mentors page</h1>
<div data-role="navbar">
<ul>
<li>all mentors </li>
</ul>
</div>
</div>
<!-- Display a coupons page -->
<div data-role="content" data-theme="b">
<table class="table table-hover table-striped" id="mentors" height="100%" width="100%" border="3px" bordercolor="blue">
<thead>
<tr style="color: green;">
<th>fullname</th>
</tr>
</thead>
<tbody>
aaaaaaaaaaaaaaa
hhhhhhhhhhhhhhhh
<%
// Retrieves the first page and display it
//List<Mentor> m = (List<Mentor>)request.getAttribute("mymentors");
List<Mentor> m = (List<Mentor>)request.getSession().getAttribute("mymentors");
System.out.println(m);
%>
<%
if (m!=null){
for(Mentor mentor : m) {
%>
<td>cccccccccccccccc<br>
<tr>
<td><%= mentor.getFullName()%><br>
</tr>
<% } }%>
xxxxxxxxxxxxxxxxxxxxx
</tbody>
</table>
</div>
<div data-role="footer" data-theme="b">
<h4>BY: ASEEL & REMA</h4>
</div>
</body>
</html>
First make sure the client is calling the /Controller first, not the showMentors.jsp
Check if the mentorsManager.getAllMentors(); returns a non-null value, maybe attribute mymentors is set correctly, but the content/value c is null;
And I suggest if it's a request-scope attribute, you may pass the argument/context using requests context, rather than session.

Categories