ModelAndView not working properly [duplicate] - java

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 6 years ago.
I have written the code in java. All the things are working properly. I just want to return the value of modelandview that is not returning correct web page. It is throwing blank page. The code of my controller is:
public class Part3 extends HttpServlet {
Num num = new Num();
String name[];
Record record = null;
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ModelAndView mv = new ModelAndView();
String number = request.getParameter("number");
num.setNumber((number));
Driver driver = GraphDatabase.driver("bolt://localhost", AuthTokens.basic("neo4j", "neo4j"));
Session session = driver.session();
StatementResult result = session.run("MATCH (tom {name: '" + number + "'}) RETURN tom.name, tom.born, tom.roles;");
while (result.hasNext()) {
record = result.next();
}
session.close();
driver.close();
request.setAttribute("selectObject", record);
mv.setViewName("index");
return mv;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
try {
handleRequest(request, response);
} catch (IOException ex) {
Logger.getLogger(Part3.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
My HTML page is index.html and its code is:
<form action ="number" name ="number">
<b>Enter Song ID:</b>
<input type="text" name='number' required placeholder="Enter SongID"><br /><br /><br />
<input type="submit" value="Submit" class="btn btn-primary" style="background-color: orangered"/>
</form>
${selectObject}
</div>

ModelAndView is a spring mvc object. You cannot use it in a servlet.
Your servlet is doing nothing, in a servlet you need to write to the object HttpServletResponse.
What do you try to do with this code handleRequest(request, response); ?
update :
First, In your object reponse, you can get a PrintWriter : response.getWriter(). Write response in this writer.
Second, delete ModelAndView, you don't need it. Try to understand what is a servlet before using Spring MVC.
Here is a simple example : http://www.tutorialspoint.com/servlets/servlets-first-example.htm

Related

Cannot invoke "Object.toString()" because the return value of "javax.servlet.http.HttpSession.getAttribute(String)" is null

I am trying to create a simple servlet to fetch data from JSP and creating a simple session But every time I submit the response in JSP it shows null pointer exception
My web.xml file is properly mapped
Attaching code snippet for my Servlet class and JSP form
//doGet Method Java
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
// JSP File
<form method="post" action="forgotPassword" >
<input type="text" name="userName" >
<input type="submit">[Error output of eclipse console][1]

How to update value on click in servlets? [duplicate]

This question already has answers here:
How can I share a variable or object between two or more Servlets?
(6 answers)
Closed 2 years ago.
I just want with each button click to add price value. This is my jsp:
<body>
<h1>Welcome ${user.name}</h1>
<c:forEach var="artical" items="${articals}">
<ul>
<li>${artical.name} </li>
<li>${artical.price}</li>
<li>${priceSum}</li> // i want to show value here just to test it.
</ul>
<form action="addtocart" method="POST">
<input type="hidden" name="names" value="${artical.name}"/>
<input type="hidden" name="price" value="${artical.price}"/>
<button type="submit" name="button">Add to cart</button>
</form>
</c:forEach>
And this is my servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String name = request.getParameter("names");
double price = Double.parseDouble(request.getParameter("price"));
double priceSum = 0;
priceSum += price;
session.setAttribute("names", name);
session.setAttribute("price", price);
session.setAttribute("priceSum", priceSum);
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
Now when i put priceSum outside doPost method as an attribute, it works, but i heard it shouldn't be solved like that. So how can i solve this properly and why is bad to put variable outside methods in servlets? Thanks!
I solve problem like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String name = request.getParameter("names");
double price = Double.parseDouble(request.getParameter("price"));
Double priceSum = (Double) session.getAttribute("priceSum");
if (priceSum == null) {
priceSum = 0.0;
}
priceSum+=price;
session.setAttribute("names", name);
session.setAttribute("price", price);
session.setAttribute("priceSum", priceSum);
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
Is this proper way to do it?

Integer.parseInt() doesn't parse String "id" from servlet url parameter

I have a .jsp page that lists all of my employees from a database. Next to each employee you can click on the button edit or delete, which will add an id of that employee into url param:
<%
List<Employee> employees = (List<Employee>) request.getAttribute("employees");
if (employees != null)
for (Employee employee : employees) {
%>
<tr>
<td><%=employee.getId()%></td>
<td><%=employee.getName()%></td>
<td><%=employee.getSurname()%></td>
<td><%=employee.getRegistrationDate()%></td>
<td>edit</td>
<td>delete</td>
</tr>
<%
}
%>
When I click on 'delete', the listing is being deleted straight away and I get immediately redirected back to the list of my employees, it works well.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = (int) request.getAttribute("id");
EmployeeDAO.deleteEmployee(id);
response.sendRedirect("EmployeeServlet");
}
When I click on 'edit', I see te .jsp that has the url with the correct id and it asks me to provide new name and surname of my employee:
<form action="UpdateEmployeeServlet" method="post">
Name <input type="text" name="name"><br>
Surname <input type="text" name="surname"/><br>
<input type="submit"value="Save">
Once i click 'save', I get NullPointerException. It seems like it cannot get or parse the id parameter. Where is an error in my UpdateEmployeeServlet methods?
#WebServlet("/UpdateEmployeeServlet")
public class UpdateEmployeeServlet extends HttpServlet {
public UpdateEmployeeServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
Employee employee = EmployeeDAO.getEmployeeById(id);
request.getRequestDispatcher("updateemployee.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Employee employee = new Employee((int) request.getAttribute("id"), request.getParameter("name"),
request.getParameter("surname"), Date.valueOf(request.getParameter("registration_date")));
int status = EmployeeDAO.updateEmployee(employee);
request.getRequestDispatcher("employeelist.jsp").forward(request, response);
}
}
Integer.parseInt tries to convert a String to an Integer and will throw an Exception if it fails to do so. Since you get a NullPointerException, it is clear that request.getParameter("id") is null. The reason of this is that your form does not contain any items with the name of id. Try to add a hidden input to the form there with name="id" and the correct value. It should solve your problem.
Doing form handling with Servlets is really low-level and there is no need to reinvent the wheel. You should consider using Spring MVC which has excellent support for form handling.
Having said that check the parameters of your <form>. You are handing over name, surname and submit to doPost(). There is no id given. Furthermore as pointed out already you are using request.getAttribute("id") instead of request.getParameter("id").
You could set your object to request scope in your doGet()-method: request.setAttribute("employee", employee). You would then access the fields of this object in your JSP. Add this to your form: <input type="hidden" value="${requestScope.employee.id}"/>. You should also mask your IDs (e.g. HashIds) and read about CSRF

JSP servlet not executing doPost method

I have recently started programming in java and have been trying out some JSP development. I am trying to make a login page which uses the POST method to transfer data to the servlet. Here is my code:
<form method="POST" name ="loginForm" action="userAuth">
<input type="hidden" name="userAction" value="login">
Username: <input type="text" name="txtUsername"> <br>
Password : <input type="password" name="txtPassword">
<br><input type="submit" value="Login">
</form>
The above code is from the initial login page.
The code below is from the userAuth.java file.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
String userAction = request.getParameter("userAction");
if (userAction.equals("Login")) {
String userName = request.getParameter("txtUsername");
String passWord = request.getParameter("txtPassword");
if (userName.equals("hello") && passWord.equals("hello")) {
response.sendRedirect("Homepage.jsp");
}
}
}
The problem I have is that when I input the correct username and password, the doPost method is not executed, so none of the redirects take place. Rather only the ProcessRequest method is executed which just displays the initial template to the web browser.
Thank you in advance.
P.S I am using Apache Tomcat 8.0.27.0
I have solved the issue...
The issue was with the following line
<input type="hidden" name="userAction" value="**login**">
and the subsequent processing in the second block:
if (userAction.equals("**Login**")) {}
The login value didnt have an uppercase L.
Just changed this.
What does the processRequest() method do? If executes as you say then the server gives a response to the client and the remaining block of code does not execute. Have you tried to run without this function?
Hide the process request method.
Like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
String userAction = request.getParameter("userAction");
if (userAction.equals("Login")) {
String userName = request.getParameter("txtUsername");
String passWord = request.getParameter("txtPassword");
}
}

calling 2 forms from a jsp to a controller one after another

I have created two forms in my jsp. 1st one is an upload functionality and other is the submit page functionality. My requirement is to upload the file using upload functionality. and if upload is successful . The pass the file name back to jsp and on submit button pass the file name along with other details to other page.
My code:
MyJsp.jsp
</tr>
<tr>
<td colspan="2" rowspan="2" align="center"> <form action="UploadDownloadFileServlet" method="post"
enctype="multipart/form-data" class="CSSTableGenerator">
Select the Raw Data Sheet of Customer : <input type="file"
name="fileName" class="button"> <input type="submit" value="Upload"
class="button">
</form>
<form action="DataController" method="post" >
<input type="submit" name="listUser" value="Confirm Selection"
class="button" align="middle">
</form>
</td>
</tr>
</table>
My Controller (Servlet):
UploadDownloadFileServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head></head><body>");
try {
List<FileItem> fileItemsList = uploader.parseRequest(request);
Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
while(fileItemsIterator.hasNext()){
FileItem fileItem = fileItemsIterator.next();
System.out.println("FieldName="+fileItem.getFieldName());
System.out.println("FileName="+fileItem.getName());
System.out.println("ContentType="+fileItem.getContentType());
System.out.println("Size in bytes="+fileItem.getSize());
String fileName = fileItem.getName().substring(fileItem.getName().lastIndexOf("\\") + 1);
System.out.println("FILE NAME>>>>"+fileName);
File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
System.out.println("Absolute Path at server="+file.getAbsolutePath());
fileItem.write(file);
HttpSession session = request.getSession();
session.setAttribute("Success", "Success");
getServletContext().getRequestDispatcher("/Welcome.jsp").forward(request, response);
/*out.write("File "+fileName+ " uploaded successfully.");
out.write("<br>");
out.write("Download "+fileName+"");*/
}
} catch (FileUploadException e) {
out.write("Exception in uploading file.");
HttpSession session = request.getSession();
session.setAttribute("Failed", "Failed");
getServletContext().getRequestDispatcher("/Welcome.jsp").forward(request, response);
} catch (Exception e) {
out.write("Exception in uploading file.");
HttpSession session = request.getSession();
session.setAttribute("Failed", "Failed");
getServletContext().getRequestDispatcher("/Welcome.jsp").forward(request, response);
}
out.write("</body></html>");/**/
}
}
My Next Contoller for submit button which needs value:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String upload = (String)request.getAttribute("Success");
if(upload.equalsIgnoreCase("Success")){
System.out.println("SERVLET DOPOST");
String action = (String) request.getAttribute("DownLoadToExcel");
System.out.println(action);
String[] kpi = request.getParameterValues("kpi");
how is it possible in jsp to know that upload was successful and submit should go forward else give an error.
Awaiting reply.
Thanks,
MS
First, after UploadDownloadFileServlet successfully receives and process the upload, you should make it go back to the JSP. You need to "redirect it" to "MyJsp.jsp".
HttpServletResponse.sendRedirect("MyJsp.jsp?fileName2="+fileName);
//- you can also call sendRedirect from a PrintWriter -
Then, in the 2nd form in the JSP you could use something (javascript, scriptlets, a tag library, a custom tag, etc) to detect the parameter "fileName2" and set a hidden input with the name of the file.
Keep in mind you don't sendRedirect() and forward() for the same response.
You can pass as many parameters as you want together with the file name.

Categories