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");
Related
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);
}
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>
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!
I am new on servlet.i have made # clases(Login,Logout,Profile).A simple error that i not solved.A link passes to call the all classes.Login and Logout work properly bt when i click on profile , it will show Downloaded file option.Please help Me , Tnkx in advance.
Logout.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
Cookie ck=new Cookie("uername", "");
ck.setMaxAge(0);
response.addCookie(ck);
out.print("you are successfully logged out!");
Login.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
String username=request.getParameter("name");
String password=request.getParameter("password");
if(username.equals("pr"))
{
out.print("You are successfully logged in!");
out.print("<br>Welcome, "+username);
Cookie ck=new Cookie(username, username);
response.addCookie(ck);
}
else{
out.print("sorry, username or password error!");
request.getRequestDispatcher("login.html").include(request, response);
}
out.close();
}
Profile.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("html/text");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
Cookie ck[]=request.getCookies();
System.out.println(ck[0].getValue());
if(ck!=null)
{
String name=ck[0].getValue();
if(!name.equals(null)||name!=null)
{
out.print("<b>Welcome to Profile</b>");
out.print("<br>Welcome, "+name);
}
}
else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
out.close();
}
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_2_5.xsd" id="WebApp_ID" version="2.5">
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.servletcookie.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>ProfileServlet</display-name>
<servlet-name>ProfileServlet</servlet-name>
<servlet-class>com.servletcookie.ProfileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProfileServlet</servlet-name>
<url-pattern>/ProfileServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>LogoutServlet</display-name>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.servletcookie.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
<!-- <welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list> -->
</web-app>
response.setContentType("html/text");
should be
response.setContentType("text/html");
I am getting this "HTTP method POST is not supported by this URL" error when I run my project. The funny thing is, it was running perfectly fine two days ago. After I made a few changes to my code but then restored my original code and its giving me this error. Could you please help me?
Here is my index.html:
<form method="post" action="login.do">
<div>
<table>
<tr><td>Username: </td><td><input type="text" name="e_name"/>
</td> </tr>
<tr><td> Password: </td><td><input type="password" name="e_pass"/>
</td> </tr>
<tr><td></td><td><input type="submit" name ="e_submit" value="Submit"/>
Here is my Login servlet:
public class Login extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
int status;
String submit = request.getParameter("e_submit");
String submit2 = request.getParameter("a_submit");
out.println("Here1");
String e_name = request.getParameter("e_name");
String e_password = request.getParameter("e_pass");
String a_name = request.getParameter("a_name");
String a_password = request.getParameter("a_pass");
out.println(e_name+e_password+a_name+a_password);
Author author = new Author(a_name,a_password);
Editor editor = new Editor(e_name,e_password);
// If it is an AUTHOR login:
if(submit==null){
status = author.login(author);
out.println("Author Login");
//Incorrect login details
if(status==0) {
out.println("Incorrect");
RequestDispatcher view = request.getRequestDispatcher("index_F.html");
view.forward(request, response);
}
//Correct login details --- AUTHOR
else {
out.println("Correct login details");
HttpSession session = request.getSession();
session.setAttribute(a_name, "a_name");
RequestDispatcher view = request.getRequestDispatcher("index_S.jsp");
view.forward(request, response);
}
}
//If it is an EDITOR login
else if (submit2==null){
status = editor.login(editor);
//Incorrect login details
if(status==0) {
RequestDispatcher view = request.getRequestDispatcher("index_F.html");
view.forward(request, response);
}
//Correct login details --- EDITOR
else {
out.println("correct");
HttpSession session = request.getSession();
session.setAttribute(e_name, "e_name");
session.setAttribute(e_password, "e_pass");
RequestDispatcher view = request.getRequestDispatcher("index_S_1.html");
view.forward(request, response);
} }
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}}
And my web.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>controller.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login.do</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>
I use Glassfish v3 server - let me know anything else you need to know
That's because on your doGet() and doPost() method, you're calling it's super methods. Rather, call the processRequest() inside the respective methods mentioned above.
The super.doGet() and super.doPost() method, returns an HTTP 405, by default, so you don't call your superclass doGet() and doPost().
Why is there a processRequest method in your code? Who will call that method?
You can't get up to that method by calling super.doGet() or super.doPost()
you need to call that method explicitly.
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req,resp)
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req,resp)
}
EDIT
Do this
response.sendRedirect("index_F.html");
return;
instead of
RequestDispatcher view = request.getRequestDispatcher("index_F.html");
view.forward(request, response);
Inside doPost() you have to call processRequest().
You're calling doGet() and doPost() method without actually implementing (using super).
The HttpServlet basically follows the template method pattern where all non-overridden HTTP methods returns a HTTP 405 error "Method not supported". When you override such a method, you should not call super method, because you would otherwise still get the HTTP 405 error. The same story goes on for your doPost() method.
Call the processRequest(req,resp) inside the respective methods mentioned above.
EDIT:
Second,
Do not use dispatcher to forward request to HTML. Use redirect anyway if you want to show html only.
response.sendRedirect("index_F.html");
return;
Also, It is good practice to use redirect when you do Logout or send back for invalid credentials.