I can not send a simple request to the servlet to jQuery tools. But at the same time if I go through the form, then everything works on hurray. Here is the index.html from which I want to send the user's login. Login.js, in which I form the request itself, SerletStore.java itself servlet. And the structure of the whole project.
login.js
$(document).ready( function(){
$("#login-submit").click(function(){
var data = {
username: $("#user").prop("value")
}
$.ajax({
method: "POST",
url: "http://localhost:8080/ChallengeClient/store",
data: {
username: $("#user").prop("value")
},
success: function(data) {
alert('Success');
},
error: function(xhr, str){
alert('Возникла ошибка: ' + xhr.responseCode);
}
}).done(function() {
alert('Success');
});
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Form</title>
<link rel="stylesheet" href="css/login.css">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400,700">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/login.js"></script>
</head>
<body>
<div id="login">
<form name="form-login">
<span class="fontawesome-user"></span>
<input type="text" id="user" name="username" placeholder="Имя пользователя">
<span class="fontawesome-lock"></span>
<input type="password" id="pass" placeholder="Пароль">
<input type="submit" id="login-submit" value="Вход">
</form>
</div>
</body>
</html>
ServletStore.java
package servlet;
import server.service.HelloWebService;
import server.service.HelloWebServiceImplService;
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;
#WebServlet(name="store", urlPatterns = "/store")
public class ServletStore extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// подключаемся к тегу service в wsdl описании
HelloWebServiceImplService helloService = new HelloWebServiceImplService();
// получив информацию из тега service подключаемся к самому веб-сервису
HelloWebService hello = helloService.getHelloWebServiceImplPort();
// обращаемся к веб-сервису и выводим результат в консоль
/*String error = hello.getHelloString("!! Challenge !!");*/
String error = "";
String username = (String) req.getParameter("username");
if (username.equals("")) {
error = "Не было введено имя пользователя";
}
req.setAttribute("error", "Не было введено имя пользователя");
req.getRequestDispatcher("jsp/loginError.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Related
I was trying to add a servlet to my Maven project and when I run the application and access its URL it gives me this error.
I leave you the servlet code and the index.html.
When I access http://localhost:8090/ServletSaludo / I get the error This application has no explicit mapping for / error, so you are seeing this as a fallback. I don't see the fault, I think I have created it and done everything right.
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
#WebServlet("/ServletSaludo")
public class ServletSaludo extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Hola Mundo!</TITLE></HEAD>");
out.println("<BODY>");
String nombre = (String) request.getParameter("nombre");
if (nombre != null) {
out.println("Hola " + nombre + "<br>");
}
out.println("</BODY></HTML>");
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet( request,response );
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Servlets</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<!-- Contenido -->
<div class="container" id="contenedor-principal">
<h2>Formulario GET Saludar</h2>
<form action="ServletSaludo" method="get">
<div class="form-group">
<label for="nombre-get">Nombre</label>
<input type="text" class="form-control" name="nombre" id="nombre-get">
</div>
<button type="submit" class="btn">Enviar</button>
</form>
<h2>Formulario POST</h2>
<form action="ServletSaludo" method="post">
<div class="form-group">
<label for="nombre-post">Nombre</label>
<input type="text" class="form-control" name="nombre" id="nombre-post">
</div>
<button type="submit" class="btn">Enviar</button>
</form>
</div>
</body>
</html>
I replicated your application and it worked for me. Please see the folder structure on whether you've kept it correctly or not.
And one more thing, since you added a tag for Spring boot, you can use #RestController or #Controller to create endpoints for your project.
I have created a simple EJB Application to demonstrate Session Bean by making a simple calculator on a JSP Page.
For Stateless SessionBean.
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div>Calculator</div>
<form action="NewServlet" method="post">
value 1:<input type="text" name="v1"><br>
value 2:<input type="text" name="v2"><br>
<input type="radio" name="g" value="1"> ADDITION <br>
<input type="radio" name="g" value="2"> SUBTRACT <br>
<input type="radio" name="g" value="3"> DIVIDE <br>
<input type="radio" name="g" value="4"> MULTIPLY <br>
<input type="submit" value="=">
</form>
</body>
</html>
NewSessionBean.java
package com;
import javax.ejb.Stateless;
#Stateless
public class NewSessionBean implements NewSessionBeanLocal {
#Override
public int sub(int a, int b) {
return (a-b);
}
#Override
public int add(int v1, int v2) {
return v1+v2;
}
#Override
public int mul(int v1, int v2) {
return v1*v2;
}
#Override
public int div(int v1, int v2) {
return v1/v2;
}
}
NewServlet.java
package com;
import com.NewSessionBeanLocal;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
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(name="NewServlet", urlPatterns={"/NewServlet"})
public class NewServlet extends HttpServlet {
#EJB
private NewSessionBeanLocal newSessionBean;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
try {
int v1=Integer.parseInt(request.getParameter("v1"));
int v2=Integer.parseInt(request.getParameter("v2"));
String f=request.getParameter("g");
int result=0;
if(f.equals("1"))
{
result=newSessionBean.add(v1, v2);
out.println("<h1>result =>"+result+"<h1>");
}
else if(f.equals("2"))
{
result=newSessionBean.sub(v1, v2);
out.println("<h1>result =>"+result+"<h1>");
}
else if(f.equals("3"))
{
result=newSessionBean.div(v1, v2);
out.println("<h1>result =>"+result+"<h1>");
}
else
{
result=newSessionBean.mul(v1, v2);
out.println("<h1>result =>"+result+"<h1>");
}
}
finally{
out.close();
}
}
#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);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
After writing the program, I went to the Project Folder(EnterpriseApplication3) right-click => properties => run => Relative Url: /index.jsp.
So that when I build and run the project it should start from index.jsp page.
Index.jsp page is working perfectly but when I press submit, i am getting NewServlet page which is blank.
Browser: Chrome, Mozilla, IE (All latest versions).
index.jsp Page
This is my html code
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>New Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form method="post" action="display">
I have used POST method above for servlet action
Enter Name: <input type="text" name="name">
Enter City <input type="text" name="city">
<input type="submit" name="submit">
</form>
</body>
</html>
Servlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class servlet1 extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
used "doPost" for the POST method defined in the html form
{
response.setContentType("text/html");
Cookie c1 = new Cookie("name",request.getParameter("name"));
Cookie c2 = new Cookie("city",request.getParameter("city"));
response.addCookie(c1);
response.addCookie(c2);
redirecting to 2nd servlet through this form
response.sendRedirect("servlet2");
}
}
servlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class servlet2 extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
I am getting an error saying "HTTP GET Method is not supported by this url", however I have nowhere mentioned GET in my code.
{
response.setContentType("text/html");
Cookie c[] = request.getCookies();
PrintWriter pw = response.getWriter();
for(Cookie cookie : c)
{
if(cookie.getName().equals("name") ||
cookie.getName().equals("city"))
{
pw.println(cookie.getValue()+"<br>");
}
}
pw.println("Print using cookie");
}
}
the servlet works perfectly fine if I use "doGET" method in servlet2.java. However I am using POST method then why does it require "doGET"??
I get the below error for the above code.
HTTP Status 405 - HTTP method GET is not supported by this URL
type: Status report
message: HTTP method GET is not supported by this URL
description: The specified HTTP method is not allowed for the requested
resource.
Apache Tomcat/7.0.56
I found a piece of code to use AngularJS with Java Servlet.
The problem is that when I run the application it tell me that the 'AtpPlayers' page it does not exists and, of course, it does not fill my table.
I was trying in JBOSS server and json-simple-1.1.1.jar library.
What is doing wrong?
The servlet is here:
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("/AtpPlayers")
public class AtpPlayers extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json;charset=UTF-8");
try {
PrintWriter out = response.getWriter();
out.println("[{\"name\": \"Nadal, Rafael (ESP)\", \"email\": \"nadalrafael#gmail.com\", \"rank\": \"1\"},"
+ "{\"name\": \"Djokovic, Novak (SRB)\", \"email\": \"djokovicnovak#gmail.com\", \"rank\": \"2\"},"
+ "{\"name\": \"Federer, Roger (SUI)\", \"email\": \"federerroger#gmail.com\", \"rank\": \"3\"},"
+ "{\"name\": \"Wawrinka, Stan (SUI)\", \"email\": \"wawrinkastan#gmail.com\", \"rank\": \"4\"},"
+ "{\"name\": \"Ferrer, David (ESP)\", \"email\": \"ferrerdavid#gmail.com\", \"rank\": \"5\"}]");
} catch (Exception e) {
System.out.println(e);
}
}
}
The HTML & JS code is that:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
</head>
<body ng-app="ATP_PLAYERS">
<div ng-controller="atpController">
<h5>Loading ATP players from a Servlet</h5>
<table>
<thead>
<tr>
<th>Rank</th>
<th>Name</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in atp">
<td>{{item.rank}}</td>
<td>{{item.name}}</td>
<td>{{item.email}}</td>
</tr>
</tbody>
</table>
</div>
<script language="javascript" type="text/javascript">
angular.module('ATP_PLAYERS', [])
.controller('atpController', function ($scope, $http) {
$http.get('http://localhost:8080/AngularGET/AtpPlayers').then(function (data, status, headers, config) {
$scope.atp = data;
alert('OK');
}, function (data, status, headers, config) {
alert('NU');
});
});
</script>
</body>
</html>
I found the problem:
$http.get('http://localhost:8080/AngularGET/AtpPlayers').then(function (data, status, headers, config) {
$scope.atp = data;
alert('OK');
}, function (data, status, headers, config) {
alert('NU');
});
replaced with:
$http.get('http://localhost:8080/AngularGET/AtpPlayers').then(function (response) {
$scope.atp = response.data;
alert('OK');
}, function (response) {
alert('NU');
});
I don't knows why the guy which write the original code was typed "function (data, status, headers, config)"...
Hello I know That this question has been asked before But unfortuanetly I didn t find among the answers proposed the one suitable for me
I m still new with J2ee lookin' forward for ur help
This is my code
login.jsp
<!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=UTF-8">
<title>Login page</title>
</head>
<body>
<form action="" method="post"/>
<br> UserId: <input type="text" name="userId"/>
<br> password<input type="password" name="password"/>
<br><input type="submit"/>
</form>
</body>
</html>
LoginServlet.java
package org.islem.login;
import java.io.IOException;
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 org.islem.login.service.LoginService;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String userId,password;
userId= request.getParameter("userId");
System.out.println(userId);
password= request.getParameter("password");
LoginService loginService= new LoginService();
boolean result= loginService.authenticate(userId, password);
if (result)
{
response.sendRedirect("home.jsp");
return;
}
else
{
response.sendRedirect("login.jsp");
return;
}
}
}
LoginService.java
package org.islem.login.service;
public class LoginService {
public boolean authenticate (String userId,String password)
{
if (password ==null || password.trim() =="") {
return false;
}
else return true;
}
}
Your form action is empty, you should fill it your servlet name in your case it should be like:
<form action="LoginServlet" method="post"/>
I assume you already define your servlet name at your web.xml
You need to specify some controller name within the action:
<form action="LoginServlet " method="post"/>
<br> UserId: <input type="text" name="userId"/>
<br> password<input type="password" name="password"/>
<br> <input type="submit"/>
</form>
Remember: This action specifies where the data submitted by the form will be received.