I have a simple JSP project, which has 3 classes, controllers and DAO's
I can Login but when I click on my buttons, I just can't get the Parameters from the form.
Lemme show the code, and maybe You'll figure it out:
package school.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import school.dao.StudentDAO;
import school.model.Student;
public class StudentController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String UPDATE = "/student.jsp";
private static String VIEW_COURSES = "CourseController";
private static String VIEW_GRADES = "GradeController";
private StudentDAO dao;
public StudentController() {
dao = new StudentDAO();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String forward = "";
String action = request.getParameter("name");
if (action.equalsIgnoreCase("update")) {
forward = UPDATE;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
} else if (action.equalsIgnoreCase("viewgrades")) {
forward = VIEW_GRADES;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
} else if (action.equalsIgnoreCase("viewcourses")) {
forward = VIEW_COURSES;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
And here's the 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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>School_JSP</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>CourseController</display-name>
<servlet-name>CourseController</servlet-name>
<servlet-class>school.controller.CourseController</servlet-class>
</servlet>
<servlet>
<description></description>
<display-name>StudentController</display-name>
<servlet-name>StudentController</servlet-name>
<servlet-class>school.controller.StudentController</servlet-class>
</servlet>
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>school.controller.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentController</servlet-name>
<url-pattern>/StudentController</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CourseController</servlet-name>
<url-pattern>/CourseController</url-pattern>
</servlet-mapping>
</web-app>
And the mainPage.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Main Page</title>
</head>
<body>
<h3>
Welcome,
<c:out value="${student.firstName}" />
</br>
<h1>My Personal Information</h1>
<center>
<form method="POST" action='StudentController' name="viewgrades">
<input type="submit" value="View My Grades" />
</form>
<form method="POST" action='StudentController' name="viewcourses">
<input type="submit" id="hidden" value="View My Courses" />
</form>
<form method="POST" action='StudentController' name="update">
<input type="submit" id="hidden" value="Update Personal Information" />
</form>
</center>
</h3>
</body>
</html>
You're confusing attributes and parameters.
Parameters are String values sent by the browser. They're accessed using the getParameterXxx() family of methods.
Attributes are data that you can add to a request (or session, or servlet context), or any type, in order to get them backlater. You typically add an attribute to the request in a servlet (for example, the information about the logged in user) in order to get back this attribute in the JSP and display the information.
In your code, the only place where you get a parameter is commented out. And you're trying to get a parameter named "hidden", although none of the form has an input field with than name. It's the name attribute of an input field that is submitted by the browser, and not its id attribute.
Also, you should use GET rather than POST for actions which consist in getting or reading things.
The reason you don't get any values is that the attribute "name" in the form, indeed is just the name of the form and isn't sent at all.
To actually send data, you need to provide some in the innerHTML of the form. Like this (not the best solution, but should you get running):
<form method="GET" action="StudentController" name="formName">
<input type="hidden" name="viewgrades" value="show" />
<input type="submit" value="View My Grades" />
</form>
After this you can read the sent data "viewgrades=show" (parameter=value) in your Java-class.
Also, btw, you shouldn't use "h3" as a paragraph ("p") or section. It is intended to be a headline.
Related
Problem: When I invoke url (url-mapping) directly in the browser it works pretty well but when I use post method to invoke servlet from jsp file, it does not work but gives an error:
Type Status Report
Message /HelloWorld/myservlet
Description The origin server did not find a current representation
for the target resource or is not willing to disclose that one exists.
Jsp page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Hello World</title>
</head>
<body>
<form method="post" action="myservlet">
<input type="submit" value ="send">
</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://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/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>helloworld2</display-name>
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>apress.helloworld.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Servlet code:
package apress.helloworld;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorld extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
//System.out.println("Get Method Called");
try { response.setContentType("text/html");
`enter code here` PrintWriter printwriter = response.getWriter();
printwriter.println("<h2>");
printwriter.println("Hello World");
printwriter.println("</h2>");
}
catch
(IOException ex)
{ ex.printStackTrace(); }
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
try { resp.setContentType("text/html");
PrintWriter printwriter = resp.getWriter();
printwriter.println("<h2>");
printwriter.println("Hello World");
printwriter.println("</h2>");
}
catch
(IOException ex)
{ ex.printStackTrace(); }
}
}
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Hello World</title>
</head>
<body>
<form method="post" action="hello">
<input type="submit" value ="send">
</form>
</body>
</html>
use Above code
in HTML form action="url-mapping" you have to mention url pattern of servlet not servlet name refer your web.xml
I have a servlet, a filter and a login.jsp. I fill the username and pasword and then click the login button and the filter isn't called, only the servlet is called. The servlet and filter are in different packages and I see this is the problem. If I put servlet and filter in the same package the filter is called successfully. But I want to use them in different packages. What should I do? Thanks in advance!
Filter:
package log.reg.myfilter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
#WebFilter("/LoginFilter")
public class LoginFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
HttpServletRequest req = (HttpServletRequest) request;
String username = req.getParameter("username");
String pass = req.getParameter("password1");
System.out.println(username);
if ((username.length() > 6) && (pass.length() > 3)) {
System.out.println("In filter");
chain.doFilter(request, response);
}
else
out.println("Invalid Input");
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
Servlet:
package log.reg;
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;
#WebServlet("/firstServlet")
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("In servlet");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
out.println("Welcome " + username);
}
}
login.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>
</head>
<body>
<form action="firstServlet" method="get">
<table style="background-color: lightgreen; margin-left: 20px; margin-top: 20px">
<tr>
<td>
<h3 style="color: red">Login Page!!!</h3>
</td>
</tr>
<tr>
<td>UserName : </td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password : </td>
<td><input type="password" name="password1"></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="login"></td>
</tr>
</table>
</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>Servlet ex29 - filter</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>
The value() of #WebServlet and #WebFilter don't have the same meaning.
The first one specifies the URL patterns of the servlet (that is its URL mapping) while the second one specifies the URL patterns to which the filter applies.
But in both cases you specified as name the simple name of the underlying class.
For the servlet, #WebServlet("/firstServlet") makes sense but annotating your Filter with #WebFilter("/LoginFilter") is not what you are looking for as
you don't want to filter only the "/LoginFilter" URL.
For example to filter any requested URL you could specify :
#WebFilter("/*")
A Servlet filter is an object that can intercept HTTP requests targeted at your web application. As I see here, you have not associated filter with servlet. You have to tell the url pattern you want to intercept/filter.
Note: Filter won't be executed independently it works with
Servlet. So You have to associated Filter with Servlets.
If you have to associate with FirstServlet then use below one.
#WebFilter("/firstServlet")
If you want to filter each request you can use /*
#WebFilter("/*")
I am learning Java CRUD Operation . I am trying to insert ,update and delete records from sql database.The insert and displaying all records methods is working but the problem is when I click edit and delete links ,its throw http 404 not found exception
Here is my HTML code display all the records .
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Posts</title>
</head>
<body>
<div style="width: 1200px; margin-left: auto; margin-right: auto;">
<table cellpadding="10">
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Detail</th>
<th>Category</th>
<th>Date</th>
<th>Image</th>
<th></th>
</tr>
<c:forEach items="${AllPost}" var="p">
<tr>
<td>${p.id}</td>
<td>${p.title}...</td>
<td>${p.description}...</td>
<td>${p.detail}...</td>
<td>${p.category}</td>
<td>${p.date}...</td>
<td>${p.image}...</td>
<td>
Edit
Delete
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
Here is the HTML for EidtPost.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Edit</title>
</head>
<body>
<h1>Edit News</h1>
<div style="width: 900px; margin-left: auto; margin-right: auto">
<c:forEach items="${getNewsById}" var="p">
<form action="JSP/ManagerEditPost.jsp" method="post">
<input type="hidden" name="id" value="${p.id}">
Title:<br>
<input type="text" value="${p.title}" name="title" style="width: 200px"><br>
Description:<br>
<input type="text" value="${p.description}" name="description" style="width: 200px"><br>
Detail:<br>
<textarea name="detail" style="width: 400px; height: 200px">${p.detail}</textarea><br>
Category:
<select name="category">
<option value="${p.category}">${p.category}</option>
<option value="World">World</option>
<option value="Tech">Tech</option>
<option value="Sport">Sport</option>
</select><br>
Image:<br>
<input type="text" value="${p.image}" name="image" style="width: 200px"><br>
<input type="submit" value="Submit">
</form>
</c:forEach>
</div>
</body>
</html>
Here is the Data Access code for CRUD operation.
public void edit(int id, String title, String description, String detail, String category, String image){
try {
String sql = "update News SET title = ?, description = ?, detail = ?, category = ?, image = ?" + " where id = ?";
PreparedStatement ps= DBUtils.getPreparedStatement(sql);
ps.setString(1, title);
ps.setString(2, description);
ps.setString(3, detail);
ps.setString(4, category);
ps.setString(5, image);
ps.setInt(6, id);
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Here is the servlet code .
#WebServlet(name = "EditPost", urlPatterns = {"/EditPost"})
public class EditPost extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
{
String idTemp = request.getParameter("id");
int id = Integer.parseInt(idTemp);
request.setAttribute("getNewsById", DataAccess.getNewById(id));
RequestDispatcher rd = request.getRequestDispatcher("CRUD/EditPost.jsp");
try {
rd.forward(request, response);
} catch (ServletException | IOException ex) {
Logger.getLogger(EditPost.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is the code web.xml
<?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">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>EditPost</servlet-name>
<servlet-class>servlet.EditPost</servlet-class>
</servlet>
<servlet>
<servlet-name>DeletePost</servlet-name>
<servlet-class>servlet.DeletePost</servlet-class>
</servlet>
<servlet>
<servlet-name>AllPost</servlet-name>
<servlet-class>servlet.AllPost</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>EditPost</servlet-name>
<url-pattern>/EditPost</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DeletePost</servlet-name>
<url-pattern>/DeletePost</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AllPost</servlet-name>
<url-pattern>/AllPost</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
Here is the screen shot of the error when i click the edit and delete link .
The following shows the minimum necessary to create the desired functionality. Obviously everything about the true implementation needs to be added.
Ultimately, the path in the .jsp needs to match to the #WebServlet path. Though the specific forwarding depends a bit on absolute vs. relative URLs.
This works in tomcat 9.0, but is likely applicable to other such servers such as glassfish, etc.
web.xml
This provides the basic information.
<web-app>
<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>
</web-app>
welcome.jsp
This is just an example .jsp that provides an href.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hello World!</h1>
<!-- note this can also be ./EditPost -->
<!-- also note that not passing any query here -->
Edit Post
</body>
</html>
EditPost.java
This is a quick example of an annotated servlet.
#WebServlet("/EditPost")
public class EditPost extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public EditPost() {
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I'm trying to build a twitter search using jsp, servlet, Tomcat-6.0.43 and eclipse and getting HTTP Status 404 error. Can anyone please check where am I going wrong.
My Code:
first.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>
</head>
<body>
<form action="ServletValues.java" method="get">
Enter Twitter Search Details : <input type="text" name="first"><br>
<input type="submit">
</form>
</body>
</html>
TwitterServlet.java:
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
public class TwitterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public TwitterServlet() {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String CONSUMER_KEY = "[data]";
String CONSUMER_KEY_SECRET = "[data]";
String AccessToken = "[data]";
String AccessTokenSecret = "[data]";
response.setContentType("text/html");
String input1 = request.getParameter("first");
try{
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
AccessToken oathAccessToken = new AccessToken(AccessToken, AccessTokenSecret);
twitter.setOAuthAccessToken(oathAccessToken);
List<Status> status = twitter.getUserTimeline(input1);
for (Status status2 : status)
{
System.out.println("---Tweet---"+status2.getText());
}}catch (TwitterException te){
System.out.println("Error occured "+te);
}
super.doPost(request, response);
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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>
Twitter12</display-name>
<servlet>
<description>
</description>
<display-name>
TwitterServlet</display-name>
<servlet-name>TwitterServlet</servlet-name>
<servlet-class>
TwitterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TwitterServlet</servlet-name>
<url-pattern>/TwitterServlet</url-pattern>
</servlet-mapping>
<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>
Error: HTTP Status 404 - /Twitter12/ServletValues.java
type Status report
message /Twitter12/ServletValues.java
description The requested resource is not available.
In your jsp file form action, Replace
<form action="ServletValues.java" method="get">
With
<form action="TwitterServlet" method="get">
Since in your web.xml your servlet mapping pattern is TwitterServlet for the Servlet class that you intend to call.
Also in your servlet you are just printing to System.out while you should write into the reponse stream using
response.getOutputStream().write("---Tweet---"+status2.getText());
so that it shows up in the response
Change your form action to:
<form action="/TwitterServlet" method="get">
your servlet url is /TwitterServlet as you have defined
<servlet-mapping>
<servlet-name>TwitterServlet</servlet-name>
<url-pattern>/TwitterServlet</url-pattern>
</servlet-mapping>
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 7 years ago.
As new to the jsp and servlet and only having basic idea of it and still learning .I want to know how can we call the servlet class on that button click.I m using button in place of submit button
Here is the page content:-
<%# 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>JSON DATA EXAMPLE</title>
<script type="text/javascript">
function callservlet() {
var servletname=document.getdata.fetchdata.value;
if(servletname== "")
{
alert("NO value..");
return false;
}
else
{
alert("value"+servletname);
document.location.href="JsonServlet";
return false;
}
}
</script>
</head>
<body>
<div>
<form name="getdata" action="JsonServlet" method="post">
<input type="button" name="fetchdata" value="CLick to get data" onclick="return callservlet();">
</form>
</div>
</body>
</html>
and here the servlet class content
public class JsonServlet extends HttpServlet
{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
JsonParser parser=new JsonParser();
if(req.getParameter("fetchdata")!=null)
{
System.out.println("Button Clicked");
}
else
{
System.out.println("Button not clicked");
}
}
}
and here is the web.xml part
<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>JsonDataExample</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jsonfetch</servlet-name>
<servlet-class>com.text.JsonServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Jsonfetch</servlet-name>
<url-pattern>/JsonServlet</url-pattern>
</servlet-mapping>
</web-app>
so is there any part i m write the method wrong because its gives me 404 error resource not found
so i want the concept that on that button click how can i call my servlet class.Thanks for any reply
try this :
function callservlet() {
var servletname=document.getdata.fetchdata.value;
if(servletname== "")
{
alert("NO value..");
return false;
}
else
{
alert("value"+servletname);
document.forms[0].action = "JsonServlet"
document.forms[0].submit();
}
}
You can't set the location to a servlet. Instead, what you should do to hit the servlet is to submit your form:
function callservlet() {
//do your processing.
document.getElementsByName('getdata')[0].submit();
}
Or you can simply use a submit type button.
You just need to submit your form - (Instead of document.location.href="JsonServlet";)
document.getElementByName('getdata').submit();
I want to know how can we call the servlet class on that button
click.I m using button in place of submit button
You don't need js here, you can do it with the existing form itself. Replace the input tag as follows:
<input type="submit" name="fetchdata" value="CLick to get data" />
If you still want to use js, try below script instead:
function callservlet() {
document.forms.getdata.submit();
}