How to process href parameters jsp - java

I have little test page, but I can't get request parameters an don't understand why.
Test page have "href" links like this:
Show smth
Simple controller:
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Controller extends HttpServlet {
#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);
}
protected void processRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
StringBuilder sb = new StringBuilder("Do SMTH<br>");
sb.append("Other will be later...<br>");
String s = sb.toString();
request.setAttribute("result", s);
RequestDispatcher view = request.getRequestDispatcher("test.jsp");
view.forward(request,response);
}
}
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_3_1.xsd"
version="3.1">
<welcome-file-list>
<welcome-file>main.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>/main.jspc</url-pattern>
</servlet-mapping>
</web-app>
and test page, where i want to show some obtained parameters:
test.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<%
out.print("<br>" + "Parameter: ");
request.getParameter("param");
out.print("<br>"+ "URL:");
request.getRequestURL();
out.print("<br>" + "Result:");
request.getParameter("result");
%>
</body>
</html>
But test page showing empty parameters, I don't understand why.

The use of scriptlets (those <% %> things) in JSP is old one and discouraged since the birth of taglibs(JSTL) and EL(Expression Language, those ${} things).
Use below code access your parameter :
Parameter : ${params} <br>
Result : ${result} <br>
URL : ${pageContext.request.requestURI}

Related

Unable to pass form data to Servlet

I have written a sample code to pass form data from a html page to a servlet. Here are my source codes,
StudentForm.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Form</title>
</head>Title
<body>
<form action="FormDataServlet" method="get">
FName:<input type="text" name="fName"> <br/>
LName:<input type="text" name="lName"><br/>
<input type="submit" value="submit">
</form>
</body>
</html>
FormDataServlet
package com.kasun.student.form;
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;
/**
* Created by kausn on 5/24/17.
*/
#WebServlet(name = "/FormDataServlet")
public class FormDataServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printWriter=response.getWriter();
printWriter.print("<html><head></head><body>");
printWriter.print("The F name of the student is "+request.getParameter("fName"));
printWriter.print("The L name of the student is "+request.getParameter("lName"));
printWriter.print("</body></html>");
}
}
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_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>ServletDemo1</servlet-name>
<servlet-class>com.kasun.servlet.demo.ServletDemo1</servlet-class>
</servlet>
<servlet>
<servlet-name>FormDataServlet</servlet-name>
<servlet-class>com.kasun.student.form.FormDataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo1</servlet-name>
<url-pattern>/ServletDemo1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>FormDataServlet</servlet-name>
<url-pattern>/FormDataServlet</url-pattern>
</servlet-mapping>
</web-app>
But when I submit the form it says 404 error that is because it is calling the servlet that exists in http://localhost:63342/ServletDemo/web/FormDataServlet?fName=sfddfddfd&lName=dfdf this path. I know for sure that this is where the bug is, but how to fix this? (Please find the screenshot of package structure as below)

Asynchronous Servlets or Filters don't work

I'm new to Java EE and was about to learn to use asynchronous Servlets. I created a web application with a simple index.jsp from which the servlet is called after pressing a button. I always get the following exception:
java.lang.IllegalStateException: Request is within the scope of a
filter or servlet that does not support asynchronous operations
But I set async-supported to true as annotation in the servlet or in web.xml or in both ways. I was searching for hours through similar questions here but I couldn't find a solution. I'm using NetBeans 8.0.2 and glassfish server 4.1 that comes along with NetBeans. Here is my 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>
<h1>Async Test</h1>
<form method="get" action="Asynctest">
<input type="submit"
value="Start test">
</form>
</body>
</html>
the Asynctest servlet:
package Controller;
import java.io.IOException;
import javax.servlet.AsyncContext;
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(asyncSupported = true, name = "Asynctest", urlPatterns = {"/Asynctest"})
public class Asynctest extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
AsyncContext ac = request.startAsync(request, response);
}
#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);
}
}
and the web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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_3_1.xsd">
<servlet>
<servlet-name>Asynctest</servlet-name>
<servlet-class>Controller.Asynctest</servlet-class>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>Asynctest</servlet-name>
<url-pattern>/Asynctest</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
It makes me crazy.. Thanks for your help!

Java servets request.getMethod() not working

Hello I am trying to create a simple servlet as follows
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Form extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter p=res.getWriter();
p.println("<html><head></head><body bgcolor=\"red\">The request came from"+req.getMethod()+"</body></html>");
}
}
The req.getMethod() should return POST but is giving me a null value.
I am taking the request from an html file coded as follows.
<html>
<body>
<form action="http://localhost:8080/Form" method="GET">
First Name: <input type="text" name="name"/>
<br>
<input type="submit" value="Submit form "/>
</form>
</body>
</html>
here is the web.xml file. Should I make any changes here.
<web-app 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"
version="3.0" metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<servlet-name>Form</servlet-name>
<servlet-class>Form</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Form</servlet-name>
<url-pattern>/Form</url-pattern>
</servlet-mapping>
</web-app>
You can write this annotation to attach your servlet to your form:
#WebServlet("/Form")
public class Form extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... }
}
You will have to import javax.servlet.annotation.WebServlet.

Java Servlet JSP does not print out attribute

I'm trying to write a servlet using generated HTML code, rather then printing out static HTMLs.
I'm using Eclipse-EE Europa and Tomcat 6.
I tried to use the flowing tips from HERE
But instead of printing the desired attribute It seems that the jsp ignoring the attribute or the attribute is empty.
Here is the servlet:
package com.serv.pac;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* Servlet implementation class for Servlet: testServlet
*
*/
public class testServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#HttpServlet()
*/
public testServlet() {
super();
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "doGet response";
request.setAttribute("message", message);
request.getRequestDispatcher("/testServlet/WEB-INF/index1.jsp").forward(request, response);
PrintWriter out = response.getWriter();
out.println("the servlet");
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("first servlet");
}
}
Here is the JSP
<!doctype html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
And the following is the :
<?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" id="WebApp_ID" version="2.5">
<display-name>servlet1_test</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
<welcome-file>index1.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>testServlet</display-name>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.serv.pac.testServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/testServlet</url-pattern>
</servlet-mapping>
</web-app>
And that is what I'm getting in the browser:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: </p>
</body>
</html>
As one may see there is nothing after the "Message" in the html body, as if the message attribute is empty.
Thank You
The only way I can see this happenning is you aren't actually accessing your Servlet.
You've declared a <welcome-file>
<welcome-file>index1.jsp</welcome-file>
So if you try to hit
localhost:8080/YourContextPath
the default Servlet will render and send you that jsp with a missing message attribute.
If you want to hit your actual Servlet, you need to use
localhost:8080/YourContextPath/testServlet
Note that you need to change
request.getRequestDispatcher("/testServlet/WEB-INF/index1.jsp").forward(request, response);
to
request.getRequestDispatcher("/WEB-INF/index1.jsp").forward(request, response);
and move your file under WEB-INF.

HTTP Status 405 - HTTP method POST is not supported by this URL

I try to send some data but it seems like the Controller could not be clear found or could not handle the request.
test.jsp
<%# page errorPage="exception.jsp"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page session="true" import="java.io.*,java.util.*"%>
<%# page import="eng.ku.sku.exceed_vote.knt.*"%>
<form name="AddForm" action="addtext" method="POST">
<input type="hidden" name="todo" value="add">
Add text:<input type="text" name="text" />
<input type="submit" value="Add">
</form>
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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" version="2.5">
<servlet>
<servlet-name>exceed</servlet-name>
<servlet-class>eng.ku.sku.exceed_vote.knt.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>exceed</servlet-name>
<url-pattern>/addtext</url-pattern>
Controller.java
package eng.ku.sku.exceed_vote.knt;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
#WebServlet("/addtext")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response); // Same as doPost()
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Retrieve the current session, or create a new session if no session exists.
HttpSession session = request.getSession(true);
System.out.println("HIIEER");
// Retrieve the shopping cart of the current session.
// For dispatching the next Page
String nextPage = "";
String todo = request.getParameter("todo");
// Dispatch to checkout.jsp
nextPage = "/checkout.jsp";
response.sendRedirect(nextPage);
return;
}
}
I read a lot of other topics but didnt find a solution. I hope u can help me :)
Okay it was a wrong config of Tomcat.
It didn't sync the project changes.

Categories