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">
Related
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'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.
This is login.jsp page
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="checklogin" method="Post">
<h2>Login tab</h2> <br>
Login id: <input type="text" name="loginid"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
This is checklogin servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out=response.getWriter();
javax.servlet.http.HttpSession session = request.getSession(true);
String username = (String)request.getParameter("loginid");
String password = (String)request.getParameter("password");
session.setAttribute("UserName", username);
if(username.equals("Prashant") && password.equals("123"))
{
response.sendRedirect("admin.jsp");
}
else
{
out.println("<h2>"+"Sharam aani chahiye account banaya nahi aur login kar rahe ho"+"<h2>");
}
}
This is my filter which is mapped in filter in we.xml as this URL /admin.jsp/*
public class adminfilter implements javax.servlet.Filter{
#Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Sawagat nahi karoge init method ka");
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("Sawagat nahi karoge doFilter method ka");
}
#Override
public void destroy() {
System.out.println("Sawagat nahi karoge destroy method ka");
}
}
This is my web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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">
<filter>
<filter-name>adminfilter</filter-name>
<filter-class>Filters_Demo.adminfilter</filter-class>
</filter>
<filter-mapping>
<filter-name>adminfilter</filter-name>
<url-pattern>/admin.jsp/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>checklogin</servlet-name>
<servlet-class>Filters_Demo.checklogin</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>checklogin</servlet-name>
<url-pattern>/checklogin</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
init() and destroy() method are running but doFilter method is not running?
In your doFilter method you should call the next filter in the chain:
chain.doFilter(request, response);
Without this your request will not be processed further after your filter.
Also,I suggest make change in web.xml file
<url-pattern>*.jsp</url-pattern>
Installation Details:
First I install the jdk then add a environment variable
variable name = "path"
variable value ="C:\Program Files\Java\jdk1.7.0_45\bin"(directory of java)
Then Extract the eclipse and tomcat
After extracting, I edit the catalina.bat from apache-tomcat-7.0.23\bin and add this:
"set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_45"
Then I made my first Servlet by creating new dynamic web project
<!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=UTF-8">
<title>Test Form</title>
</head>
<body>
<h1>JAVA TEST</h1>
<form action ="work.html" method ="get">
<input type="submit" value="login">
</form>
</body>
</html>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class work
*/
#WebServlet("/work.html")
public class work extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public work() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<html>");
out.print("<head>");
out.print("<title>Login Authentication Result</title>");
out.print("<h2>Welcome to servlet</h2>");
out.print("<p> powered by" + getServletContext().getServerInfo()+ "</p>");
out.print("</body>");
out.print("</hmtl>");
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
<?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>Test3</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>
</web-app>
I'm new to servlet. I don't know why it is always have this error when clicking the button in the index.html
I think I have the same problem
Just configure Tomcat in eclipse!
I'm trying to write a servlet using generated HTML code, rather then printing out static HTMLs.
I'm using Eclipse-EE Europa and Tomcat 6.
I tried to use the flowing tips from HERE
But instead of printing the desired attribute It seems that the jsp ignoring the attribute or the attribute is empty.
Here is the servlet:
package com.serv.pac;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* Servlet implementation class for Servlet: testServlet
*
*/
public class testServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#HttpServlet()
*/
public testServlet() {
super();
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "doGet response";
request.setAttribute("message", message);
request.getRequestDispatcher("/testServlet/WEB-INF/index1.jsp").forward(request, response);
PrintWriter out = response.getWriter();
out.println("the servlet");
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("first servlet");
}
}
Here is the JSP
<!doctype html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
And the following is the :
<?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>servlet1_test</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>index1.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>testServlet</display-name>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.serv.pac.testServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/testServlet</url-pattern>
</servlet-mapping>
</web-app>
And that is what I'm getting in the browser:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: </p>
</body>
</html>
As one may see there is nothing after the "Message" in the html body, as if the message attribute is empty.
Thank You
The only way I can see this happenning is you aren't actually accessing your Servlet.
You've declared a <welcome-file>
<welcome-file>index1.jsp</welcome-file>
So if you try to hit
localhost:8080/YourContextPath
the default Servlet will render and send you that jsp with a missing message attribute.
If you want to hit your actual Servlet, you need to use
localhost:8080/YourContextPath/testServlet
Note that you need to change
request.getRequestDispatcher("/testServlet/WEB-INF/index1.jsp").forward(request, response);
to
request.getRequestDispatcher("/WEB-INF/index1.jsp").forward(request, response);
and move your file under WEB-INF.