Retrieving data with JSP (JSTL) from a Java MVC and JDBC [duplicate] - java

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.

Related

retrive session attribute and sort it into String [duplicate]

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 7 years ago.
I've been a PHP developer but recently need to work on some project using Google App Engine (Java). In PHP I can do something like this (in term of MVC model):
// controllers/accounts.php
$accounts = getAccounts();
include "../views/accounts.php";
// views/accounts.php
print_r($accounts);
I take a look at some demos of Google App Engine Java using Servlet and JSP. What they're doing is this:
// In AccountsServlet.java
public class AccountsServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("accountid");
// do something
// REDIRECT to an JSP page, manually passing QUERYSTRING along.
resp.sendRedirect("/namedcounter.jsp?name=" + req.getParameter("name"));
}
}
Basically in the Java case it's 2 different HTTP requests (the second one being automatically forced), right? So in JSP file I can't make use of the data calculated in the Servlet.
Is there some way I can do it similar to the PHP way?
You will need to set the data retrieved in the servlet in request scope so that the data is available in JSP
You will have following line in your servlets.
List<Account> accounts = getAccounts();
request.setAttribute("accountList",accounts);
Then in JSP you can access this data using the expression language like below
${accountList}
I would use request dispatches instead of the sendRedirect as follows
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req, res);
If you can use RequestDispatcher then you can store these values in request or session object and get in other JSP.
Is there any specific purpose of using request.sendRedirect?. If not use RequestDispatcher.
See this link for more details.
public class AccountServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Account> accounts = getAccountListFromSomewhere();
String url="..."; //relative url for display jsp page
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
request.setAttribute("accountList", accounts );
rd.forward(request, response);
}
}
What you want to do is first define an object to represent the information from getAccounts() - something like AccountBean.
Then in your servlets doPost or doGet function, use the request info to populate your AccountBean object.
You can then store the AccountBean object either in the request, session, or servlet context by using the setAttribute method, and forward the request to the JSP page.
The AccountBean data in your jsp page is extracted using the and tags.
Here might be an example of your servlet:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
// get data from request querystring
String accountId = req.getParameter("accountid");
// populate your object with it (you might want to check it's not null)
AccountBean accountBean = new AccountBean(accountId);
// store data in session
HttpSession session = req.getSession();
session.setAttribute("accountBean", accountBean);
// forward the request (not redirect)
RequestDispatcher dispatcher = req.getRequestDispatcher("account.jsp");
dispatcher.forward(req, resp);
}
Then your JSP page would have the following to display the account information:
<jsp:useBean id="accountBean" type="myBeans.AccountBean" />
Your account is <jsp:getProperty name="accountBean" property="status" />
Besides what's mentioned above about using expression lang, you can also pass attributes via request itself. In Servlet's doGet(), we write something like:
Account[] accounts = AccountManager.getAccountList();
request.setAttribute("accountList", accounts );
RequestDispatcher rd = req.getRequestDispatcher(nextJSPurl);
rd.forward(req, resp);
In JSP, we can retrieve the attribute from request:
<%
Account[] accounts= (Account[])request.getAttribute("accountList");
if (accounts.length>0) {
for (Account account: accounts) {
%>
<blockquote>account name: <%= account.getName() %></blockquote>
<%
}
}
%>
import javax.servlet.http.*;
public class AccountsServlet extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response) {
try {
// Set the attribute and Forward to hello.jsp
request.setAttribute ("somename", "someValue"); // to save your temporary calculations.
getServletConfig().getServletContext().getRequestDispatcher("/namedcounter.jsp?name=" + req.getParameter("name")).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace ();
}
}
}
In the above code servlet will not create 2 different requests. It will forward, also will retain all data from original request.
request.setAttribute ("somename", "someValue"); // to save your temporary calculations.
This is my understanding of your question - you want to redirect or dispatch to a new JSP page along with the data calculated in Servlet, right? To do so you need to set request attributes before dispatching the request.
You can set attributes using HttpServletRequest object (req.setAttribute("attribute name", "attribute value")). Attribute value can be any Java object.
You can retrieve the value by req.getAttribute("attribute name"). You'll also need to type cast the object while user getAttribute() function.
You can set the data inside java beans and easily access that data onto jsp page when control goes to jsp. set the date in java beans using setters get access those data onto jsp page by including that bean into jsp.
<%#page contentType="text/html"%>
<jsp:useBean id="man" class="beans.Person"/>
<jsp:setProperty name="man" property="*"/>
First Name: <jsp:getProperty name="man" property="firstName"/>
like this you can access as many properties your bean class can have.

Send more than one attribute for the request.setAttribute ()

I am developing a web page where on the homepage (in my case it is my "Home" servlet) I wish to present information about several tables as well as queries to them. What I have achieved is to obtain the information of my company / brands table and show the last companies added, the detail is that I do not know how to send more than one attribute for the request.setAttribute () since I want to show in my homepage information of my users table and show my featured users as well as my table news show the last post (news from suppliers). I hope and I can help myself since I am super stuck with this.
This is my code for my servlet.
public class InicioController extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rd;
//Connection DB
conexion conn = new conexion();
//send objectd Connection to the constructor of myDAO class
HomeDAO fun = new HomeDAO(conn);
List<companies> list1 = new LinkedList<>();
List<users> list2 = new LinkedList<>();
List<postNews> list3 = new LinkedList<>();
// call to the method that gets the information from my companies table
list1=fun.ShowCompanies("");
// call to the method that gets the information from my Users table
list2=fun.LastUsers("");
// call to the method that gets the information from my Posts table
list3=fun.News("");
//disconnect DB
conn.desconectar();
//how to send more than one attribute "request.setAttribute ()"
request.setAttribute("Companies", list1);
rd = request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
}
Why can't you have an object that will contain all three lists, plus whatever other objects you want to "pass" to your JSP? Your attribute will contain that single object in an attribute and the JSP can sort it out. It's good design also, because that way you have in one class, all the "parameters" that the specific JSP expects.

JSP form to display data from JDBC through java MVC

My servelet.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter( "action" );
String forward ="";
if( action.equalsIgnoreCase( "search" ) ) {
forward = FIND_COURSE;
String coursename = request.getParameter("coursename");
dao.findCourse(coursename);
}
RequestDispatcher view = request.getRequestDispatcher( forward );
view.forward(request, response);
}
The DAO has the prepared statements etc.
How can I call this in a jsp?
This is my attempt
<form action="search" method="GET">
<input type="text" name="coursename" />
<c:forEach var="course" items="${courses}">
<td>${course.coursename}</td>
Since you never showed us how you defined the courses variable, I'll just assume it's defined as (just for the sake of demonstration)
public class Course{
public String coursename;//just to match your variable
public int numOfStudents; //students attending a particular course
}
List<Course> coursesList;
Provided that your JDBC code retrieves all the courses and stores them in a List object, you still need to add that list to the current request as either an
attribute or a session (read up on JSP scoped objects)
In your servlet add
request.setAttribute("courses", coursesList);//coursesList is defined as List<Course> and has already been populated by the DAO/JDBC code
Now your table will get populated with all the courses fetched from the database.
If you want to search by course name, then simply have your DAO/JDBC code filter by course name. In your servlet just add code to check that a course name isn't empty and then add the necessary filtering logic.
Also, your form suggests that you want to call http://some_url/search (search is not a parameter but rather a part of the URL address)

simple HTML can't getJSON from servlet (java) + mysql

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.

Use an Ajax response in JSP

I have a JSP page which has nothing but a normal HTML table with five rows and five columns.
Now I am making an Ajax call and get a response back. Now once I have the response back, I need the data to be filled in appropriate cells of the table.
So my question is;
Should I use JSON for building the response?
How do I handle the data back at the JSP level. That is, once I have the response from the server?
Just as additional information, I am using DWR which is nothing but calling a Java method (which builds the response) from inside JavaScript code.
Let's consider this Java class.
class Employee
{
int id;
String eName;
// Setters and getters
}
In JavaScript, the JSON object:
var employee = {
id : null,
name : null
};
This is the call to a Java method from a JavaScript function:
EmployeeUtil.getRow(employee,dwrData);
In getRow() of the EmployeeUtil class, the return type of method will be Employee:
Employee getRow();
So using the setters of Employee set the data. dwrData is the callback function.
function dwrData(data) {
employee=data;
}
The data returned, which is an Employee bean, will be in the callback function.
Just initialize this in the JavaScript JSON object.
Use a JSON object accordingly to populate the table.
EDIT :
You can use List getRow() instead of Employee getRow(), returning a list of rows as a List instead of a Bean.
Now the response contains list as data.
Refer to Populate rows using DWR.
Check these examples to populate data in table:
DWR + Dojo Demo
Dynamically Editing a Table
Should I use JSON for building the response?
No need to pass JSON in response. Instead return a Bean of a class as mentioned above.
A list can be passed as a response, also as mentioned above.
How do I handle the data back at the JSP level. That is, once I have the response from the server.
Check the explanation above and the examples of the given links to handle the response in JSP and display the response data in a table.
DWR basics on YouTube
JSP pages are dynamically generated servlets. Once a user hits a JSP page, they receive dynamically generated HTML that no longer talks to the JSP page that generated it unless they complete an action such as hitting "refresh" or submitting a form. Check out the JSP Page at Oracle for more info and Wikipedia for a decent high level explanation of JSP technology.
To handle the AJAX, you're going to need to define a new network endpoint capable of processing the XML requests coming up from the Javascript. See this example, this library, or this JSON Example.
What I do quite frequently is setup two servlets for this situation:
MyServlet
MyAJAXServlet
MyServlet handles the normal HTTP requests and (usually) ends up using a RequestDispatcher to forward the request to a JSP.
Example:
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = -5630346476575695999L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetAndPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetAndPost(req, res);
}
private final void doGetAndPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
/*
* Handle the response here, manipulate the 'MODEL'
*/
/*
* Forward to the 'VIEW' (No Baba Wawa jokes please)
*/
RequestDispatcher rdis = req.getRequestDispatcher("Path/To/My/JSP");
rdis.forward(req, res);
}
}
Where as the AJAX servlet checks the request's parameter list for presence of a 'command':
public class MyAJAXServlet extends HttpServlet {
private static final long serialVersionUID = -5630346476575695915L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetAndPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetAndPost(req, res);
}
private final void doGetAndPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
String cmd = req.getParameter("cmd");
if (cmd == null || cmd.length() < 1) {
/* Custom fail mode here, perhaps toss back failure HTML */
return;
}
/* Easily implement command pattern here, but for simplicity, we will use an if tree */
if (cmd.equalsIgnoreCase("getSomeData")) {
String out = "<tr><td>ExampleCell in ExampleRow</td></tr>";
res.getWriter().append(out);
return;
} else if (cmd.equalsIgnoreCase("someOtherCommand")) {
/* Do something else */
}
}
}
If you format your JSP to allow for bulk replacement of html elements like so:
<table id="pleaseReplaceMyContentsTABLE">
<tr><td> </td></tr>
</table>
Then it becomes very easy to dynamically modify a web pages content (I use JQuery for this example):
var url = "http://mydomain.whatever/myapp/MyAJAXServletMappedURL?cmd=getSomeData";
$.post(url, function(data) {
//Message data a bit & display
$("#pleaseReplaceMyContentsTABLE").html(data);
});
Some limitations with sending back preformatted HTML from the AJAX Servlet:
If you are sending back a moderate to large amount of data, then your webserver will easily become overloaded when the number of clients starts to rise. Aka, it won't scale well.
Java code that is formatting HTML to send to a client can get ugly and hard to read. Quickly.
If you use DWR you don't need to use JSON, it uses internally.
Use javascript , the jsp code is out-of-scope. The page has been generated so you only can modify the DOM using javascrip
There are lot of examples doing what you need in DWR tutorials. I suppose you need just do something as:
dwrobject.funtionAjax(param,returnFunction);
...
function returnFunction(data) {
// use javascript to change the dom
}
Ajax part: We return a list of objects:
public List<IdTexto> getPaisesStartingBy(String texto,String locale){
List<IdTexto> res = new ArrayList<IdTexto>();
// Fill the array
return res;
}
The IdTexto is a simple bean with geters and setters:
public class IdTexto {
private int id;
private String texto;
private String texto2;
// getters and setters
}
And it is defined in the dwr.xml as bean:
<convert converter="bean" match="com.me.company.beans.IdTexto"/>
And the class containing the java function is defined as creator:
<create creator="new" javascript="shopdb">
<param name="class" value="com.me.company.ajax.ShopAjax"/>
</create>
In the jsp, we define a function javascript to retrieve the List of starting by some text object in this way:
shopdb.getPaisesStartingBy(req.term,'<s:text name="locale.language"/>', writePaises);
And the corresponding function to write down the texts:
function writePaides (data) {
var result="<table>";
for (i=0; i<data.length;i++) {
id = data[i].id;
texto=data[i].texto;
texto2=data[i].txto2;
// now we write inside some object in the dom
result+="<tr><td>"+id+"</td><td>"+texto+"</td><td>"+texto2+"</td></tr>";
}
result+="</table>";
$("tabla").innerHTML=result;
}
If you, instead of a bean have some other object you'll access the properties in the same way.

Categories

Resources