Pass GET parameter and resultset to a servlet in Java - java

I want to pass two values to a servlet from a jsp page. 1- a result set value, 2- a get parameter value.
It should look something like this in jsp page:
SCcalculator.getValue(rs.getString("value1"),request.getParameter("value1"));
on the servlet side how can i receive and manipulate this data in the SCcalculator package? any suggestions please?

In your servlet class use :
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
String s = request.getParameter("value1");
String s1 = request.getParameter("value");
}
in JSP don't do like that, instead do :
<form action="name" method="post"> //here action=name is name of your servlet class name
<input type="text" name="value">
<input type="text" name="value1">
<input type="submit" value="Send">
</form>

Conside this example
<html>
<head>
<title>Demo application</title></head>
<body>
<form id = "form1" method = "GET" action = "../Sample Application">
link1 : <input type = "text" id = "nRequests" name = "nRequests" />
<input type = "submit" name = "submit" id = "submit"/>
</form></body></html>
Now how you servlet will accept the request
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
nRequests = request.getParameter("nRequests");
In this way you can get the value from a HTML page to your servlets.

Related

How to run Servlet before running JSP page?

Goal:
I have only one page and when page loads, it should run the query from servlet and display all values on index.jsp page.
Existing problem:
when i am submitting the page from "Submit" button to another page, it works fine but when i load page index.jsp with values, its gives NullPointerException because servlet didn't run before the index.jsp page.
My Servelet:
public class GetStudentController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StudentDao sd = new StudentDao(); // model
StudentInfo si = sd.getInfo();
request.setAttribute("si", si);
RequestDispatcher rd = request.getRequestDispatcher("display.jsp");
rd.forward(request, response);
}
}
my JSP:
<body>
<form action="displayStud"> <--my servlet controller name -->
Student id <input type="text" name = "sid">
<button name="test" type="submit"">Primary Button</button>
</body>
</html>
<button type="submit" class="btn btn-primary" name="action" formaction="ddd" value="find">Test2</button>
<!-- <input type ="submit" value ="Submit"> -->
</form>
StudentDao has query in there
Again:
I just want it to run the same code on page load and all data should load(without click on submit)
Thanks for the help
You can use the value set in the request scope using jstl or expression language.
request.setAttribute("si", si);
Something like:
Student id <input type="text" name = "sid" value="${requestScope.si.id}">

Servelt Page doesn't Redirect to second Page using Servlet

I am a beginner of servlet jsp. I am creating a simple login form if the login successful page redirects to the second servlet along with the username. but it doesn't work it shows the error java.lang.IllegalArgumentException: Path second does not start with a "/" character
what I tried so far I attached below.
Form
<div class="row">
<form method="POST" action="login">
<div class="form-group">
<label>Username</label>
<input type="text" id="uname" name="uname" placeholder="uname" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" id="pword" name="pword" placeholder="pword" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-success">
</div>
</form>
</div>
Login Servlet Page
#WebServlet("/login")
public class login extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String uname = request.getParameter("uname");
String pass = request.getParameter("pword");
if(uname.equals("John") && pass.equals("123"))
{
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
session.putValue("username", uname);
ServletContext context=getServletContext();
RequestDispatcher rd=context.getRequestDispatcher("second");
rd.forward(request, response);
}
}
Second Servlet Page
#WebServlet("/second")
public class second extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
String uname = (String)session.getValue("uname");
out.println("User Name is " + uname);
}
There are some big differences between redirect and forward . This article will help you to understand better your problem.
Some things to keep in mind from the article :
FORWARD
1) Request and response objects will remain the same object after forwarding. Request-scope objects will be still available (this is why if you try to add the "/" you get the 405 status - it will try to forward you to the "/second" servlet but the only request overridden is GET)
REDIRECT
1) The request is redirected to a different resource
2) A new request is created
So instead of using rd.forward I would suggest you to use the sendRedirect() method from HttpServletResponse class.
response.sendRedirect(request.getContextPath() + "/second");
AND the correct way to get the session username attribute is this:
String uname = (String) session.getValue("username");
Otherwise it will try to look after uname key which is not set. The uname was only a value mapped to the username key ( session.putValue("username",uname);
this exception indicates, path does not start with a "/".
try below instead.
RequestDispatcher rd=context.getRequestDispatcher(request.getContextPath() +"/second");

httpservlet parameter are null [duplicate]

This question already has answers here:
Http Servlet request lose params from POST body after read it once
(13 answers)
Closed 7 years ago.
I have a jsp page with a form. After submitting it is calling a httpservlet class. But all getParamter() operations are returning null. What am I doing wrong?
JSP
<form action="GatherController" method="post">
<input type='text' name="a"/>
<input type='date' name="b" />
...
<input type="submit" />
</form>
Servlet
#WebServlet(name = "GatherController", urlPatterns = { "/GatherController" })
public class GatherController extends HttpServlet {
...
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String a = request.getParameter("a");
System.out.println(a);
...
}
}
Edit
-I am using Tomcat v8.0
-doPost(...) method is executed, I am getting an output with System.out.println(a); which is null
I have no enough reputation to put comments, so I put it as answer if you don't mind.
Please make sure that you don't call other methods on httpServletRequest before, like getReader() or getInputStream(). You can't access your post parameters after these calls.
<form action="GatherController" method="post"><input type="text" name="a"/>
Please use double quotes,it might work
<html>
<h1>Register</h1><br>
<body>
<form name="userRegistration" method="post">
<input type="text" name="firstname" class="textbox" required/>
<input type="text" name="lastname" class="textbox" required/>
<input type="text" name="email" class="textbox" required/>
</form>
</body>
</html>
servlet code
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
HttpSession session = request.getSession(false);
if (//handle your logic) {
out.print("<p style=\"color:red\">Account Created</p>");
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
} else {
out.print("<p style=\"color:red\">Error Occured </p>");
RequestDispatcher rd = request.getRequestDispatcher("newuser.jsp");
rd.include(request,response);
}
}

Passing value to servlet from image

From JSP I have
..
<form action="TestMartController" method="post">
<input type="hidden" value="math">
<input type="image" src="<%=request.getContextPath()%>/css/categories/math.jpg">
</form>
..
In my servlet I have
...
private static final String MATH = "WEB-INF/jsp/math.jsp";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String forward = null;
String action=request.getParameter("action");
if(action.equals("math")){
forward = MATH;
flag = 1;
}
RequestDispatcher rd = request.getRequestDispatcher(forward);
rd.forward(request, response);
}
...
When I clicked the image I got null pointer exception. I want to know why it does not pass the value where it should. Since hidden will always get the values to pass.
your input type="hidden" field is missing a name="action" attribute. Thus, the action parameter is null.

Unable to read form field in servlet [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 7 years ago.
Hey I am quite new to servlet environment. Here I am trying to post a form to my servlet with something like this:
<form action="OnlineExam?q=saveQuestion" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Question</legend>
<textarea class="questionArea" id="question" name="question">Enter Question.</textarea>
<br class="clearFormatting"/>
Attach File<input type="file" name="file" />
<input class="optionsInput" value="Option A" name="A" onfocus = "clearValues('A')" onblur = "setValues('A')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="Option B" name="B" onfocus = "clearValues('B')" onblur = "setValues('B')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="Option C" name="C" onfocus = "clearValues('C')" onblur = "setValues('C')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="Option D" name="D" onfocus = "clearValues('D')" onblur = "setValues('D')"/>
<br/>
<input type="submit" value="Save" />
<input type="reset" value="Cancel" />
<button style="display: none" onclick="return deleteQuestion()" >Delete</button>
</fieldset>
</form>
And the servlet is something like this:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("q").equals("saveQuestion")){
saveQuestion(request);
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
public void saveQuestion(HttpServletRequest request){
Enumeration enum = request.getParameterNames();
while (enum.hasMoreElements()) {
String pName = (String) enum.nextElement();
String[] pValues = request.getParameterValues(pName);
System.out.print("<b>"+pName + "</b>: ");
for (int i=0;i<pValues.length;i++) {
System.out.print(pValues[i]);
}
out.print("<br>");
}
}
But it is printing only the q parameter not the other form fields.
I also tried to get them with the request.getParameter("question") but this was also not working. So where i am going wrong. actually i am from PHP background and recently started coding in java so please help.
Thanks in advance
When you use enctype="multipart/form-data" you can not access request parameter as you normally do[that is request.getParameter("question")]. You have to use MultipartRequest object.
And also you submit form in POST and then in servlet you redirect it to doGet. Why so? Why don't directly use GET as a method in form submit.
Demo to use MultipartRequest:
String ph="images\\";
MultipartRequest req=new MultipartRequest(request, ph);
String question=req.getParameter("question");
System.out.println("Question: "+question);
why is your form action looking like a GET request with the ?q=saveQuestion, while the form type is POST? maybe the GET parameter is ignored on this call.

Categories

Resources