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)
Related
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.
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 function say :
public void display(ActionRequest areq, ActionResponse ares) throws Exception,PortletException,IOException {
String name= areq.getParameter("name");
String add= areq.getParameter("add");
String phone= areq.getParameter("phone");
}
I have a jsp say disp.jsp which passes the user input to the above function display.
Now I after doing some processing on the above data in display() function, I want to display the results on a jsp page say new.jsp. How should I go ahead with it?
I tried something like:
areq.setAttribute("name",name);
areq.getRequestDispatcher("new.jsp").forward(areq, aresp); but it shows an error that getRequestDispatcher is not defined for actionrequest and actionresponse.
I am using liferay framework
In your action you can set attributes and set the redirect page like that:
public void display(ActionRequest aReq, ActionResponse aResp){
aReq.setAttribute("name",name);
aResp.setRenderParameter("jspPage", "/new.jsp");
}
I Usually prefer setting attributes instead of Parameters, because it allows to pass non Sting variables.
Then, in the jsp you can get the attributes
<%
String name = (String)renderRequest.getAttribute("name");
%>
Just remember to include this, to have access to renderRequest object
<portlet:defineObjects />
I'm restricted to work on an enterprise software project using Netbeans IDE, and no frameworks.
The front-end display is register.jsp. My Model package contains Customer.java class, with some getters and setters. A Data package contains 'CustomerData.java', with DB functions related to the Customer: registration, log-in, etc. CustomerData extends HttpServlet.
I need to reference a specific method from the CustomerData class from my registration form. Is this possible to do?
If this is possible to do, what should the web.xml file entry be for the servlet and servletmapping?
Here is code.
Register.jsp
<form name="loginForm" method="post" action="CustomerData/RegisterCustomer">
......
</form>
CustomerData.java skeleton:
public class CustomerData extends HttpServlet {
public void registerCustomer(HttpServletRequest request)
throws ServletException, IOException
{
// this is the method I need to reference. It creates a db connection, checks to see if
// the Customer is already in the DB, and if not, registers the user.
}
public void loginCustomer(HTTPServlet request)
throws ServletException, IOException
{
// Some other Customer data method that will need to be called from my login.jsp page
}
public void SomeOtherMethod()
{
// some helper methods or validation methods for Customer
}
}
I would recommend you the below thing.
In the JSP page you can define one parameter say opr where you can set value of the operation.
<form name="loginForm" method="post" action="CustomerData/">
<input type=hidden name=opr id=opr value=1
......
</form>
In the Servlet you can handle the operation by the operation value passed as below
public doPost(HttpServletRequest req, HttpServletResponse res){
int operation = Integer.valueOf(req.getParameter("opr"));
if (operation == 1){
registerCustomer(req);
}else if (operation == 2){
loginCustomer(req);
}else if (operation == 3){
SomeOtherMethod();
}...
}
Hope this will help you.
What you want to do can be done by using getPathInfo
Assuming your servlet mapping is
<servlet-mapping>
<servlet-name>CustomerData</servlet-name>
<url-pattern>/CustomerData/*</url-pattern>
</servlet-mapping>
Calling
String pathInfo = request.getPathInfo();
will give you the value '/RegisterCustomer' in pathInfo. From there it should be rather trivial to figure out what method needs to be called. Don't forget to ad check code to deal with all kinds of abuse that might be thrown at the servlet (eg no "method name" is given, nonexisting method names are specified, etc).
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.