This question already has answers here:
How to transfer data from JSP to servlet when submitting HTML form
(4 answers)
Closed 5 years ago.
I'm writing a jsp file code that creates dropdown menus dynamically; the entries on the menus are dinamically inserted after a query executed in dao.QueriesDAO java class. Additionally, there is a search bar.
I want all the selected voices from the menus, plus the string inserted in the search bar, are sent to the servlet SearchServelt.java, contained in src/controller/SearchServlet.java, after the Search button it's clicked.
JSP file (in WebContent/jsp/homeView.jsp):
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.List, java.util.Iterator" %>
<!DOCTYPE html>
<html>
<head></head>
<body>
<jsp:include page="_header.jsp"></jsp:include>
<jsp:include page="_menu.jsp"></jsp:include>
<div style = "text-align: center">
<form action="/Search" method="post">
Search <input name="search"> <input type="submit" value="Search"/>
</form>
</div>
<div style = "text-align: center">
<%-- select value brand from drop-downlist --%>
<div style = "display: inline-block">
<%
List<String> brands = dao.QueriesDAO.getBrands();
Iterator<String> iterBrands = brands.iterator();
%>
<form name="f1" method="post" action="/Search">
Select brand:
<select name="brand">
<option value="All">All</option>
<% while(iterBrands.hasNext()){ %>
<option><%= (String) iterBrands.next() %></option>
<% } %>
</select>
</form>
</div>
<%-- select value of instrument type from drop-downlist --%>
<div style = "display: inline-block">
<%
List<String> instrumentTypes = dao.QueriesDAO.getInstrumentType();
Iterator<String> iterInstrumentTypes = instrumentTypes.iterator();
%>
<form name="f2" method="post" action="/Search">
Select instrument type:
<select name="instrumentType">
<option value="All">All</option>
<% while(iterInstrumentTypes.hasNext()){ %>
<option><%= (String) iterInstrumentTypes.next() %></option>
<% } %>
</select>
</form>
</div>
<%-- select value used from drop-downlist --%>
<div style = "display: inline-block">
<form name="f3" method="post" action="/Search">
Select used status:
<select name="used">
<option value="0">All</option>
<option value="false">Not used</option>
<option value="true">used</option>
</select>
</form>
</div>
<%-- select value product type from drop-downlist --%>
<div style = "display: inline-block">
<form name="f4" method="post" action="/Search">
Select product type:
<select name="productType">
<option value="All">All</option>
<option value="2">Professional product</option>
<option value="1">Scholastic product</option>
<option value="0">Classic product</option>
</select>
</form>
</div>
</div>
<jsp:include page="_footer.jsp"></jsp:include>
</body>
</html>
Servlet file:
package controller;
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;
#WebServlet(urlPatterns = { "/search"})
public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = -1953084286713579746L;
public SearchServlet() {
super();
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String searchParameters= request.getParameter("search");
String brandSelected= request.getParameter("brand");
String selectedInstrumentType= request.getParameter("instrumentType");
String selectedUsedStatus= request.getParameter("used");
String selectedProductType= request.getParameter("productType");
System.out.println("Inserted: " + searchParameters + ", "
+ brandSelected + ", "
+ selectedInstrumentType + ", "
+ selectedUsedStatus + ", "
+ selectedProductType + ".");
}
}
I want to be able to work with the values from the servlet and then eventually call other java methods and/or jsp files.
I don't know what is wrong, because I've seen similar questions on stackoverflow and I utilized the solution proposed.
I'll like to know what do I do of wrong and what should be a good approach to a problem like this, thank you very much.
The homeView.jsp file is called from a different servlet, HomeServlet.java. Should I use that servlet instead of a new servlet SearchServlet.java? What is better?
EDIT:
I resolved with <form action="${pageContext.request.contextPath}/search" method="get"> in the JSP page (and modified in having a single form), and accordingly I changed the SearchServlet.java method from doPost to doGet.
You need to add a form to the search input
Search <input name="search"> <input type="submit" name="submit" value="Search"/>
When the user clicks on the search button, it gets submitted to the post request of the servlet "SearchServlet". There you get the "search" parameter name which will contain the input from the user.
<form action="SearchServlet" method="post">
Search <input name="search">
<input type="submit" value="Search"/>
// here you can add other inputs like brand selected, instrumentType, productType etc...
</form>
Then from the servlet you query the database with the user input and set the results.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String brandSelected= request.getParameter("search");
//if you add more options in the form you can get those also
//query database and get arraylist of instrumentTypes by brand.
List<String> instrumentTypes = dao.QueriesDAO.getInstrumentType(brandSelected);
//set attribute for jsp
request.setAttribute("instrumentTypes", instrumentTypes);
//add the name of the jsp file you want to view the attribute you just set
RequestDispatcher rd = request.getRequestDispatcher("searchview.jsp");
rd.forward(request, response);
}
}
to view the attribute in JSP, do:
${instrumentTypes}
Related
This is my structure of the project:-
[1]: https://i.stack.imgur.com/ootY1.png
My problem is that whenever I am running my project on the server, there is an HTTP Status 404 Error.
This is the error I am getting by the server:-
The requested resource [/Doctor_Appointment_Application/Regis] is not available
I am using annotations to register my servlets and there is only a welcome file in my web.xml.
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0"
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">
<display-name>User Login</display-name>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>/JSP/login.jsp</welcome-file>
</welcome-file-list>
</web-app>
My Register Servlet:-
package com.servlet;
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 com.bean.RegisBean;
import com.dao.RegisDao;
#WebServlet("/Regis")
public class Regis extends HttpServlet {
private static final long serialVersionUID = 1L;
public Regis() {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fullname=request.getParameter("fullname");
String email=request.getParameter("email");
String username=request.getParameter("username");
String password=request.getParameter("password");
long mobile= Long.parseLong(request.getParameter("mobile"));
String address=request.getParameter("address");
String identity=request.getParameter("radio");
String specialisation=request.getParameter("special");
String degree=request.getParameter("degree");
String exp=request.getParameter("exp");
String fees=request.getParameter("fees");
RegisBean regisBean=new RegisBean();
regisBean.setFullname(fullname);
regisBean.setEmail(email);
regisBean.setUsername(username);
regisBean.setPassword(password);
regisBean.setMobile(mobile);
regisBean.setAddress(address);
regisBean.setIdentity(identity);
if(identity.equals("Doctor")) {
regisBean.setSpecialiasation(specialisation);
regisBean.setDegree(degree);
regisBean.setExperience(exp);
regisBean.setFees(fees);
}
RegisDao dao=new RegisDao();
String userRegistered=dao.registerUser(regisBean);
if(userRegistered.equals("SUCCESS"))
request.getRequestDispatcher("/JSP/conf.jsp").forward(request, response);
else {
request.setAttribute("errMessage", userRegistered);
request.getRequestDispatcher("/JSP/register.jsp").forward(request, response);
}
}
}
EDIT 1:
Register.jsp:-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registration Page</title>
<style type="text/css">
<%-- <%#include file="/CSS/register.css"%> --%>
<%#include file="/CSS/regis.css"%>
</style>
<script src='https://kit.fontawesome.com/a076d05399.js'></script>
<script>
function validate() {
var password = document.form.password.value;
var confpassword = document.form.confpassword.value;
/* if (password.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
} else */ if (password != confpassword) {
alert("Confirm Password should match with the Password");
return false;
}
}
</script>
</head>
<body>
<form name="form" action="<%=request.getContextPath() %>/Regis" method="post" onsubmit="return validate()">
Full Name: <input type="text" name="fullname" required>
<br>
<br>
Email: <input type="text" name="email" required>
<br>
<br>
Username: <input type="text" name="username" required>
<br>
<br>
Password: <input type="password" name="password" required>
<br>
<br>
Confirm Password: <input type="password" name="confpassword" required>
<br>
<br>
Mobile Number: <input type="number" name="mobile" required>
<br>
<br>
Address: <input type="text" name="address" required>
<br>
<br>
Identity: Doctor <input type="radio" name="radio" value="Doctor" required>
<div class="reveal">
Specialisation: <select name="special" class="require-if-active">
<option selected disabled>Choose...</option>
<option value="Allergist">Allergist</option>
<option value="Anesthesiologist">Anesthesiologist</option>
<option value="Cardiologist">Cardiologist</option>
<option value="Dermatologist">Dermatologist</option>
<option value="Endocrinologist">Endocrinologist</option>
<option value="Gastroenterologist">Gastroenterologist</option>
<option value="Hematologist">Hematologist</option>
<option value="Immunologist">Immunologist</option>
<option value="Internist">Internist</option>
<option value="Neurologist">Neurologist</option>
<option value="Pulmonologist">Pulmonologist</option>
<option value="Oncologist">Oncologist</option>
</select>
<br>
<br>
Degree: <select name="degree" class="require-if-active">
<option selected disabled>Choose...</option>
<option value="MBBS">MBBS</option>
<option value="BDS">BDS</option>
<option value="BAMS">BAMS</option>
<option value="BUMS">BUMS</option>
<option value="BHMS">BHMS</option>
<option value="BYNS">BYNS</option>
<option value="B.V.Sc & AH">B.V.Sc & AH</option>
</select>
<br>
<br>
Experience: <input type="number" name="exp" class="require-if-active">
<br>
<br>
Fees: <input type="number" name="fees" class="require-if-active">
</div>
Patient <input type="radio" name="radio" value="Patient" required>
<span style="color: red"><%=(request.getAttribute("errMessage") == null) ? "" : request.getAttribute("errMessage")%></span>
<br>
<br> <input type="submit" value="Register">
</form>
</body>
</html>
EDIT 2:
I just tried to do an experiment, what I did is I created another jsp file and a servlet to check if the problem is in my jsp and servlet files or not. So the same thing happened, the jsp file ran successfully but the server wasn't abl to find the servlet after submitting the form method.
Any kind of help is appreciated.
Hello to whosoever is seeing this,
I solved this query by removing the mysqljdbc.auth.dll from my build path. This solved my problem and it is working fine now. If you are having a problem with the mysqljdbc.auth.dll file, you just have to copy it in the JDK 8 bin folder and it will work fine.
Update (based on the update posted in the question):
Replace
<form name="form" action="<%=request.getContextPath() %>/Regis" method="post" onsubmit="return validate()">
with
<form name="form" action="Regis" method="post" onsubmit="return validate()">
as the paths in a JSP are already relative to the context path.
Original answer:
The reason why you are getting this error is that by default, the server gets the request as GET whereas you have not provided any implementation of doGet in your servlet. If you are calling this servlet from a JSP/HTML, make sure you mention method="POST". If you are trying to call the servlet directly, you can either rename doPost to doGet or provide an implementation of doGet e.g.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
This question already has answers here:
How can I retain HTML form field values in JSP after submitting form to Servlet?
(2 answers)
Closed 5 years ago.
So basically I have retrieved data from a database, have the values I need stored in an array. But I am having trouble setting the values in an HTML input field. I have three fields Welsh name, English name, and gender. So I need the welsh input field in the form to hold the welsh word and so on. How would I do this?
The HTML code;
<html>
<head>
<title>Academi Gymraeg</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Academi Gymraeg</h1>
<h2>Modify Vocabulary</h2>
<div class="login-form">
<div class="login-elements">
<br>
<form action="instructorServlet" name="searchVocab" method="post">
<input type="hidden" name="type" value="searchVocab" />
Word:
<input type="text" name="word" class="inputBox" required><br><br>
Language:<br>
<select name="language" class="dropDown">
<option value="English" selected>English</option>
<option value="Welsh">Welsh</option>
</select><br><br>
<button type="submit" class="button" name="search" value="search"
>Search</button><br><br>
</form>
<form action="instructorServlet" name="modifyVocab" method="get">
<input type="hidden" name="type" value="modifyVocab" />
Welsh Name:
<input type="text" name="welshName" class="inputBox" required><br><br>
English Name:
<input type="text" name="englishName" class="inputBox" required><br><br>
Gender:<br>
<select name="gender" class="dropDown">
<option value="Masculine" selected>Masculine</option>
<option value="Feminine">Feminine</option>
</select><br><br>
<button type="submit" class="subButton" name="modifyEntry" value="Modify Entry"
>Modify Entry</button>
<button type="reset" class="subButton" name="modifyEntry" value="Modify Entry"
>Reset</button>
</form><br>
<form action="instructorServlet" name="backToMenu" method="post">
<input type="hidden" name="type" value="backToMenu" />
<button type="submit" class="button" name ="backToMenu" value="backToMenu"
>Back To Menu</button>
</form>
</div>
</div>
</body>
The servlet code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String form = request.getParameter("type");
if ("searchVocab".equals(form)) {
String searchFor = request.getParameter("search");
if (searchFor != null) {
String word = request.getParameter("word");
String language = request.getParameter("language");
String values[] = database.searchFor(word, language);
response.getOutputStream().println("<script> window.location = \"modify-vocab.html\";</script>");
response.getOutputStream().println("<script> document.getElementById(\"welshName\").value = " + values[0] + ";\n"
+ " document.getElementById(\"englishName\").value = " + values[1] + ";\n"
+ " document.getElementById(\"gender\").value = " + values[2] + "; </script>");
}
}
The form reloads, however, the values aren't put into the input fields they just load blank.
Your servlet should build the values you need and forward them to the JSP view.
#Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
// ... code to build your values
// Set the values
request.setAttribute("welshName", welshName);
request.setAttribute("englishName", englishName);
request.setAttribute("gender", gender);
// Ask the view to take care of the values
request.getRequestDispatcher("view.jsp").forward(request, response);
}
Your view.
<%
final String welshName = (String) request.getAttribute("welshName");
final String englishName = (String) request.getAttribute("englishName");
final String gender = (String) request.getAttribute("gender");
%>
Welsh Name: <input type="text" name="welshName" class="inputBox" value="<% out.print(welshName); %>"/>
English Name: <input type="text" name="englishName" class="inputBox" value="<% out.print(englishName); %>"/>
Gender:
<select name="gender" class="dropDown">
<option value="Masculine" <% out.print("masculine".equals(gender) ? "selected" : ""); %>>Masculine</option>
<option value="Feminine" <% out.print("feminine".equals(gender) ? "selected" : ""); %>>Feminine</option>
</select>
I have this code
<div class="row">
<div class="col-md-10">
<form class="form-horizontal" action="ChatController">
<textarea name="bottxt" id="disabledTextInput" border="2" class="form-control col-xs-6" rows="8" cols="60"></textarea><br>
<input class="form-control" type="text" name="usertxt" placeholder="your text here">
<button type="submit" class="btn btn-success active"> Send </button>
</div>
</div>
So i have ChatController. I want to return a string every time user types something in TextBox and press "submit". How can i do that .
From what I have understood from our conversation here is your answer. First we have to convert your html page to jsp page because only jsp page can receive response send in form of request dispatcher from servlet. Here it is :-
//textView.jsp
<%#page import="model.TextBean"%>
<%#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 class="row">
<%
TextBean txt=new TextBean();
txt=(TextBean)request.getAttribute("txt");
String text="";
if(txt!=null && txt.getText()!=null){
text=txt.getText();
}
%>
<div class="col-md-10">
<textarea name="bottxt" id="disabledTextInput" border="2" class="form-control col-xs-6" rows="8" cols="60"><%=text%></textarea><br>
<form class="form-horizontal" action="ChatController" method="post">
<input class="form-control" type="text" name="usertxt" placeholder="your text here">
<button type="submit" class="btn btn-success active"> Send </button>
</form>
</div>
</div>
</body>
</html>
Then we receive the value sent from this page in a servlet. But first we have to design a java class called TextBean. Its text variable will store the value of text entered.
package model;
public class TextBean {
String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
In our servlet we assign the value received from jsp page to this bean. Then we use request dispatcher to send response back to the jsp page in form of attribute.
package controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.TextBean;
public class ChatController extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String text=request.getParameter("usertxt");
TextBean txt=new TextBean();
txt.setText(text);
RequestDispatcher rd = request.getRequestDispatcher("textView.jsp");
request.setAttribute("txt", (TextBean)txt);
rd.forward(request, response);
}
}
In jsp page we create a new TextBean and set it to the value received from servlet. Then using getter method from bean we store the text in a string variable and then display it in textarea. If it is what you want mark the problem solved by clicking right mark in left side of my answer. If it is not let me know. Happy Coding :)
I am using Liferay as platform.I have created drop down list with 2 values (true/false ("false" is selected by default)) once I click on update button , it should be updated in preferences field (i.e drop down list). I am using below code but its giving null value. I am not able to read/get selected drop down value from EditPreferences.jsp to EditController.java. If its possible to render value from Editpreferences.jsp to EditConytroller Class then That should be fine for me. thank you for any kind of suggestion.
This is my code in EditPreferences.jsp
<portlet:defineObjects />
<script type="text/javascript" src="js/jquery.js"></script>
<%#page import="javax.portlet.PortletPreferences" %>
<%
PortletPreferences pref = renderRequest.getPreferences();
String IsCollege = pref.getValue("IsCollege","");
Locale locale = renderRequest.getLocale();
ResourceBundle bundle = portletConfig.getResourceBundle(locale);
String updated = (String) request.getAttribute ("preferences-updated");
if (updated != null && updated.equals ("true")) {
%>
<div class="portlet-msg-info">
<liferay-ui:message key="preferences-update-successful" />
</div>
<%
}
%>
<portlet:actionURL var="actionOneMethodURL">
<portlet:param name="action" value="actionOne"></portlet:param>
</portlet:actionURL>
<form method="POST" action="${actionOneMethodURL}" >
<tr>
<td>
IsCollege:
</td>
<td>
<select id="IsCollege">
<option value="false" selected="selected">False</option>
<option value="true">True</option>
</select>
</td>
</tr>
<tr>
<td colspan=2>
<input type="submit" id="updateBtn" value="Update">
</td>
</tr>
</form>
EditController.java
#ActionMapping(params = "action=actionOne")
public void setPublisherPref(ActionRequest request, ActionResponse response)
throws Exception {
PortletPreferences pref = request.getPreferences();
String IsCollege = ParamUtil.getString(request, "IsCollege", "");
pref.setValue("IsCollege", IsCollege);
pref.store();
request.setAttribute("preferences-updated", "true");
}
The select tag is missing name attribute. The id, which is specified, doesn't affect parameter binding. Moreover, the name must be prefixed with portlet namespace.
<select name="<portlet:namespace/>IsCollege">
Instead of rendering the complete HTML manually, next time you may want to use aui or liferay-ui taglibs.
I have a simple select tag
Job Category:
<select name="jobCat">
<option value="tech">Technology</option>
<option value="admin">Administration</option>
<option value="biology">Biology</option>
<option value="science">Science</option>
</select>
now when the user selects a option i want to send the data to a servlet dopost method?
The above code resides in abc.jsp and the name of servlet file is pqr.java
How to perform the above action?
I have read something like
<form action="login" method="post">
UserId <input type="text/html" name="userId"/><br><br>
Password <input type="password" name="password"/><br><br>
<input type="submit"/>
</form>
and this i mapped to login servlet by
WebServlet("/login")
so when the user presses submit then the data is sent to this servlet. Now i want to achieve the same functionality with the select statement?
This is the scheduleMeet.jsp file
` <%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#page import="important.businessService.dto.Employee" %>
Insert title here
</head>
<body>
Job Category:
<form action="scheduleMeet" method="post">
<select name="jobCat">
<option value="tech">Technology</option>
<option value="admin">Administration</option>
<option value="biology">Biology</option>
<option value="science">Science</option>
</select>
</form>
</body>
</html>`
and this is the ScheduleMeetServlet.java
` package important;
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;
/**
* Servlet implementation class scheduleMeetServlet
*/
#WebServlet("/scheduleMeet")
public class scheduleMeetServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String jobCategory = request.getParameter("jobCat");
System.out.println("Job category is: " + jobCategory);
}
}
`
You can do it by using name of the select
Your select must be inside the form
<form action="login" method="post">
<select name="jobCat">
<option value="tech">Technology</option>
<option value="admin">Administration</option>
<option value="biology">Biology</option>
<option value="science">Science</option>
</select>
UserId <input type="text/html" name="userId"/><br><br> Password <input type="password" name="password"/><br><br> <input type="submit"/> </form>
In your Login servlet,
in your servlet post method just use the request.getparameter to get that value
eg
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
String selectedvalue = request.getparameter("jobCat");
// you will get that value in the string selectedvalue
}