Servlet not forwarding to jsp - java

I have a couple of JSPs: home and graph.
I am calling a servlet from the home JSP using ajax: ExcelServlet.
I need to forward from the servlet to the graph JSP.
I am able to get control to the Servlet, so the mapping and the ajax calls are fine.
However this is not happening.
home.jsp:
$.ajax({
type: "get",
url: "CopyServlet",
beforeSend:function(){
$('#text3').css({"color":"red"});
$('#text3').text("Running Dynamic Diff Graph");
},
success:function(responseText){
$('#text3').css({"color":"green"});
$('#text3').text(responseText);
},
complete:function(){
$.ajax({
type: "post",
url: "ExcelServlet",
beforeSend:function(){
$('#text4').css({"color":"red"});
$('#text4').text("Preparing Difference Summary");
},
success:function(data){}
});
}
});
Excelservlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ExcelExtract excelextract = new ExcelExtract();
excelextract.extract();
String newDup=excelextract.getNewDup();
request.setAttribute("newDup", newDup);
String diff=excelextract.getDiff();
request.setAttribute("diff", diff);
String newRecNA=excelextract.getNewRecNA();
request.setAttribute("newRecNA", newRecNA);
String oldRecNA=excelextract.getOldRecNA();
request.setAttribute("oldRecNA", oldRecNA);
String unchangedRec=excelextract.getUnchangedRec();
request.setAttribute("unchangedRec", unchangedRec);
if (diff.equals("0.0")){
request.setAttribute("message", "Test Passed: 0 differences");
}
else{
request.setAttribute("message", "Test Failed: Differences found");
}
request.getRequestDispatcher("graph.jsp").forward(request, response);
}
graph.jsp
<body>
<div align="center">
<h1>Welcome to ETL Automation Testing Tool</h1>
<br>
<table border="1">
<th align="center"><b>Difference summary:</b></th>
<tr><td>${oldFile}</td></tr>
<tr><td>${newFile}</td></tr>
<tr><td>${dml}</td></tr>
<tr align="center"><td><b>Counts:</b></td></tr>
<tr>
<td>Old Records:</td>
<td>${oldRec}</td>
</tr>
<tr>
<td>Old Duplicates:</td>
<td>${oldDup}</td>
</tr>
<tr>
<td>New Records:</td>
<td>${newRec}</td>
</tr>
<tr>
<td>New Duplicates:</td>
<td>${newDup}</td>
</tr>
<tr>
<td>Differences:</td>
<td>${diff}</td>
</tr>
<tr>
<td>New Records not in old(Adds):</td>
<td>${newRecNA}</td>
</tr>
<tr>
<td>Old Records not in new(Deletes):</td>
<td>${oldRecNA}</td>
</tr>
<tr>
<td>Unchanged Records:</td>
<td>${unchangedRec}</td>
</tr>
</table>
<h3>${message}</h3>
</div>
</body>

Related

How to refresh page content after POST request without location.reload()

Goal
After a POST request, I want to update a list. For example, if a user is added, so user list must be refresh.
So I do the post request, then I do a get request to update the content.
There is a way to do it without reload the page?
Thanks for your answer!
Ajax calls
function rafraichirContenu(url, type) {
$.ajax({
url: url,
type: type
}).done(function (response) {
$(document).html(response)
});
}
postRequest().done(function(response) {
rafraichirContenu('/emprunts/encours', 'GET');
...
});
Get Mapping
#GetMapping(value = "/encours")
public ModelAndView findAllEnCours() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("emprunts", empruntResource.getEmpruntsByStatutEquals(StatutEmprunt.EN_COURS));
modelAndView.setViewName("webapp/pages/emprunts");
return modelAndView;
}
HTML
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionEmprunts">
<div class="card-body">
<table class="table">
<thead>
<tr>
<th scope="col">Usager</th>
<th scope="col">Exemplaire</th>
<th scope="col">Date de rendu</th>
<th scope="col">Statut</th>
</tr>
</thead>
<tbody>
<th:block th:each="emprunt : ${emprunts}">
<tr>
<!--/*#thymesVar id="emprunt" type="bibliotheque.model.Emprunt"*/-->
<td th:text="${emprunt.getUsager().getMail()}"></td>
<td th:text="${emprunt.getExemplaire().getOeuvre().getTitre()}"></td>
<td th:text="${emprunt.getDaterendu()}"></td>
<td th:text="${emprunt.getStatut()}"></td>
</tr>
</th:block>
</tbody>
</table>
</div>
</div>
Console error
jquery.min.js:2 Uncaught TypeError: Cannot read property 'createDocumentFragment' of null

doPost method of servlet class not giving required result

I've created a jsp login page form and I've put my logic inside the doPost(). But seems it is not working.
Even the System.out.println statement result in doPost() method is not shown in the console.
JSP page::(LogIn.jsp)
<body>
<form method="post" action="LogIn">
<table>
<tr>
<td colspan=2 align="center"
style="font-weight: bold; font-size: 20pt;" align="center"><b>User
Login Form</b></td>
</tr>
<tr>
<td colspan=2></td>
</tr>
<tr>
<td>User Name:</td>
<td><input type="text" id="txtUserName" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="txtpassword" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" id="btnSubmit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
Servlet class (LogIn.java)
#WebServlet("/LogIn")
public class LogIn extends HttpServlet {
private static final long serialVersionUID = 1L;
public LogIn() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
String UserName = request.getParameter("txtUserName");
String Password = request.getParameter("txtpassword");
System.out.println(UserName);
System.out.println(Password);
if (UserName == "Servlet" && Password == "admin") {
response.sendRedirect("Home.jsp");
Enumeration paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
String[] paramValues = request.getParameterValues(paramName);
// Read single valued data
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
{
System.out.println("no values");
}
else
System.out.println(paramValue);
} else {
// Read multiple valued data
System.out.println(".....");
for (int i = 0; i < paramValues.length; i++) {
System.out.println( paramValues[i]);
}
}
}
}
}
Web.xml file
<servlet>
<servlet-name>LogIn</servlet-name>
<servlet-class>LogIn</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogIn</servlet-name>
<url-pattern>/LogIn</url-pattern>
</servlet-mapping>
request.getParameter("txtUserName");
searches for the name = "txtUserName" attribute in input tag and similarly for password field as well, which is not present, modify the JSP code as below and it should work:
<body>
<form method="post" action="LogIn">
<table>
<tr>
<td colspan=2 align="center"
style="font-weight: bold; font-size: 20pt;" align="center"><b>User
Login Form</b></td>
</tr>
<tr>
<td colspan=2></td>
</tr>
<tr>
<td>User Name:</td>
<td><input type="text" id="txtUserName" name="txtUserName"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="txtpassword" name="txtpassword" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" id="btnSubmit" value="Submit" /></td>
</tr>
</table>
</form>
</body>

how to make an .jsp invoke a method using eclipse Google app engine

hello iam having problem invoking function in my project ![enter image description here]
<form action="register" method="post">
<table>
<tr>
<td colspan="2" style="font-weight:bold;">UserID:</td><td><input type="text" name="Id"></td>
</tr>
<tr>
<td colspan="2" style="font-weight:bold;">Name :</td><td><input type="text" name="name"></td>
</tr>
<tr>
<td colspan="2" style="font-weight:bold;">Password</td><td><input type="password" name="pass"></td>
</tr>
<tr>
<td><input type="button" value="sumbitk"></td>
</tr>
</table>
</form>
<hr>
$
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
//RequestDispatcher dispatcher;
String id=req.getParameter("id");
String name=req.getParameter("name");
String password=req.getParameter("pass");
System.out.println("user id : "+id+" name "+name+" pass "+password);
resp.sendRedirect("/index.html");
//dispatcher=getServletContext().getRequestDispatcher("/index.html");
//dispatcher.forward(req, resp);
}
}
i made form action on register and calls function post but it not seems to work when i click sumbit i dont know why .
First try write "submit" correctly in last input, if don't work try chage the type of last input to "submit" instead "button"

mixing up ajax and jsp to get data into a servlet

I've got a jsp file with two text fields (signUp and post). Now, I want the post text and the signUp text to be called to a servlet. Normally its going with request.getParameter(), but now I want the post text going to the servlet with an AJAX function and the signup text with the normal way (that means the name of the input within the jsp file and then request.getParameter).
Is it possible to mix both parts within one servlet because i have this:
<form name="form1" method="POST" action="PostWallServlet" id="form1">
form1 is the ajax code. I don't know how this should work. Normally there stands
`<form action="PostWallServlet" method="POST" >
and everything is callable through the Servlet. But, for now I don't know how I can mix up both components.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PostWall pw=new PostWall();
SimpleDateFormat df = new SimpleDateFormat("YYYY/MM/DD hh:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("Current Date Time : " + df.format(cal.getTime()));
String message = "";
String sender = request.getParameter("sender");
String post = request.getParameter("message");
String a= df.format(cal.getTime()).toString();
pw.setSender(sender);
pw.setPost(post);
pw.setDate(a);
if (pwi.addPost(pw)) {
message = "Student Successfuly Added";
} else {
message = "Student Adding Failed";
}
//RequestDispatcher rd = request.getRequestDispatcher("post.jsp");
//rd.forward(request, response);
}
$(document).ready(function(){
$('#Add').click(function(){
sendData();
});
});
function sendData(){
var mge = $('#newText').val();
alert(mge);
$.ajax({
type: "POST",
url: "PostWallServlet",
data: { message : mge }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
<form name="form1" method="GET" action="PostWallServlet" id="form1"></form>
<table border="0" width="100%">
<tr>
<td colspan="3"> ${message}</td>
</tr>
<tr>
<td>Sender</td>
<td>:</td>
<td><input type="text" name="sender" value="" size=20/></td>
</tr>
<tr>
<td>Post</td>
<td>:</td>
<td><input type="text" name="post" value="" size=500 id="newText"/ ></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" value="Add" name="Add" /></td>
</tr>
</table>
Any solutions?
Put your ending tag for form AFTER all your inputs:
<form name="form1" method="GET" action="PostWallServlet" id="form1">
...
<td><input type="text" name="sender" value="" size=20 /></td>
...
<td><input type="text" name="post" value="" size=500 id="newText" /></td>
...
<td><input type="submit" value="Add" name="Add" /></td>
...
</form>
Your inputs must be INSIDE the form, not after the form.
Also make sure to end your input tags with /> not / >. You have a space between / and > on one of them.
For the Ajax part you need to give your inputs ids as well as names:
<td><input type="text" name="sender" id="sender" value="" size=20 /></td>
And then in your Ajax function for data:
data: { sender: $('#sender').val(), post: $('#post').val() }

Submitting a Spring Form in AJax is always null

I am trying to submit a spring form via ajax but the values within the form are always coming across as null (The actual form is not null).
This is how I send the form from the JSP:
$('#fSystemSave').click(function() {
$.post("/live-application/systemSave", {systemForm: $("#systemForm").serialize()}, displayModifiedSystemResults, "html");
});
This is the form:
<form:form id="systemForm"
method="post" action="/live-application/systemSave"
commandName="systemForm">
<tr>
<td colspan="1" align="left">
<strong>SYSTEM SETTINGS</strong>
</td>
</tr>
<tr>
<td valign="top">Name: </td>
<td valign="top"><form:input path="fName" size="20" /> </td>
</tr>
<tr>
<td valign="top" align="left">
<button type="button" id="fSystemSave">Save</button>
</td>
</tr>
</form:form>
And this is the Java controller side:
#RequestMapping(value = "/systemSave", method = RequestMethod.POST)
public void saveSystem(#ModelAttribute("systemForm") SystemForm systemForm, OutputStream outputStream) throws IOException {
logger.info("Save System1: " + systemForm);
logger.info("Save System2: " + systemForm.getfName());
}
So 'Save System1' returns an Object tostring and 'Save System2' returns null. Can anyone spot what I am doing wrong?
Thanks,
I don't know Spring but I think {systemForm: $("#systemForm").serialize()} should just be $("#systemForm").serialize().

Categories