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.
Related
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");
}
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(",")));
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.
I know this question has been asked a number of times and answered as well. However, I am unable to solve the problem. I have tried every possible way of mapping in web.xml. Used annotation #WebServlet also. Still I can't go to my servlet after submitting the html form. Tried changing server location as well. Kindly help.
Please find my web.xml, login page and servlet.
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Webservice</display-name>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>controller.ItemServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/ItemServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>html/Login.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>
</web-app>
<!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>Home Page</title>
<!-- <link rel="stylesheet" TYPE="text/css" href="../css/mystyle.css" ></link>
<link href='http://fonts.googleapis.com/css?family=Lily+Script+One' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="../js/Validations.js"></script>-->
</head>
<body>
<div id='header'>Online Music Store</div>
<div id='content'>
<form name="UserLogin" action="./ItemServlet?req=Login" method="post">
User Id <input type="text" name="userId" ></input>
Password<input type="password" name="password" ></input>
<input type="submit" value="Login"></input>
</form>
</div>
</body>
</html>
/**
* Servlet implementation class ItemServlet
*/
//#WebServlet("/ItemServlet")
public class ItemServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ItemServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
doPost(request,response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
CDDao daoObj= new CDDao();
if("Login".equalsIgnoreCase(request.getParameter("req")))
{
System.out.println("Inside if");
System.out.println(request.getParameter("req"));
Change your web.xml like this.
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>packagename.ItemServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/ItemServlet</url-pattern>
</servlet-mapping>
And your servlet class as
#WebServlet(name="MyServlet", urlPatterns={"/ItemServlet"})
public class ItemServlet extends HttpServlet {
Restart the server and check if there is some problem.
Also, change this line to
<form name="UserLogin" action="ItemServlet" method="post">
Problem is in this line. I believe this is your Login.html which is in html folder. When you use ./ it is a relative url which is looking for ItemServlet in location html/ItemServlet
<form name="UserLogin" action="./ItemServlet?req=Login" method="post">
I do not know your full folder structure but probably this should work for you.
<form name="UserLogin" action="../ItemServlet?req=Login" method="post">
Or provide full context
<form name="UserLogin" action="/[YOUR WEB CONTEXT]/ItemServlet?req=Login" method="post">
Below are my pages, please do help.
home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
<link type="text/css" rel="stylesheet" href="css/homepage.css">
<link type="text/css" rel="stylesheet" href="css/datepickerJqueryUI.css">
<script src="js/homepage.js"></script>
<script src="js/jquery.js"></script>
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/jquery.datepicker.min.js"></script>
<script>
$(function() {
$( "#datepickerDeparture" ).datepicker();
});
$(function() {
$( "#datepickerReturn" ).datepicker();
})
</script>
</head>
<body>
<div class="headerBackground">
<!-- Headers for Logo and menu items -->
<div class="header">
<div class="logo"></div>
<div class="menu">
Menu List Items
</div>
</div>
</div>
<!-- Division for items between the logo header and footer -->
<div class="body">
<!-- Division for search -->
<div class="searchBox" >
<form action="search" method="get" name="searchBus">
<div class="searchLeavingFrom">Leaving from : <input type="text" name="from" class="txtBox"><h6 id="leavingFrom" class="errorMsg"></h6></div>
<div class="searchGoingTo">Going To :<input type="text" name="destination" class="txtBox"><h6 id="destination" class="errorMsg"></h6></div>
<div class="searchDepartOn">Depart On:<input type = "text" name="departureDate" class="txtBox" id="datepickerDeparture"><h6 id="departure" class="errorMsg"></h6></div>
<div class="searchReturn">Return On:<input type = "text" name="returnDate" class="txtBox" id="datepickerReturn"></div>
<div><input type="button" name="search" value="Search Buses" class="searchBtn" onClick="validateForm()"></div>
</form>
</div>
</div>
<!-- Division for footer -->
<div>
</div>
</body>
</html>
web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>TicketStore</display-name>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>TicketStore</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/TicketStore-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!--- my servlet mapping if we put as .jsp it doesnt run at all i mean homepage doesnt display at all-->
</servlet>
<servlet-mapping>
<servlet-name>TicketStore</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
TicketStore-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean name="search" id="search" class="com.ticketgoose.controller.SearchDetails">
<property name="formView" value="home" />
<property name="successView" value="searchBuses" />
</bean>
<!-- Register the Customer.properties -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
SearchDetails.java
package com.ticketgoose.controller;
import com.ticketgoose.form.SearchForm;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
#Controller
#SessionAttributes
public class SearchDetails {
#RequestMapping (value = "/search", method = RequestMethod.GET)
public String addContact(#ModelAttribute("searchDetails")
SearchForm searchDetails, BindingResult result){
System.out.println("From:" + searchDetails.getFrom() +
" To:" + searchDetails.getDestination());
return "redirect:searchBus.html";
}
#RequestMapping("/searchBus")
public ModelAndView showContacts() {
return new ModelAndView("searchDetails", "command", new SearchForm());
}
}
searchBuses.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Success Page</title>
</head>
<body>
User Details
<hr>
From : ${user.name}
To : ${user.gender}
Date of jourey: ${user.country}
Return journey: ${user.aboutYou}
</body>
</html>
This is my form:
SearchForm.java
package com.ticketgoose.form;
import java.sql.Date;
public class SearchForm {
String from;
String destination;
Date departureDate;
Date returnDate;
//getter setters
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getDestination() {
return destination;
}
public void getDestination(String Destination) {
this.destination = Destination;
}
public Date getDepartureDate() {
return departureDate;
}
public void setDepartureDate(Date departureDate) {
this.departureDate = departureDate;
}
public Date getReturnDate() {
return returnDate;
}
public void setReturnDate(Date returnDate) {
this.returnDate = returnDate;
}}
Please help me solve this, I couldn't figure out the problem at all.
Is you application running under an application context on the web server?
Try this:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<form action="<c:url value="/search" />" method="get" name="searchBus">
The action of form say action="search" :
<form action="search" method="get" name="searchBus">
But, in your web.xml your mapping for spring is *.do :
<servlet-mapping>
<servlet-name>TicketStore</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Change action="search" by action="search.do"
or change the mapping by ( not recommended )
<servlet-mapping>
<servlet-name>TicketStore</servlet-name>
<url-pattern>*</url-pattern>
</servlet-mapping>