How to run Servlet before running JSP page? - java

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}">

Related

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");

User interface does not come out when passing the value to servlet using link <a href>

I'm implementing MVC using JAVA. I want to display the details from db. I'm passing the value using link which direct to the servlet page. The details from the db come out on the screen but the problem is the user interface does not appear. I have already include all of my CSS style files in jsp pages. But when I run the page itself without connecting to servlet, the UI appear nicely.(but without it data from db)
How can I solve this? Help me.
Here are the codes;
1.jsp file(where the input value):
'
Search Patient :
<div class="col-sm-9">
<input type="text" id="empid" name="empid" placeholder="ID" class="col-xs-10 col-sm-5" />
</div>
</div>
<div class="space-4"></div>
<div class="clearfix form-actions">
<div class="col-md-offset-3 col-md-9">
Search
<button class="btn" type="reset">
<i class="ace-icon fa fa-undo bigger-110"></i>
Reset
</button>
</div>
</div>
</form>'
Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("13124124");
String forward="";
String action = request.getParameter("action");
if (action.equalsIgnoreCase("view")){
System.out.println("sdfvdsdsg");
forward = "/cms/viewempdetail.jsp";
int empid = Integer.parseInt(request.getParameter("empid"));
Employee employee = empdao.EmployeebyId(empid);
System.out.println(employee.getEmpName());
request.setAttribute("employee", employee);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
}
}
'

Why URL is changing

I have a simple servlet like this:
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "root";
private final String password = "root";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
rd.include(request, response);
}
}
Also I have login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
Username: <input type="text" name="user">
<br>
Password: <input type="password" name="pwd">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
In browser I start my app http://localhost:8080/LoginCookie/ and browser shows login.html. Then I click "Login" button and URL is changing to http://localhost:8080/LoginCookie/LoginServlet.
How do I disable it?
Instead of including your HTML, you could instead redirect to your login.html
Consider using
response.sendRedirect("login.html");
instead of rd.include()
Redirecting has the nice side-effect that reloading the page will reload login.html instead of triggering your servlet again.
If you want to stay on the same page, leave the action attribute empty into your form tag
<form action="" method="post">
But then, you have to make sure that your Servlet will receive your form. LoginServlet will not receive the form request anymore, it will be sent to Servlet mappend with the URL of your current position. So you'll have to make a Servlet receiving this info.

Conditional use of RequestDispatcher to send the same Java object across multiple JSP pages

Please bear with me as I'm very new to JSP. I thank you in advance for your help; I greatly appreciate it.
BACKGROUND
I am trying to build a web application which "remembers" certain java objects throughout a user's login session. Currently, I have a servlet which uses RequestDispatcher to send an object to a JSP page via its doPost method.
Here is the doPost of the servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String strBook = "Test Book";
// Send strBook to the next jsp page for rendering
request.setAttribute("book", strBook);
RequestDispatcher dispatcher = request.getRequestDispatcher("sample.jsp");
dispatcher.include(request, response);
}
The sample.jsp gets the strBook object, and processes it. The body of the sample.jsp looks like this:
<body>
<%
// Obtain strBook for rendering on current page
String strBook = (String) request.getAttribute("book");
/*
// TODO: A way to conditionally call code below, when form is submitted
// in order for sample2.jsp to have strBook object.
RequestDispatcher dispatcher = request.getRequestDispatcher("sample2.jsp");
dispatcher.include(request, response);
*/
%>
<h1> Book: </h1>
<p> <%=strBook%> </p>
<form action="sample2.jsp" method="post">
<input type="submit" id="buttonSubmit" name="buttonSubmit" value="Buy"/>
</form>
</body>
PROBLEM
How do I take the strBook object from within sample.jsp, and send it to the sample2.jsp WHEN the submit button is clicked (so the strBook object can be utilized in sample2.jsp)?
Currently, the body of sample2.jsp looks like this, and the strBook within is null:
<body>
<%
// Obtain strBook for rendering on current page
String strBook = (String) request.getAttribute("book");
%>
<h1> Book: </h1>
<p> <%="SAMPLE 2 RESULT " + strBook%> </p>
</body>
You could pass it as parameter to next jsp.
Sample1.jsp
<form action="sample2.jsp" method="post">
<input type="submit" id="buttonSubmit" name="buttonSubmit" value="Buy"/>
<input type="hidden" name="book" value="<%=strBook%>"/>
</form>
Sample2.jsp
<%
// Obtain strBook for rendering on current page
String strBook = (String) request.getParameter("book");
%>
<h1> Book: </h1>
<p> <%="SAMPLE 2 RESULT " + strBook%> </p>

Pass GET parameter and resultset to a servlet in 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.

Categories

Resources