This question already has answers here:
Generate an HTML Response in a Java Servlet
(3 answers)
Closed 2 years ago.
I have a form in a jsp from which i am retrieving data to servlet via doPost method, suppose username and password now there is an empty textarea field inside the same form where i want to send the username from servlet,how do i do it?
I don't really understand your case. But there're 2 common ways to send data from servlet to JSP:
Request attributes: you can use this if data is transferred along a same request.
request.setAttribute("username",obj);
request.getRequestDispatcher("url").forward(request,response);
In JSP:
<div>${username}</div>
Session attribute: use this to retain data during a session
Session session = request.getSession(true); //true: create session if not existed
session.setAttribute("username",obj);
response.sendRedirect("url"); //or use request dispatcher to forward the request
In JSP:
<div>${username}</div>
Write your Servlet class like this
public class ServletToJSP extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//communicating a simple String message.
String message = "Example source code of Servlet to JSP communication.";
request.setAttribute("message", message);
//Servlet JSP communication
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("jsp url");
reqDispatcher.forward(request,response);
}
}
jsp page
<%
String message = (String) request.getAttribute("message");
out.println("Servlet communicated message to JSP "+ message);
%>
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.
I made a LoginServlet with Java, that gets username and password from a database. Now I want to display the username on my website after logging in.
Servlet Code:
public class LoginServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
Sql2o sql2o = DatabaseConnetcionProvider.getSql2oConnection();
User user = UserDAO.findBenutzerByUsername(username, sql2o);
if(user != null && user.getPassword().equals(password)){
UserListe.getInstance().add(user);
HttpSession session = req.getSession();
session.setAttribute("user", user);
resp.sendRedirect("/public/Home.html");
} else {
resp.sendRedirect("/public/Error.html");
}
}
}
Now I want to display the username on my Website.
I hope you can help me :)
In case of JSP you can use session implicit object
<%= ((User) session.getAttribute("user")).getUsername %>
You can retrieve value in your Home.html as below
<script type="text/javascript">
$(document).ready(function() {
userName = "{{user}}";
$("#yourFieldName").val(userName);
});
</script>
if the page is static html page,the static page can not handle the servlet page scope data,use jsp or other dynamic page to handle it,freemarker,velocity is suitable.
in jsp,you can use EL Express to show the data.the format is ${sessionScope.user}.
you should review the pageScope,requestScope,sessionScope,applicationScope concept.
sendRedirect method can cause data missing in pageScope,you should choose the right scope and the redirect or forward method,test it,please.
if the page is static page,please use AJAX to send request and handle the data,jQuery library is classic.
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.
for example :
i have a js like :
$.get('Test_Controller.html',function(response){
alert(response);
});
and in my Test_Controller.html servlet i have :
request.setAttribute("test","testData");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/test.jsp");
requestDispatcher.forward(request,response);
Question is :
why is that the response will always alert the text content of the test.jsp and not the JSON that i passed through the getWriter()
EDIT :
I need to get the :
TestData testData = new TestData();
request.setAttribute("test",testData);
using jQuery's $.get() so the page won't reload, but unfortunately when i didn't do dispatch my response object seems to be null and when i do dispatch and forward, when i alert the response it alerts the text of the page.
You want to write some information from within your servlet back to the client.
Your serlvet could look like this:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("application/json");
Writer w = response.getWriter();
w.append("... your json here ....");
}
And that's all there is (obviously wiring the servlet to your URL in web.xml). Your $.get() should see whatever you write into the writer.
Note that both what's sent (in Java) and what's received (in Javascript) are TEXT strings. You're responsible to convert your data to readable JSON on the Java side, and to interpret the text as JSON on the Javascript side. The latter can be done like this:
$.get(....., function(data) {
try {
// convert the text to JSON
data = jQuery.parseJSON(data);
} catch (e) {
alert("Problem reading data: "+e);
}
... use the JSON data ...
}
In this case the final response is coming from test.jsp because you have forwarded the request to test.jsp inside that Test_Controller.html. If you want to print that json data to test.jsp then you don't need to forward that request to test.jsp page.Otherwise you can also create that json file inside
test.jsp using scriplet tag like:
<%
request.setAttribute("test","testData");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
String json = new Gson().toJson(test);
response.getWriter().write(json);
%>
Happy Coding!!!
Get the object in test.jsp .
<%
TestData testData = (TestData) request.getAttribute("test");
String testDataString = new GSON().toJson(testData);
out.println(testDataString);
%>
Javascipt USE $.getJSON instead of $.get
$.getJSON('Test_Controller.html',function(responseJSON){
alert(responseJSON);
var testData = responseJSON;// Then you can accesss your class values.
$.each(testData,function(key,value){
alert("Key:-"+key+": Value:-"+value");
} );
});
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.