I am trying to get JSON from a simple HTML but I can't do it successfully :c .. I generate JSON from a java Servlet, from MySQL, like this ...
Prueba.java (Servlet)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
Connection conn = ConexionBD.obtenerConexion();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM grifo where id=1");
while(rs.next()){
String grifo = rs.getString("grifo");
String distrito = rs.getString("distrito");
String latitud = rs.getString("latitud");
String longitud = rs.getString("longitud");
JSONObject json = new JSONObject();
json.put("grifo", grifo);
json.put("distrito", distrito);
json.put("latitud", latitud);
json.put("longitud", longitud);
out.print(json);
}
} catch (Exception e){
out.print(e);
}
}
So, when I run this, I get the JSON:
{"grifo":"Grifo Libertad","distrito":"San Juan de Lurigancho",
"latitud":"-123.059028347924","longitud":"93.945783454234234"}
In my java project I have another page called index.jsp, that gets the JSON.
I get the json correctly, but when I create a .html (in desktop: file:///C:/Users/Jhonatan/Desktop/prueba.html in the web browser) with the same code:
http://freetexthost.com/w2xgabhaks
I can't get the JSON, just display NOTHING! Is there a problem with the file on the server (.jsp), at some other location (desktop: .html) or maybe with the database (mysql)?
How does https://graph.facebook.com/zombies work then?
Thanks for all of you!
Have you looked at what the JS console says? My guess is that it will throw something like Origin null is not allowed by Access-Control-Allow-Origin.
JavaScript requests have a same-origin policy. What you're trying to do is a cross-origin request.
The simple fix is for your server to return the following header:
Access-Control-Allow-Origin: *
But I recommend you read all about this and understand what are the implications.
Related
This question already has answers here:
Passing parameter without use of HTML forms in JSP
(3 answers)
Closed 3 years ago.
I have been trying to pass the data from a JSP page to a Java Servlet without using form. The JSP form returns to itself (action="") and I validate the form element. Then I want to pass the inputs of the user to Java Servlet. Couldn't find a good solution. Is there any easy way?
I understand what you are looking for, if you want to pass parameters to Servlet without using form you can simple try this, but you need to add your parameters on the link
this is an example.
<a href="ServletName?theNameOfParameterToSend=TheValueOfTheParameter&anotherNameOfParameterToSend=TheAotherValueOfTheParameter>
this is real example
<a href="MyApp?currancy=usd&country=usa>Send</a>
By using this way you can't send data by String query in post, it will be always visible in the link.
Wish I was helpful.
Maybe you can try Ajax.
I use Ajax Asynchronous Verify that the account exists.
If the account does not exist, you will be prompted below.
It can pass data without refreshing the page.
Here is my related code.
public User getUserByName(String name) {
User user = null;
try {
conn = DBUtils.getConnection();
String sql = "select id,name,pwd from user_info where `name`=?";
statement = conn.prepareStatement(sql);
statement.setString(1, name);
resultSet = statement.executeQuery();
while (resultSet.next()) {
user = new User();
user.setName(resultSet.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.close(conn, statement, resultSet);
}
return user;
}
public class CheckNameServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
UserDao userDao = new UserDaoImpl();
User user = userDao.getUserByName(name);
PrintWriter pw = resp.getWriter();
if (user == null) {
pw.print(1);
} else {
pw.print(0);
}
}
}
<script type="text/javascript">
function checkName() {
var name = $("#name").val();
$.ajax({
type: "post",
url: "check",
data: {"name": name},
success: function (data) {
if (data == "0") {
$("#msg").html("");
} else {
$("#msg").html("The account does not exist, please re-enter!")
}
}
});
}
</script>
then put msg in your HTML.
Hope it can help you.
This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 4 years ago.
I'm new to Servlets and MVC web programming. So far I have developed a basic CRUD project and would like to add a search function. I would like to use a JSP file to communicate with the servlets and use the tag ( I'm having trouble wording the question, but I hope my code below will clear it up).
Part of My DAO
public List<Courses> getAllCourses() {
// TODO Auto-generated method stub
List<Courses> courseList = new ArrayList<Courses>();
try {
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery( "select * from courses" );
while( resultSet.next() ) {
Courses course = new Courses();
course.setCourseid( resultSet.getInt( "courseid" ) );
course.setCoursename( resultSet.getString( "coursename" ) );
course.setFaculty( resultSet.getString( "faculty" ) );
course.setCourseSpecification( resultSet.getString( "courseSpecification" ) );
course.setDuration( resultSet.getInt( "duration" ) );
courseList.add(course);
}
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return courseList;
}
public void findCourse(Courses course) {
try { Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery( "select * from courses where coursename=?" );
while( resultSet.next() ) {
Courses course1 = new Courses();
course1.setCourseid( resultSet.getInt( "courseid" ) );
course1.setCoursename( resultSet.getString( "coursename" ) );
course1.setFaculty( resultSet.getString( "faculty" ) );
course1.setCourseSpecification(resultSet.getString("courseSpecification"));
course1.setDuration( resultSet.getInt( "duration" ) );
}
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return;
}
Servelet
#WebServlet(name = "GetStudent", urlPatterns = {"/GetStudent"})
public class FindCourse extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB private CourseDao courseDAO;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Courses course = new Courses();
String coursename = request.getParameter("coursename");
Courses course1= courseDAO.getCourse(course, coursename);
request.setAttribute("Courses", course1);
request.getRequestDispatcher("findCourse.jsp").forward(request, response);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
JSP
<form action="FindCourse" method="GET">
<input type="text" name="coursename" />
<c:forEach var="course" items="${courses}">
<td>${course.coursename}</td>
I would love a good explanation of this code as most of it is taken from tutorials etc and I am very kean to learn. So I would like the form to take user input and retrieve the courses which match the query and display the course or possibly courses if more than one course match the name. At the moment I'm getting "resource not found" errors.
As a side question, if I'm allowed, what is the form of the data between the view and the controller? Is there a way of regulating it or forcing it to take JSON/XML? How could I make this simple MVC into a RESTFUL service? I don't expect complex answers just some pointers in the right direction. Overall I have found this very enjoyable and challenging. Thank you.
The servlet is the heart of your web application . It functions as the controller where user (http) requests are being processed and response is generated and sent back to the user (usually in the form of a JSP page but could also be an image, a pdf document, a JSON response or any other content corresponding to a predefined http MIME type).
Jsp pages basically serve two purposes: 1) They present the response content to the user and 2) They allow the user to input information that is sent to the server (and then either stored there or used for filtering so as to create different responses). A JSP page should normally not be abused and business logic should be placed into the servlet while the JSP page should only have a minimum JAVA code (this usually means that you will use JSTL and EL (Expression lanhuage) and try to avoid scriptlets as much as possible)
The model in your web application is the data you're working on. An example would be a simple POJO (e.g. Courses) which contains all the fields (and corresponding getters/setters methods) that the Course table has. Typically, the controller will through a DAO (or some other means) access this model and make changes to it.
Regarding data format, JSP is rendered on the server, so normal Java objects can be used between the servlet (controller) and JSP pages.
Of course, when you send data via a HTML form (as part of a JSP page), the form data will, by default, be sent in application/x-www-form-urlencoded format. (this would be the enctype attribute of the form element). If you're using a file upload as part of the form , you will have to set data format to multipart/form-data. (as far as I know, a browser should support only these two formats on input)
Now, when you're not using a browser and want to create a REST web service, you will have to do the serialization/deserialization manually. This will involve creating a HTTP client and making HTTP requests (GET/POST) against the URL of the REST service. The actual data will have to be serialized (as JSON, XML, application-x-www-form-urlencoded etc) and attached to the request. The response will have to be deserialized.
As far as user input processing is concerned, you should do something like
//servlet
String courseName = request.getParameter("coursename"); //get the argument
//and then modify the sql query
ResultSet resultSet = statement.executeQuery( "select * from courses where coursename='"+courseName+"'";
Note that it would be much better to use a PreparedStatement than a Statement (because a PreparedStatement is faster and more secure (against sql injection attacks)
As for the error, post the entire stack trace.
I have a html login page, where the user has to put in a number and if this number is registered in the database the user is redirected to a certain site. If the number is not in the database the user get's to see an error message. At the moment I am doing this with a java servlet a local mySql database and tomcat 8.0 and it works perfectly. But I need to use a remote database by accessing it with JSON, I filled the database with a poster addon on mozilla firefox and I can see what is in the database. So it needs to check the user input on the HTML page with the data in the database via json and grant access or not. This is my java servlet that connects to my mysql database.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class servlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String Ticketnumber = request.getParameter("Ticketnumber");
if(Ticketnumber.length() >= 16 || Ticketnumber.length() <= 14){
response.sendRedirect("http://localhost:8080/Error.html");
}
String DB_URL="jdbc:mysql://localhost/ticketnumbers";
String USER = "root";
String PASS = "password";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
final String sql;
sql = "select Ticketnumber from users where Ticketnumber='"+ Ticketnumber +"' limit 1";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
if(rs != null && rs.next()){
response.sendRedirect("http://localhost:8080/Welcome.html");
}else{
response.sendRedirect("http://localhost:8080/Error.html");
}
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
I think with "a remote database by accessing it with JSON" you mean a remote Web Service.
You will first need to download the JSON data by making a Java HTTP request and then parsing the retrieved string as JSON using a parser library (GSON is very good for this).
After that, you can do your logic and validate the Ticketnumber against the parsed JSON object.
You will not need to connect to any database since you will get the data via HTTP, the same way you get them via Poster in Firefox. Poster does not know what database (if any) is being used by the remote site, it only needs the URL.
I am trying to include several servlets in the main servlet to get finish some processs and retrieve values. In this example, I am receiving the control from a jsp file to the main servlet. After this servlet send call to the next servlet to carry out an operation related to a Java List and after returns the control to the main servlet. However, I am not able to recover the value of this List. How can I recover values from servlets that I am calling from the main servlet? The part of source code is the next:
(Main Servlet)
DeletePolicy.java:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
Client client= Client.create();
WebResource webResource= client.resource("http://localhost:8080/clientLibrary/webapi/policy");
//create an object of RequestDispatcher
RequestDispatcher rd = request.getRequestDispatcher("GetPolicy");
// send the client data available with req of delete to req of getPolicy with include()
rd.include(request, response);
// To receive the parameter from the second servlet
List<Policy> policies = (List<Policy>) request.getAttribute("policies");
printWriter.print("List of books in Delete: ");
for(Policy policy : policies) {
printWriter.println("<li>"+"ID: "+policy.getId()+"<br>"+"Max Number of Books: "+policy.getMax_books()+"<br>"+"Year of Book: "+policy.getYear_book()+"<br>"+"Activated: "+policy.getActivate()+"<br></li><br>");
}
printWriter.print("I am comming back in Delete to send a request to Delete method");
/*ClientResponse rs=webResource.accept(
MediaType.APPLICATION_JSON_TYPE,
MediaType.APPLICATION_XML_TYPE).
delete(ClientResponse.class,input);
printWriter.print("Delete a policy");*/
}
/* Include solution provided by Jozef Chocholacek: request.setAttribute("policies", policies);
GetPolicy.java(Second Servlet):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter printWriter = response.getWriter();
Client client= Client.create();
WebResource webResource= client.resource("http://localhost:8080/clientLibrary/webapi/policy");
printWriter.println("<u>Searching for current policies...</u><br>");
ClientResponse rs=webResource.accept(
MediaType.APPLICATION_JSON_TYPE,
MediaType.APPLICATION_XML_TYPE).
get(ClientResponse.class);
//ClientResponse rs = webResource.type(MediaType.APPLICATION_JSON).delete(ClientResponse.class,input);
/*Transform json to java object*/
String jsonPolicy=rs.getEntity(String.class);
Gson gson = new Gson();
Policy[] PolicyA = gson.fromJson(jsonPolicy, Policy[].class);
List<Policy> policies = Arrays.asList(PolicyA);
for(Policy policy : policies) {
System.out.println(policy.getId()+" "+policy.getMax_books()+", "+policy.getYear_book()+", "+policy.getActivate()+", ");
}
//Send List to the servlet that is calling
request.setAttribute("policies", policies);
/*Display book list in the servlet*/
printWriter.println("<h1>List of Policies</h1>");
if (policies.isEmpty()){
printWriter.println("<html><body>Sorry, we did not have any policy"+"<br>");
}else{
printWriter.println("<html><body>The complete list of policies: <br>");
printWriter.println("<ul>");
for(Policy policy : policies) {
printWriter.println("<li>"+"ID: "+policy.getId()+"<br>"+"Max Number of Books: "+policy.getMax_books()+"<br>"+"Year of Book: "+policy.getYear_book()+"<br>"+"Activated: "+policy.getActivate()+"<br></li><br>");
}
}
printWriter.println("</body></html>");
}
Thank you in advance
Cheers
Well, in your first servlet (DeletePolicy.java) you use
List<Policy> policies = (List<Policy>) request.getAttribute("policies");
but the second servlet (GetPolicies.java) does not store this list into request. You have to add
request.setAttribute("policies", policies);
into your second servlet.
I want to write a .jsp (tomcat5.5) that calls a web service (IIS in domain). I get an HTTP Error 401 Unauthorized. It seems that in order to call the web service you have to be a domain user. I want to allow access to the jsp only to domain users. The request.getRemoteUser() in the jsp returns null but not the domain user that calls the jsp.
From a web browser I call the web service and it works fine.
I am a bit confused with this. Can someone tell me how can the issue be resolved?
Do i have to make tomcat make SSO?
Thank you for your time.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter o = response.getWriter();
o.println("sstarting...");
o.println("user.name ".concat(System.getProperty("user.name")));
o.println("request.getRemoteUser() ".concat(request.getRemoteUser()));
try {
GetUserRoles getUserRolesRequest = new GetUserRoles();
getUserRolesRequest.setApplicationId(121);
getUserRolesRequest.setUserName("user");
GetUserRolesResponse getUserRolesResponse;
ServiceStub stub =new ServiceStub() ;
stub._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED,"false");
getUserRolesResponse = stub.getUserRoles(getUserRolesRequest); //IT FAILS HERE 401
String str =getUserRolesResponse.getGetUserRolesResult().toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
o.println(e.getMessage());
}
}