Uploading Java to a website doesn't works - java

I have uploaded on a... let's say www.mywebsite.com a /helloservlet/ and into /helloservlet/ I have an index.html that shows a simple Hello World! This works fine but if I want to put an Java app, I uploaded a /WEB-INF/web.xml with:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="3.0"
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_3_0.xsd">
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>mypkg.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>
</web-app>
and in /helloservlet/WEB-INF/src/mypkg/HelloServlet.java with
package mypkg;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Set the response message's MIME type
response.setContentType("text/html;charset=UTF-8");
// Allocate a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();
// Write the response message, in an HTML page
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>Hello, World</title></head>");
out.println("<body>");
out.println("<h1>Hello, world!</h1>"); // says Hello
// Echo client's request information
out.println("<p>Request URI: " + request.getRequestURI() + "</p>");
out.println("<p>Protocol: " + request.getProtocol() + "</p>");
out.println("<p>PathInfo: " + request.getPathInfo() + "</p>");
out.println("<p>Remote Address: " + request.getRemoteAddr() + "</p>");
// Generate a random number upon each request
out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");
out.println("</body>");
out.println("</html>");
} finally {
out.close(); // Always close the output writer
}
}
}
but when I try
http://www.mywebsite.com/helloservlet/sayhello
It gives me an error.
What is the problem?
Thanks!

Use a Java application server on the machine that should host your code, like Tomcat. Then upload the .war to this Tomcat instance (or glassfish or whatever) this should fix your issue.

Related

Servlets & IntelliJ

I created a test project under Intellij to start Java EE with Tomcat.
My server starts well, no worries aside.
I created a Servlet which contains my HTML code, as well as doPost and getPost.
When I want to run the servlet, the server launches fine but I end up with a blank page.
An idea ?
Code :
package com.octest.servlets;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
#WebServlet(name = "Test")
public class Test extends HttpServlet {
protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType ("text/html");
response.setCharacterEncoding ("UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<meta charset=\"utf-8\" />");
out.println("<title>Test</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>Bonjour !</p>");
out.println("</body>");
out.println("</html>");
}
protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Et le web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app
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_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>com.octest.servlets.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/app</url-pattern>
</servlet-mapping>
</web-app>
Thanks
The browser will make a GET request but your HTML page is in doPost method. You need to keep this page inside doGet method.

Error HTTP Status 404. The requested resource is not available. [Netbeans]

I do a project Fahrenheit to Celsius conversion using netbeans with Tomcat 8.0.37
when i try to run project, i get a issue HTTP Satus 404.
My index.html
<html>
<head>
</head>
<body>
<h3>Please enter Fahrenheit temperature:</h3><p>
<form action="/conv/test">
Temperature(F) : <input type="text" name="temperature"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
My web.xml
<web-app>
<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>doGetMethod.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
My TestServlet.java
public class TestServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws javax.servlet.ServletException, java.io.IOException
{
String temperature = req.getParameter("temperature");
DecimalFormat twoDigits = new DecimalFormat("0.00");
try
{
double tempF = Double.parseDouble(temperature);
String tempC = twoDigits.format((tempF -32)*5.0/9.0);
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println("<h3>" + temperature + " Fahrenheit is
converted to " + tempC + " Celsius</h3><p>");
out.println("</body>");
out.println("</html>");
}
catch(Exception e)
{
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"There was an input error");
}
}
}
Please help me to solve this issue !
I apologize for not being word-perfect in English.
You should access the index.html at localhost:8080/contextRoot/index.html. The action associated to the form should map to the servlet, so it should be action="/test". The servlet-class tag in the web.xml should specify your servlet class full name such as mypackage.TestServlet. You could avoid using a web.xml and save you some time by using annotation on the Servlet class as well explained here https://docs.oracle.com/javaee/7/tutorial/servlets004.htm#BNAFU. Also look here for a similar example https://stackoverflow.com/a/2395262/6848537

Error with Java Servlet & DB connection [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
Having issues getting the program to display anything when running in eclipse.
Goal is:
In this application you will also create a virtual directory so that you do not have to use the word servlet as part of your form post URL. You will then be able to run your Web application servlet by using a URL similar to the following: http://localhost:7070/Week5/FormPost2. To create your virtual directory you may start by modifying the web.xml attached to this assignment. Next, create a Servlet that displays a form when the doGet method is invoked. The form will contain a post action that directs the form post back to the same servlet, which in the doPost method will save the form data to a database. Use your Oracle account to make the DB connection. After the form data has been saved to the database, respond back with a query from the database displaying all the current records contained in the database, in an appealing format. The form must contain a minimum of three input fields.
Below error was received:
HTTP Status 404 - /Week5/servlet/Week5.Week5
type Status report
message /Week5/servlet/Week5.Week5
description The requested resource is not available.
Apache Tomcat/7.0.72
I'm sure it is a simple error, but please pinpoint it so I can get it to display properly. Thank you.
package Week5;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Week5 extends HttpServlet{
private static final long serialVersionUID = 1L;
Connection con = null;
Statement stmt = null;
public Week5(){
init();
}
public void init(){
try{
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "student2", "pass");
stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE MYTABLE (FNAME VARCHAR2(20), LNAME VARCHAR2(40), PHONE VARCHAR2(20))");
stmt.close();
}
catch (Exception e){
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println("First Name:");
out.println("");
out.println("");
out.println("Last Name:");
out.println("");
out.println("");
out.println("Phone:");
out.println("");
out.println("SUBMIT");
out.println("");
out.println("");
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
try{
if (con != null)
init();
String fname = request.getParameter("FNAME");
String lname = request.getParameter("LNAME");
String phone = request.getParameter("PHONE");
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO MYTABLE VALUES('" + fname + "', '" + lname + "', '" + phone + "')");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
ResultSet rset = stmt.executeQuery("SELECT * FROM MYTABLE");
while (rset.next()){
out.print("");
out.print("First Name: " + rset.getString(1));
out.print("");
out.println();
out.print("");
out.print("Last Name: " + rset.getString(2));
out.print("");
out.println();
out.print("");
out.print("Phone: " + rset.getString(3));
out.print("");
out.println();
out.println();
}
out.println("");
out.close();
stmt.close();
}
catch (Exception e){
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println(e.getMessage());
out.println("");
out.close();
}
}
}
XML
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
<servlet>
<servlet-name>
Week5 <!-- Alias I gave the servlet // -->
</servlet-name>
<servlet-class>
HelloWorld <!-- Class name // -->
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
Week5 <!-- Alias I gave the servlet // -->
</servlet-name>
<url-pattern>
/VirtualName <!-- What I want the user to type in // -->
<!-- Example: http://localhost:7070/Week5/FormPost2 // -->
</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>
FormPost2
</servlet-name>
<servlet-class>
HelloWorld2
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
FormPost2
</servlet-name>
<url-pattern>
/VirtualName2
</url-pattern>
</servlet-mapping>
</web-app>
your servlet class should be fully qualified class name such as
<servlet-class>
week5.week5
</servlet-class>
<servlet-class> tag should contain the servlet(class)
<servlet-name> will be the name of the servlet that is mapped with the <servlet-mapping>
example
<servlet>
<servlet-name>
anyServletName
</servlet-name>
<servlet-class>
com.example.customServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
anyServletName
</servlet-name>
<url-pattern>
/VirtualName2
</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!

Executing MySQL Commands from a Java Servlet

I'm trying to get my servlet to output the results of SQL commands entered by the user. Right now, the servlet correctly detects when a command does not include "SELECT", "INSERT", or "DELETE", and outputs an error message. When the command is valid, nothing is outputted. I know this means my problem is likely occurring either where I am trying to connect to the database, or where I am trying to print output to "out".
databaseServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
#SuppressWarnings("serial")
public class databaseServlet extends HttpServlet {
private Connection conn;
private Statement statement;
public void init(ServletConfig config) throws ServletException {
try {
Class.forName(config.getInitParameter("databaseDriver"));
conn = DriverManager.getConnection(
config.getInitParameter("databaseName"),
config.getInitParameter("username"),
config.getInitParameter("password"));
statement = conn.createStatement();
}
catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<xml version = \"1.0\"?>");
out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
"XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
"/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
out.println("<html xmlns = \"http://www.w3.org/1999/xhtml\">");
out.println("<head>");
out.println("<title>MySQL Servlet</title>");
out.println("<style type='text/css'>");
out.println("body{background-color: blue}");
out.println("</style>");
out.println("</head>");
out.println("<body>");
String query = request.getParameter("query");
if (query.toLowerCase().contains("select")) {
//SELECT Queries
try {
ResultSet resultSet = statement.executeQuery(query);
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
for(int i = 1; i<= numberOfColumns; i++){
out.printf("%20s\t", metaData.getColumnName(i));
}
out.println();
while (resultSet.next()){
for (int i = 1; i <= numberOfColumns; i++){
out.printf("%20s\t", resultSet.getObject(i));
}
out.println();
}
}
catch (Exception f) {
f.printStackTrace();
}
}
else if (query.toLowerCase().contains("delete") || query.toLowerCase().contains("insert")) {
//DELETE and INSERT commands
try {
conn.prepareStatement(query).executeUpdate(query);
out.println("\t\t Database has been updated!");
}
catch (Exception l){
l.printStackTrace();
}
}
else {
//Not a valid response
out.println("\t\t Not a valid command or query!");
}
out.println("</body>");
out.println("</html>");
out.close();
}
}
dbServlet.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- dbServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>MySQL Servlet</title>
<style type="text/css">
body{background-color: green;}
</style>
</head>
<body>
<h1>Hello World!</h1>
<h2>This is the MySQL Servlet</h2>
<form action = "/database/database" method = "get">
<p>
<label>Enter your query and click the button to invoke a MySQL Servlet
<input type = "text" name = "query" />
<input type = "submit" value = "Run MySQL Servlet" />
</label>
</p>
</form>
</body>
</html>
I thought another potential failure point could be my path to the database file, which is initialized in my web.xml file. An example I found online included the port, but I'm wondering if I should remove the port number. Does anyone know the default port to use for MySQL?
This is the specific line I'm talking about from the xml file below:
jdbc:mysql://localhost:3309/project4
web.xml
<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">
<!-- General description of the web application -->
<display-name>
MySQL Servlet
</display-name>
<description>
This web application allows the user to connect to a database, sumbit queries, and make changes.
</description>
<!-- Servlet definitions -->
<servlet>
<servlet-name>database</servlet-name>
<description>
A servlet that handles SQL commands submitted by the user.
</description>
<servlet-class>
databaseServlet
</servlet-class>
<init-param>
<param-name>databaseDriver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
<init-param>
<param-name>databaseName</param-name>
<param-value>jdbc:mysql://localhost:3309/project4</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>pass</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>database</servlet-name>
<url-pattern>/database</url-pattern>
</servlet-mapping>
</web-app>
I was using port 3309, and needed to use port 3306.
PROBLEM
jdbc:mysql://localhost:3309/project4
SOLUTION
jdbc:mysql://localhost:3306/project4

Categories

Resources