#WebInitParam value is null in JSP - java

I have a simple servlet using annotations, all I want to do is to set initial values using servlet initialization parameters.
SimpleServlet.java
#WebServlet(
description = "A simple servlet",
urlPatterns = {
"/SimpleServlet"
}, loadOnStartup=1, initParams = {
#WebInitParam(name="maximum", value="1000")
})
public class SimpleServlet extends HttpServlet {
#Override
public void init(ServletConfig config) {
System.out.println(config.getInitParameter("maximum"));
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
index.jsp
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%
out.print(config.getInitParameter("maximum"));
%>
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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>Simple Servlet</display-name>
</web-app>
The init method prints 1000 which is correct. But the index.jsp prints null.
Can you tell me what's wrong in this code?

The #WebInitParam will init a param for this servlet. So when you access to this servlet you have the param value but when you directly access to your jsp the value is null.
So you should access your jsp page through your servlet by hitting the url /SimpleServlet. This will help you:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/index.jsp").forward(request,response);
}

Related

Http status 500 Error instantiating servlet class [duplicate]

This question already has answers here:
How do I import the javax.servlet / jakarta.servlet API in my Eclipse project?
(16 answers)
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 1 year ago.
I'm using Tomcat8 server and i'm getting following error.
It's url is http://localhost:8080/WeatherWebApp When i'm submitting the details then it's giving this error.
Here is WeatherServlet.java class
package org.akshayrahar;
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 WeatherServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
WeatherServlet(){
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("again");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("akshay rahar");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Here is web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<web-app 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">
<display-name>WeatherWebApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>WeatherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/CurrentWeather</url-pattern>
</servlet-mapping>
</web-app>
Here is index.html file too:-
<!DOCTYPE html>
<html>
<head>
<title>Weather App</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script >
function initMap() {
var input =document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyACZhmkSaIz436Dt3kHt_cVEYKN-gHzfYo&libraries=places&callback=initMap"async defer></script>
</head>
<body>
<h1>Find weather of any city in the world</h1>
<h2>Enter City Name</h2>
<form id="form" action="CurrentWeather" method="GET">
<input id="pac-input" type="text" name="cityname">
</form><br>
<div class="button1">
<button type="submit" form="form" value="Submit">Submit</button>
</div>
</body>
</html>
I've also mentioned stylesheet.css file in comment. Please check it.
The error shows that Tomcat is unable to create an instance of your WeatherServlet class.
You should make its constructor and other methods public too. You can even make use of the default constructor by removing the less accessible constructor:
public class WeatherServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public WeatherServlet(){
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("again");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("akshay rahar");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Please provide a fully qualified class name on your web.xml. I was facing a similar issue and this is what fixed it.
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>org.akshayrahar.WeatherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/CurrentWeather</url-pattern>
</servlet-mapping>

Cannot send ajax post request to Servlet

Here is my code.,
Javascript
$(document).ready(function()
{
$("button").click(function(){
$.post("AjaxpostloginServlet.java",
{
name:"kevin",
pass:"Duckburg"
});
});
});
Java servlet
package com.iappuniverse.ajaxpostlogin;
import java.io.IOException;
import javax.servlet.http.*;
#SuppressWarnings("serial")
public class AjaxpostloginServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException
{
String name=req.getParameter("name");
System.out.println(name);
}
}
The name here in the servlet doesn't get printed in the console. Trying to send data to the server using ajax .post(), but cannot make the servlet linked to the ajax .post() call run.
Change your web.xml to something like the below
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app 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"
version="2.4">
<display-name>Application</display-name>
<description>
Description Example.
</description>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>AjaxpostloginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
lets take it a step further and change your servlet post method
public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException {
String name=req.getParameter("name");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(name);
}
finally change the url of the ajax call and use a callback function.
$(document).ready(function() {
$("button").click(function() {
$.post("login",{
name:"kevin",
pass:"Duckburg"
}).done(function( data ) {
alert( "name: " + data );
})
});
});
Disclaimer:
I haven't test it!

404 error while running jsp

Hi I am receiving the 404 HTTP status while submiting the below jsp.
HTTP Status 404 - /TestServlet1
Could you please help me to resolve this error
Note : The person and the dog class were defined
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
<body>
<form id="a" action="/TestServlet1">
<input type="submit">
</form>
<%
%>
Name = '${person.name}'
Dog = '${person.dog.name}'
</body>
</html>
TestServlet1
package test;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 TestServlet
*/
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TestServlet() {
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
Dog g = new Dog();
g.setName("dogeee");
Person p = new Person();
p.setDog(g);
p.setName("xxx");
request.setAttribute("person", p);
RequestDispatcher dispatch = request.getRequestDispatcher("/index.jsp");
dispatch.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
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" 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>GlobalWeather</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>test.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet1</url-pattern>
</servlet-mapping>
</web-app>
First and Third answers are right. Either write action="TestServlet1" or action="/Projectname/TestServlet1". If you put /testServet1 in action, it means you are specifying the path the desired file which in this case is wrong while if you use testservlet1 in action , it means you are searching for a file name testservlet1 in your project to run.
404 means that the URL was not found. I suspect that you need the web application name in your URL.
So rather than using a form action of:
/TestServlet1,
try
/name_of_your_web_app/TestServlet1
Just remove tha / in your form action:
<form id="a" action="/TestServlet1">
change it to
<form id="a" action="TestServlet1">
In HTML, adding a / means the relative URL and without a slash means absolute URL. Or better to use the context as mentioned here:
<form id="a" action=${pageContext.request.contextPath}/TestServlet1>
you have to put your contextroot + your servlet name...
contextRoot usually is the name of your project.
action="/nameProject/TestServlet1"
I hope this helps you

How to access index page?

I'm new in the servlets thing, and I've seen that there's a lot of code that explains how to make a complete road through the request-response of the servlet, but most of cases they use the response.getWritter().println("something"), but, I've seen that there's another ways to generate html content, like the index page that should charge by default when the servlet is accessed. I have a basic example of a servlet and the web.xml, I want to know if you can help me to understand what I can do to make the index.html show when I type localhost:8280/persistence-with-jdbc2/...
this is the basic of the servlet:
#WebServlet(urlPatterns = "/PersistenceWithJDBCServlet2")
public class PersistenceWithJDBCServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER =
LoggerFactory.getLogger(PersistenceWithJDBCServlet2.class);
private PersonDAO personDAO;
#Override
public void init() throws ServletException {
System.out.println("init");
}
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//What can I use here?
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
// test code
} catch (Exception e) {
response.getWriter().println(
"Persistence operation failed with reason: "
+ e.getMessage());
LOGGER.error("Persistence operation failed", e);
}
}
}
and the web.xml content:
<?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>persistence-with-jdbc2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>PersistenceWithJDBCServlet2</display-name>
<servlet-name>PersistenceWithJDBCServlet2</servlet-name>
<servlet-class>com.sap.cloud.sample.persistence.PersistenceWithJDBCServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PersistenceWithJDBCServlet2</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<resource-ref>
<res-ref-name>jdbc/DefaultDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
</resource-ref>
</web-app>
Thanks for your time!
You can just redirect it to what ever webadress you want.
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("/yourwebAdress/index.html");
}
I thing you are creating the index page like index.jsp and put this following sample code like as:
<body>
<jsp:forward page="/UserController?action=listUser" />
</body>
And call this index page in the web.xml page, like
<display-name>Simple1</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>UserController</display-name>
<servlet-name>UserController</servlet-name>
<servlet-class>com.pro3.controller.UserController</servlet-class>
</servlet>
And add this one in controller page:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String forward="";
String action = request.getParameter("action");

I am new to jsp and google app engine getting this error: HTTP method GET is not supported by this URL

This is my JSP File. It has 3 text fields and a submit button..
<%# 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="buttontoserv" method="post">
<input type="text" name="name"/><br>
<input type="text" name="group"/>
<input type="text" name="pass"/>
<input type="submit" value="submit">
</form>
</body>
</html>
This is my 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" version="2.5">
<servlet>
<servlet-name>ButtontoServ</servlet-name>
<servlet-class>pack.exp.ButtontoServServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ButtontoServ</servlet-name>
<url-pattern>/buttontoserv</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
This is the servlet under pack.exp package with file name ButtontoServServlet.java
package pack.exp;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
#SuppressWarnings("serial")
public class ButtontoServServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String name = request.getParameter("name");
String group = request.getParameter("group");
String pass = request.getParameter("pass");
System.out.println("Name :"+ name);
System.out.println("group :"+ group);
System.out.println("pass :"+ pass);
}
}
When I am deploying it to the google app engineit is throwing this error
"Error: HTTP method GET is not supported by this URL"
I also tried on tomcat and the error says
"HTTPO 405 Method not allowed. The website cannot display the page HTTP 405
Most likely cause: •The website has a programming error."
As your servlet has only doPost method. So, you can't get access the servlet with URL. Your URL should be for JSP page where action="buttontoserv" is assigned. When you click the submit button of JSP page than it will forwarded to /buttontoserv servlet.
To solve your problem, you should include a doGet method on Servlet or forward to Servlet with form submit from JSP page.
public class ButtontoServServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String group = request.getParameter("group");
String pass = request.getParameter("pass");
System.out.println("Name :"+ name);
System.out.println("group :"+ group);
System.out.println("pass :"+ pass);
}
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
Make sure you type the url to the jsp file instead of the servlet. Also try overriding the doGet method too like:
protected void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}

Categories

Resources