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!
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);
}
I have a simple program which get username and password, if the password is servlet then it will forward to the welcome page, else, it will show a message and includes html login form.
When I enter username and password and click on login, no matter what, it always shows me the "HTTP Status 405 : HTTP method GET is not supported by this URL" error.
I have read a lot of questions and answers here, none of them helped me to solve this problem.
Here's my code:
Simple.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class Simple extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String p=request.getParameter("userPass");
if(p.equals("servlet")){
RequestDispatcher rd=request.getRequestDispatcher("welcome");
rd.forward(request, response);
}
else{
out.print("Sorry username or password error!");
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.include(request, response);
}
}
}
WelcomeServlet.java
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 WelcomeServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
index.html
<form action="go" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>Simple</servlet-name>
<servlet-class>Simple</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Simple</servlet-name>
<url-pattern>/go</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
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>
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'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");