using getClass().getResourceAsStream() in servlet to access json file data - java

Hi I have a json file stored in the project folder "project/file.json". How can I first, access and read the json file's data from the servlet's doGet()method. Second I want to print the returned data in a separate JSP file. I'm posting here as the last resort since I could not find anything on how to do this. here is my files and my attempt so far
here is file.json
{
"person": {
"title": "manager",
"questions": [
"name ?",
"age ?",
"hobby ?"
]
}
}
here is the doGet () method from fileServlet.java
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
response.setContentType("text/json");
/* here I'm accessing the external file JSON file*/
getClass().getResourceAsStream("project/file.json");
/* here is where I run into trouble. the StringReader() only
accepts strings and I cannot figure out how to read the table form
file.json here*/
JsonReader reader = Json.createReader(new StringReader(person));
/*the reader needs to be set inorder to create a JsonObject*/
JsonObject jsonObject = reader.readObject();
}
and finally, the JSP file. I want the file.json items to appear in this form like so
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form>
"name ?" get displayed here <br>
<input type="text" name="firstname" value="">
<br>
"age ?" get displayed here <br>
<input type="text" name="age" value="">
<br>
"hobby ?" get displayed here <br>
<input type="text" name="hobby" value="">
<br><br>
<input type="submit" value="Done">
</form>
</body>
</html>
Any help or tips will be appreciated

Related

Display error message from Servlet to JSP page without reloading the page

I have an HTML form for user login on a JSP document and I send the input of the user to a Servlet, check the password against a database then redirect the user to a new page if it's correct or show an error message on the page "Incorrect Password" of incorrect.
I want the error message to appear on the same page as the form just below the Password input field. I have tried the code below but it still redirects me to a new page where it displays only the "Incorrect Password" message.
Is there any other way on how to do it?
Thank you in advance.
//SERVLET CODE
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Some code to check if the password matches the one in the DB and redirects to another page.
} else {
String text = "Incorrect Password!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(text);
}
}
}
//JSP PAGE
<!DOCTYPE html>
<html>
<head>
<script>
$('#sButton').click(function() {
$.post('UserServlet', function(responseText) {
$('#msg').text(responseText);
});
});
</script>
<title>User Log in</title>
<%# include file="PageHeader.html" %>
</head>
<body>
<form action = "SomeServlet" method="POST">
<h3 >Enter detailsto Sign In</h3><br>
Email: <input type="text" name="email" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" name="submit" value="Sign in">
<div style="color:red" id="msg"></div>
</form>
</body>
</html>
The error message should appear on this same page as I understand but it just opens a new page showing only the message and not the html form.

Ajax post from JSP to servlet in Java?

So, here is what I want to achieve. Lets say I have a form and I fill up the details and click on submit. The data will be inserted to the database. Now,my idea is that I want to display the data I just added to the DB using ajax without having to refresh the page. I am learning the idea of working with ajax and so I am a bit lost. Can someone suggest any advise.
The idea is that when I click on submit, there will be two events that will be triggered. One is inserting the data to the db and the other getting the data from the db and displaying it inside the tags.
This is my get method in my servlet.
Home.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<html><body>");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/apiprovider","root","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from apiinfo");
// out.println("<table border=1 width=50% height=50%>");
// out.println("<tr><th>EmpId</th><th>EmpName</th><th>Salary</th><tr>");
while (rs.next()) {
String n = rs.getString("apiname");
String nm = rs.getString("apiendpoint");
int s = rs.getInt("id");
response.getWriter().write(n);
// out.println("<tr><td>" + n + "</td><td>" + nm + "</td><td>" + s + "</td></tr>");
}
// out.println("</table>");
// out.println("</html></body>");
con.close();
}
catch (Exception e) {
out.println("error");
}
}
Home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="ajaxresponse">
</div>
<form>
API Name:<br>
<input type="text" id = "apiname" name="apiname">
API ENDPOINT:<br>
<input type="text" id ="apiendpoint" name="apiendpoint">
<br>
API VERSION:<br>
<input type="text" id="apiversion" name="apiversion">
ACCESSIBLE:<br>
<input type="checkbox" name="source" value="internet"> Internet<br>
<input type="checkbox" name="source" value="vpn"> VPN<br>
<br><br>
<input type="submit" formaction="Home" method="post" value="Submit">
<br>
<input type="submit" name="Submit" value="Submit">
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#Submit').click(function(event) {
console.log("You clicked me");
$.ajax({
url: "Home",
sucess:function(result){
}
});
});
});
</script>
</body>
</html>
I think you don't need to have two events. You should send ajax call to servlet and get from it properly formatted JSON (with data from DB). In that case, when you will receive data you know that insert was successful. After that in you sucess function you need to parse response from servlet and useing javaScrip set data into elements of you form.
you can achieve this in multiple ways based on your fail over scenarios
please go through this link for better understanding of ajax with servlets. On click of submit button first insert the data into db if this call is success then trigger one more ajax call to get data from db to display please check below sudo code
<script type="text/javascript">
$(document).ready(function() {
$('#Submit').click(function(event) {
console.log("You clicked me");
$.ajax({
url: "Home",
sucess:function(result){
// here call another servlet which will get the data
}
});
});
});
</script>
if the insert call fails you can mention generic message like "insertion failed please try again later"

Tunnelling DELETE through XMLHttpRequest.setRequestHeader() for a REST call

I'm unable to perform "delete" from the HTML form. This is my HTML, what's incorrect here? , also included the RESTservice method that performs deletion. I see the POST is getting invoked after every button click. Any inputs or suggestions ?
create_todo.html
<!DOCTYPE html>
<html>
<head>
<title>Form to create a new resource</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script>
document.getElementById("delete").addEventListener("click", function () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8080/com.dcr.jersey.first/rest/todos", true);
xhr.setRequestHeader("Content-Type", "application/xml");
xhr.setRequestHeader("X-HTTP-Method-Override", "DELETE"); //X-HTTP-Method-Override
xhr.send();
},true);
</script>
</head>
<body>
<form id= "myForm" action="../com.dcr.jersey.first/rest/todos" method="post" >
<label for="id">ID</label>
<input name="id" />
<br/>
<label for="summary">Summary</label>
<input name="summary" />
<br/>
Description:
<TEXTAREA NAME="description" COLS=40 ROWS=6></TEXTAREA>
<br/>
<input type="submit" id="submit" value="Submit" /> <br/>
<button id="delete">Delete</button>
</form>
</body>
</html>
REST method for DELETE from form
#DELETE
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void delTodo(#FormParam("id") String id,
#Context HttpServletResponse servletResponse) throws IOException {
Todo c = TodoDao.instance.getModel().remove(id);
if(c==null)
throw new RuntimeException("Delete: Todo with " + id + " not found");
else servletResponse.sendRedirect("../create_todo.html");
}
RESTResourceClient to post and delete which works fine
Form form = new Form();
form.param("id","45");
form.param("summary","Summary for id 45");
response = target.path("rest").path("todos").request().post(Entity.form(form));
System.out.println("\nPost by FORM response code is "+ response.getStatus()+"\n");
response = target.path("rest").path("todos/45").request().delete();

Reload a jsp page from servlet when form data is involved

I have a jsp that calls a servlet. This servlet does some tasks and then I want to return to the page I was just at and reload it. This would be simple if I knew the exact url it would be each time using the redirectUrl. However, I can't hard code a value in this as it is dynamically created. Is there a way to do this when the previous url is Not known to me?
I am not sure if I understood you correctly, do you need move from jsp to servlet, and return to the same jsp? If this is what you need, I would put some hidden input in jsp form with path
<input type="hidden" name="jspPath" value="${pageContext.request.requestURI}"/>
So full solution is below:
page1.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${requestScope.dataFromServlet }
<form action="${pageContext.request.contextPath}/HelloWorldServlet " method="POST">
<input type="hidden" name="jspPath" value="${pageContext.request.requestURI}"/>
<input type="hidden" name="param1" value="value1"/>
<input type="submit" value="Submit">
</form>
</body>
</html>
HelloWorldServlet.java
public class HelloWorldServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String jspPath = request.getParameter("jspPath");
if(jspPath == null || "".equals(jspPath))
jspPath = "errorPage.jsp";
request.setAttribute("dataFromServlet", "Hello World");
RequestDispatcher rd = request.getRequestDispatcher(jspPath);
rd.forward(request, response);
}
}

How to map JSON object to Spring Object

How to map JSON object to Spring Object... I have AJAX, posting a JSON object to my Spring Controller but how do I make Spring turn that JSON into a Object in java
Java Code:
#RequestMapping(method=RequestMethod.POST, value="/employee")
public ModelAndView addEmployee(#RequestBody String body) {
System.out.println("in post: " + body);
Source source = new StreamSource(new StringReader(body));
System.out.println("source: " + source.toString());
//
// how do I turn the JSON String into a Java Object?
//
return new ModelAndView(XML_VIEW_NAME, "object", body);
}
JavaSript/html code:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>This is a project to show how to use RESTful</title>
</head>
<body>
<script type="text/javascript">var contexPath = "<%=request.getContextPath()%>";</script>
<script src="<%=request.getContextPath()%>/js/jquery.js"></script>
<script type="text/javascript">
function doAjaxPost() {
var queryString = $('#htmlform').serialize();
alert("doAjaxPost Called :" + queryString +":");
$.ajax({
contentType : "application/json",
dataType : 'json',
type : "POST",
url : contexPath + "/service/employee",
data : queryString, //json serialization (like array.serializeArray() etc)
success : function(data) {
alert("Thanks for submitting. \n\n" + response.result);
// response
},
error : function(request, status, error) {
alert('Error: ' + e);
}
});
}
</script>
<H1>Add Employee</H1>
<p>
<form name="htmlform" id="htmlform">
<table border=1>
<thead><tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr></thead>
<tr>
<td><input type="text" name="ID" maxlength="5" size="3"></td>
<td><input type="text" name="Name" maxlength="10" size="10"></td>
<td><input type="text" name="Email" maxlength="10" size="10"></td>
</tr>
</table>
<input type="button" value="Save Employee" onclick="doAjaxPost();" />
<p>
<p>
</form>
[List all Employees | Employee Form Test]
</body>
</html>
Make sure to:
send JSON object, not JSON String
included Jackson on your classpath
Then you can add #RequestBody Employee employee at the controller's method signature.
I suppose you're using Spring 3.0+. Take a look at Spring Source blog post on JSON simplifications. It seems that you're half way there already.
Use JSON mapping library such as Jackson or Gson
Your code would look approximately as :
Employee e;
try {
e = objectMapper.readValue(body, Employee .class);
} catch (IOException e) {
throw new IllegalArgumentException("Couldn't parse json into a employee", e);
}
If you using Spring 3 or higher, there is even simpler way to do it:
http://blog.springsource.org/2010/01/25/ajax-simplifications-in-spring-3-0/

Categories

Resources