Servlet request.getParameter() returns null [duplicate] - java

This question already has answers here:
How to transfer data from JSP to servlet when submitting HTML form
(4 answers)
Closed 2 years ago.
I have read all the questions about this here, but I still do not have any progress. I want to pass the value from the input field to my servlet, but the servlet's request.getParameter returns null, instead of what is inputted. Here is my HTML:
<form method="post" action="MyHttpServletDemo" id="myForm">
<input type="text" id="input" name="input1" placeholder=" Input coordinates...">
</form>
<button type="button" id="vnes" onclick="Vnes()">Search</button>
Here is my .xml:
<servlet>
<servlet-name>MyHttpServletDemo</servlet-name>
<servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServletDemo</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
And the Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String value = (String) request.getParameter("input1");
out.println("<h1>" + value + "</h1>");
}
I tried this:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
PrintWriter out = response.getWriter();
String value = (String) request.getParameter("input1");
out.println("<h1>" + value + "</h1>");
}
HTML:
<form method="post" action="/welcome" id="myForm">
<input type="text" id="input" name="input1" placeholder=" Input coordinates...">
<button type="button" id="vnes" onclick="Vnes()">Search</button>
</form>
And still does not work.

It worked! Here's the solution:
HTML:
<form method="get" action="welcome" id="myForm">
<input type="text" id="pole" name="pole1" placeholder=" Input coordinates...">
<button type="submit" id="vnes">Search</button>
</form>
.xml file:
<servlet>
<servlet-name>MyHttpServletDemo</servlet-name>
<servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServletDemo</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String value = (String) request.getParameter("pole1");
out.println("<h1>" + value + "</h1>");
}

Related

How to link external css in java servlet?

I have a report.jsp page which looks like below (NOTE: I have just added codes which are necessary).
<form name="report" action="../printOrganization" method="post">
<table>
<tr>
<td>
Organization name: <input type="text" name="orgName" />
</td>
</tr>
<tr>
<td>
<input type="submit" value="Submit" name="action" />
</td>
</tr>
</table>
When user clicks "Submit" button of report.jsp page. The request is sent to servlet called OrganizationServlet. And the request is handle by doPost method. The code in OrganizationServlet looks like below:
public class OrganizationServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String organizatio = request.getParameter("orgName");
if (organizatio.equals("ABC")) {
printAllOrganization();
}
}
public void printAllOrganization()
{
PrintWriter pw = response.getWriter();
response.setContentType("text/html");
pw.println("<!DOCTYPE html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n");
pw.println("<html>\n");
pw.println("<head>\n");
pw.println("<title> Print Organization </title>\n");
pw.println("<link rel=\"stylesheet\" type=\"text/css\" HREF=\"../styles/myStyle.css\">\n"); // This style sheet doesn't show effect when program run in browser
pw.println("</head>\n");
pw.println("<body>\n");
//printing all organization code is here!
pw.println("</body>\n");
pw.println("</html>\n");
pw.close();
}
The part of web.xml which handles request is shown below:
<servlet>
<servlet-name>servletForOrganization</servlet-name>
<servlet-class>com.project.report.OrganizationServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletForOrganization</servlet-name>
<url-pattern>/printOrganization</url-pattern>
</servlet-mapping>
My css file is located in this path:
MyProject > resource > styles > myStyle.css
When I run my application in the browser, the css style which is in printAllOrganization() method of OrganizationServlet servlet doesn't show any effect. Could someone please help me how to sort this problem. Thank you in advance.
Add in your home JSP file:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<link rel="stylesheet" href="<c:url value="/resource/styles/myStyle.css" />">
Add in dispatcher-servlet.xml:
<mvc:resources mapping="/resource/**" location="/resource/" />
modify your class:
public class OrganizationServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String organizatio = request.getParameter("orgName");
if (organizatio.equals("ABC")) {
printAllOrganization(request);
}
}
public void printAllOrganization(HttpServletRequest request) {
PrintWriter pw = response.getWriter();
response.setContentType("text/html");
pw.println("<!DOCTYPE html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n");
pw.println("<html>\n");
pw.println("<head>\n");
pw.println("<title> Print Organization </title>\n");
pw.println("<link rel=\"stylesheet\" type=\"text/css\" HREF=\"" + request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/resource/styles/myStyle.css\">\n");
pw.println("</head>\n");
pw.println("<body>\n");
//printing all organization code is here!
pw.println("</body>\n");
pw.println("</html>\n");
pw.close();
}

RequestDispatcher for an input form

<form id='search' method='get'>
<input type='text' name='search' />
<input type='submit' value='Search'/><br/>
</form>
I have this search form.
String search = request.getParameter("search");
if (search != null) {
request.setAttribute("search", search);
RequestDispatcher rd = request.getRequestDispatcher("Content");
rd.forward(request, response);
}
And here I want to get what I type in the input and dispatch it to the Content. My input is not reaction at all. My debugger shows that my programm doesnt even go to the request.getParameter("search") part. Whats the problem?
Specify the action name in form like below:
<form action="/yourServlet/"id='search' method='get'>
<input type='text' name='search' />
<input type='submit' value='Search'/><br/>
</form>
Servlet Code:
public class YourServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException{
String search = request.getParameter("search");
if (search != null) {
request.setAttribute("search", search);
RequestDispatcher rd =
request.getRequestDispatcher("Content");
rd.forward(request, response);
}
}
}
And servlet mapping in your web.xml:
<servlet>
<servlet-name>yourServlet</servlet-name>
<servlet-class>test.YourServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>yourServlet</servlet-name>
<url-pattern>/yourServlet/</url-pattern>
</servlet-mapping>

Eclipse - Java Issue finding the controller

I am learning JSP through a French JSP book full of tutorials. I'm currently learning "MVC & Jsp" basically, with a Catalog of DVD and a Shopping cart. A controller adds dvds to the cart when the user clicks on the add button.
However, it appears that my controller isn't called. I place a System.Out when it is called to check if it works, and there is no text popping on my console...
Here is my project explorer.
And here are my codes for my catalog and my Controller.
<%#page import="exoLivres.ShoppingCart"%>
<%# page errorPage="../PagesErreur/Erreurpage.jsp" %>
<jsp:useBean id="cart" scope="session" class="exoLivres.ShoppingCart" />
<html>
<head>
<title>Catalogue DVD</title>
</head>
<body>
Quantité actuelle : <%=cart.getNumOfItems() %>
<hr>
<center><h3>Catalogue DVD</h3></center>
<table border="1">
<tr><th>Description</th><th>Prix</th></tr>
<tr>
<form action="ShopController" method="post">
<!--no error, but nothing happening-->
<td>Frozen</td>
<td>$19.95</td>
<td><input type="submit" name="Submit" value="Ajouter"></td>
<input type="hidden" name="id" value="1">
<input type="hidden" name="desc" value="Frozen">
<input type="hidden" name="price" value="19.95">
<input type="hidden" name="command" value="add">
</form>
</tr>
<tr>
<form action="ShopController" method="post">
<!--no error, but nothing happening-->
<td>XMen Origins</td>
<td>$19.95</td>
<td><input type="submit" name="Submit" value="Ajouter"></td>
<input type="hidden" name="id" value="1">
<input type="hidden" name="desc" value="XMen">
<input type="hidden" name="price" value="19.95">
<input type="hidden" name="command" value="add">
</form>
</tr>
<tr>
<form action="ShopController" method="post">
<td>Avengers</td>
<td>$17.95</td>
<td><input type="submit" name="Submit" value="Ajouter"></td>
<input type="hidden" name="id" value="1">
<input type="hidden" name="desc" value="Avengers">
<input type="hidden" name="price" value="17.95">
<input type="hidden" name="command" value="add">
</form>
</tr>
</table>
</body>
</html>
and my controller
package exoLivres;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
import exoLivres.ShoppingCart;
public class ShopController extends HttpServlet {
public void init(ServletConfig config) throws ServletException{
super.init(config);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
System.out.println("Contrôleur démarré");
String command= request.getParameter("command");
HttpSession session = request.getSession();
ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
if(command.equals("add")){
String id = request.getParameter("id");
if (id!=null){
System.out.println(id);
String desc = request.getParameter("desc");
Float price = new Float(request.getParameter("price"));
cart.addItem(id, desc, price.floatValue(), 1);
System.out.println(id + desc + price);
}
}
response.sendRedirect("U:/workspace/myfirstProject/WebContent/MVC/Catalogue.jsp");
}
public String getServletInfo(){
return "ShopController Information";
}
}
I guess the problem is from my references to my Controller but I can't think of the correct reference. Any help welcome =)
EDIT
Okay so here is my web.xmm [I also did the modifications suggered on my code above, and removed every "e" I wrote at the end of method (and not methode)]
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>MyfirstServlet</servlet-name>
<servlet-class>myfirstProject.MyfirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyfirstServlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Books</servlet-name>
<servlet-class>myfirstProject.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Books</servlet-name>
<url-pattern>/books</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ShopController</servlet-name>
<servlet-class>exoLivres.ShopController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShopController</servlet-name>
<url-pattern>/ShopController</url-pattern>
</servlet-mapping>
</web-app>
I think the problem is the way you set action to the form.
action="U:/workspace/myfirstProjet/src/ShopController"
I think it should be action="Name_Of_CLass" not path to the class.
Also notice that the sendRedirect receives a url location not the path to the jsp in your project. (https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletResponse.html#sendRedirect%28java.lang.String%29)
So in your servlet (controller) and your jsp, rename this "U:/workspace/myfirstProjet/build/classes/exoLivres/ShopController" to something like this: "/myfirstProjet/".
and where you have "U:/workspace/myfirstProject/WebContent/MVC/Catalogue.jsp"
rename to "/myfirstProjet/".
You must have your controller mapping in the web.xml
You have not given path of your ShopController controller in this
<servlet>
<servlet-name>MyfirstServlet</servlet-name>
<servlet-class>myfirstProject.MyfirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyfirstServlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Books</servlet-name>
<servlet-class>myfirstProject.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Books</servlet-name>
<url-pattern>/books</url-pattern>
</servlet-mapping>
It should be like this
<servlet>
<servlet-name>ShopController</servlet-name>
<servlet-class>packagename.ShopController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShopController</servlet-name>
<url-pattern>/ShopController</url-pattern>
</servlet-mapping>
And change the action of your jsp form as below..
<form action="ShopController" method="post">
<!--no error, but nothing happening-->
<td>XMen Origins</td>
<td>$19.95</td>
<td><input type="submit" name="Submit" value="Ajouter"></td>
<input type="hidden" name="id" value="1">
<input type="hidden" name="desc" value="XMen">
<input type="hidden" name="price" value="19.95">
<input type="hidden" name="command" value="add">
</form>
To prevent get method not supported change controller like this
public class ShopController extends HttpServlet {
public void init(ServletConfig config) throws ServletException{
super.init(config);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
processRequest(request,response)
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
processRequest(request,response)
}
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
System.out.println("Contrôleur démarré");
String command= request.getParameter("command");
HttpSession session = request.getSession();
ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
if(command.equals("add")){
String id = request.getParameter("id");
if (id!=null){
System.out.println(id);
String desc = request.getParameter("desc");
Float price = new Float(request.getParameter("price"));
cart.addItem(id, desc, price.floatValue(), 1);
System.out.println(id + desc + price);
}
}
response.sendRedirect("U:/workspace/myfirstProject/WebContent/MVC/Catalogue.jsp");
}
}

Print checked values in JSP page

I am trying to print checked values of checkbox list from a JSP page but nothing appears even if some selections are there.
<form action="process" method="POST">
<c:forEach var="item" items="${list.items}">
<input type="checkbox" name="chkSkills" value="${$item.Id}">${item.name}
</c:forEach>
<input type="submit" name="Getvalue" value="Get value" />
</form>
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String[] Answers = request.getParameterValues("chkSkills");
PrintWriter out = response.getWriter();
String ButClicked = request.getParameter("Getvalue");
if (ButClicked != null) {
for (String Answer : Answers) {
out.print(Answer + "<br>");
}
}
//processRequest(request, response);
}
Correct your value attribute to
value="${item.Id}"
Notice, there's no need to put a $ inside the {} again.

redirecting form jsp in Web-inf to servlet in javaResources through href in

This is my Login.jsp page
<form name="login" action="ValidateServlet" method="post">
<input type="hidden" name="pagename" value="login"/>
<table>
<tr>
<td><b>USERNAME:</b><input type="text" name="txtUsername"/> </td>
</tr>
<tr>
<td><b>PASSWORD:</b><input type="password" name="txtPassword"/></td>
</tr>
<tr>
<td><input type="SUBMIT" value="SIGN IN"/></td>
</tr>
<tr>
<td>Forgot Password</td>
</tr>
<tr>
<td> Create New user </td>
</tr>
</table>
</form>`
And this is my SignupServlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response throws
ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/WebPages/Signup.jsp");
rd.forward(request, response);
}
}
and this is my web.xml
<servlet>
<servlet-name>SignupServlet</servlet-name>
<servlet-class>com.affiliate.servlet.SignupServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SignupServlet</servlet-name>
<url-pattern>/SignUp</url-pattern>
</servlet-mapping>
Login.jsp is in Webcontent/WEB-INF/WebPages/Login.jsp
and SignupServlet in JavaResources/src/com.affiliate.servlet/SignupServlet
but my Login is not redirecting to the SignupServlet. And i have doubt on my href and form action. Please help me in this regard.
Change
Create New user
↑
To
Create New user
And in anchor tag there is no post method available. You need to change the code in SignupServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response throws
ServletException, IOException
{
RequestDispatcher rd = request.getRequestDispatcher("Signup.jsp");
rd.forward(request, response);
}
If you want post request using a tag then refer POST from an tag
replace
Forgot Password
Create New user
To
Forgot Password
Create New user
Remove "/" before Servlet URL Pattern
Change this code
protected void doPost(HttpServletRequest request, HttpServletResponse response throws
ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/WebPages/Signup.jsp");
rd.forward(request, response);
}
to
protected void doPost(HttpServletRequest request, HttpServletResponse response throws
ServletException, IOException {
getServletContext().getRequestDispatcher("WEB-INF/WebPages/Signup.jsp").forward(request, response);
}
In your login.jsp call SignUp servlet in following way
<td> Create New user </td>
and In SignUp servlet in your doGet method
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/webpages/Signup.jsp");
rd.forward(request, response);
Because when you call a servlet from a link or href it the doGet method gets run. Hope this helps

Categories