Servlet with jdbc response to client [duplicate] - java

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 6 years ago.
I have a database with houses, and HTML page with <SELECT>, where user need to select a district where the houses are located.
Servlet:
#WebServlet("/post")
public class HosesBaseServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
//choice from html form
String choice = request.getParameter("district");
//Database parameters
final String DB_CONNECTION = "jdbc:mysql://localhost:3306/mydb2";
final String DB_USER = "root";
final String DB_PASSWORD = "root";
Connection conn;
try {
conn = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
System.out.println("Connection available");
PreparedStatement ps = conn.prepareStatement("SELECT Square, RoomNumbers, Price FROM houses WHERE District = " + choice);
}catch (SQLException ex) {
System.out.println("Fail to connect with base");
}
}
}
How can I put SQL select results into HTML page and give it back to client?
I created class House
public class Hosue implements Serializable {
private String price;
private String square;
private String RoomNumbers;
public String getPrice() {
return price;
}
public String getSquare() {
return square;}
public String getRoomNumbers() {
return RoomNumbers;}
public void setPrice(String price) {
this.price = price;
}
public void setSquare(String square) {
this.square = square;
}
public void setRoomNumbers(String roomNumbers) {
RoomNumbers = roomNumbers;
}
}
and houses
public class Houses {
public List<House> getList() {
}
}
and add script to my html. What next, how to add information from select to this list?

You can solve your problem as said by Jeed in the previous answer. However, it would be better if you model your db entities with Java objects and use them to encapsulate information from and towards the db. You may also use the DAO programming pattern to better organize your code, thus you can define simple objects (beans) to model data (your database entities) and data access object (DAO object) in which you would encode interaction with the db (your jdbc code).
Then you will have something like this to query your db (this code will be in your servlet):
HouseDAO h=new HouseDAO(db connection param...)
ArrayList<House> list=h.selectHouses();
In the HouseDAO object you will create a method selectHouse in which you will basically move the jdbc code you have in your servlet right now. By the way, your are missing a part in which you call the method execute query from the ps object. This method returns a ResultSet object which contains the query result.
With the code above, you will have your data in the ArrayList list, and you can use the code suggested by Jeed to output it.
Clearly, if you want to avoid using jsp, you can print your html code directly in your servlet. I do not recommend this as you would merge view details with control and model code. This is not good especially if you are planning to change your view in the future.

Add result of your query to some List or custom object and set it as attribute in your request object.
request.setAttribute("result", result);
and then forward to your next page using RequestDispatcher.

Use Gson external Library for sending java-List into String form to
HTML,
Your Servlet Code looks likewise,
List<House> listofHouses = getList from Database;
Gson gson = new Gson();
String json_obj = gson.toJson(listofHouses);
response.getWriter().println(json_obj);
Your HTML(use Jquery-ajax for Handling result & send Request to
Servlet ) Code looks some what nearer likewise......
<script>
$.ajax({
url: 'Servlet.do?distinct=YOUR_SELECTED_district_NAME',
type: "POST/GET",
data: query,
dataType: 'application/json; charset=utf-8',
success: function (data) {
var returnedData = JSON.parse(data);
alert(data);
$.each(data, function(index, value) {
('#your_drop_down_tag_id').append($('<option>').text(value).attr('value', index));
});
}
});
</script>
NOTE: jquery-XXX.js file must be inclue into your project and into your html file properly.

Related

Print output in TextArea(append-way) from different class in JSP/Servlet

I have below Dynamic web project setup
Index.jsp
<form action="submitClick" method ="post"
<textarea> id="textarea" name="textarea" rows="25" cols="100">${result}</textarea>
<input type="submit">
SubmitClick.java //servlet class
public class SubmitClick extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response){
MainLogicClass mainLogic = new MainLogicClass(username,password); //let's suppose hardcoded
request.setAttribute("result", "Hello");// Hello is getting printed on textarea, but I want to print output text on textarea from MainLogicClass.
getServletContext().getRequestDispatcher("/index.jsp").forward(request,response);
}
}
MainLogicClass//different class, present in same package
public class MainLogicClass{
public MainLogicClass(String username, String password){
//DB Connection logic
System.out.println("Database Connection successful");
/* I want to print "Database Connection successful" on textarea which presents on index.jsp
And after that, I need to print few more output so that the text gets appended to textarea like-
"Database Connection successful
DB query executed
DB connection closed"
*/
}
}
How can I print text from MainLogicClass to Servlet using request.setAttribute method or any other workaround.
Constructor doesn't have any return type so instead of constructor you can create a method and put your logic code there and return some value from there . So , your method inside MainLogicClass will look like somewhat below :
public String Something(String username, String password){
String msg = "" ;
msg +="Something to return";
msg +="soemthing more";
//your logic code
return msg;//return back
}
And then in your servlets doPost method do like below :
MainLogicClass mainLogic = new MainLogicClass();
String message = mainLogic.Something(String username, String password);//call that function
request.setAttribute("result", message );

Is there any way to write custom or native queries in Java JPA (DocumentDbRepository) while firing a query to azure-cosmosdb?

Connected to azure-cosmosdb and able to fire default queries like findAll() and findById(String Id). But I can't write a native query using #Query annotation as the code is not considering it. Always considering the name of the function in respository class/interface. I need a way to fire a custom or native query to azure-cosmos db. ?!
Tried with #Query annotation. But not working.
List<MonitoringSessions> findBySessionID(#Param("sessionID") String sessionID);
#Query(nativeQuery = true, value = "SELECT * FROM MonitoringSessions M WHERE M.sessionID like :sessionID")
List<MonitoringSessions> findSessions(#Param("sessionID") String sessionID);
findBySessionID() is working as expected. findSessions() is not working. Below root error came while running the code.
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property findSessions found for type MonitoringSessions
Thanks for the response. I got what I exactly wanted from the below link. Credit goes to Author of the link page.
https://cosmosdb.github.io/labs/java/technical_deep_dive/03-querying_the_database_using_sql.html
public class Program {
private final ExecutorService executorService;
private final Scheduler scheduler;
private AsyncDocumentClient client;
private final String databaseName = "UniversityDatabase";
private final String collectionId = "StudentCollection";
private int numberOfDocuments;
public Program() {
// public constructor
executorService = Executors.newFixedThreadPool(100);
scheduler = Schedulers.from(executorService);
client = new AsyncDocumentClient.Builder().withServiceEndpoint("uri")
.withMasterKeyOrResourceToken("key")
.withConnectionPolicy(ConnectionPolicy.GetDefault()).withConsistencyLevel(ConsistencyLevel.Eventual)
.build();
}
public static void main(String[] args) throws InterruptedException, JSONException {
FeedOptions options = new FeedOptions();
// as this is a multi collection enable cross partition query
options.setEnableCrossPartitionQuery(true);
// note that setMaxItemCount sets the number of items to return in a single page
// result
options.setMaxItemCount(5);
String sql = "SELECT TOP 5 s.studentAlias FROM coll s WHERE s.enrollmentYear = 2018 ORDER BY s.studentAlias";
Program p = new Program();
Observable<FeedResponse<Document>> documentQueryObservable = p.client
.queryDocuments("dbs/" + p.databaseName + "/colls/" + p.collectionId, sql, options);
// observable to an iterator
Iterator<FeedResponse<Document>> it = documentQueryObservable.toBlocking().getIterator();
while (it.hasNext()) {
FeedResponse<Document> page = it.next();
List<Document> results = page.getResults();
// here we iterate over all the items in the page result
for (Object doc : results) {
System.out.println(doc);
}
}
}
}

How to call action after selecting values from dynamically created dropdown list using struts2

Here I have created dynamic dropdown list using this link, but when I select some value from available list it should be called in action class.
The dropdown list which can be seen in the image ,here the values are loaded dynamically from the database and now what I want is when I select any value from that two dropdown list that values (I mean text value) should be sent to the action class and there I will execute one JDBC select query on the basis of this two values and will display in the table shown in the image but everything should be on load.Action should be on selecting values from dropdown list not on any button click .With static values I am able to call value from dropdown list into action class with name attribute.But in this case I cannot :(
I hope I am clear now .
I have tried calling select tag using listkey,name and id but none of them worked .
Below is my JSP code:
<div>
<div class="invoicetext1">Event Name :</div>
<s:select name="dp.eventState"
list="%{state}"
class="billlistbox1"
id="eventName" />
<div>
<s:select name="dp.companyState"
class="billlistbox2"
listKey="companyState"
list="%{status}">
</s:select>
</div>
<div class="invoicetext2">Company Name :</div>
<div class="clear"></div>
</div>
<s:form action="ActionSelect">
<s:submit value=" Click Here"/>
</s:form>
<div>
Action class for loading dynamic dropdown list :
package com.ca.actions;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.ca.database.Database;
import com.ca.pojo.Event;
import java.sql.PreparedStatement;
import com.opensymphony.xwork2.ActionSupport;
public class RetrieveEvNaCoNaAction extends ActionSupport {
private static final long serialVersionUID = -5418233715172672477L;
List<Event> dataForBillsJspList;
private List state = new ArrayList();
private List status = new ArrayList();
String eventName;
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public RetrieveEvNaCoNaAction() {
// TODO Auto-generated constructor stub
}
public List<Event> getDataForBillsJspList() {
return dataForBillsJspList;
}
public void setDataForBillsJspList(List<Event> dataForBillsJspList) {
this.dataForBillsJspList = dataForBillsJspList;
}
public List getStatus() {
return status;
}
public void setStatus(List status) {
try {
Database database = new Database();
Connection con = database.Get_Connection();
PreparedStatement ps = con
.prepareStatement("SELECT EVENT_NAME,COMPANY_NAME,date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom,date_format(TO_DATE,'%d/%m/%Y') as dateAsTo FROM EVENT");
ResultSet rs = ps.executeQuery();
//dataForBillsJspList = new ArrayList<Event>();
while (rs.next()) {
/*dataForBillsJspList.add(new Event(rs.getString("EVENT_NAME"),
rs.getString("COMPANY_NAME"), rs
.getString("dateAsFrom"), rs
.getString("dateAsTo")));
System.out.println(rs.getString("EVENT_NAME"));*/
status.add(rs.getString("COMPANY_NAME"));
}
System.out.println("Data Collected ...");
}catch(Exception e)
{
e.printStackTrace();
}
}
public List getState() {
return state;
}
#Override
public String execute() throws Exception {
// TODO Auto-generated method stub
setState(this.state);
setStatus(this.status);
return "success";
}
public String showEventDetails(){
System.out.println("Hi.."+eventName);
return SUCCESS;
}
public void setState(List state) {
//implement the application specific logic to
try {
Database database = new Database();
Connection con = database.Get_Connection();
PreparedStatement ps = con
.prepareStatement("SELECT EVENT_ID,EVENT_NAME,COMPANY_NAME,CONTACT_PERSON,CONTACT_NO,EMAIL_ID,EVENT_VENUE,date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom,date_format(TO_DATE,'%d/%m/%Y') as dateAsTo ,EVENT_TIME FROM EVENT");
ResultSet rs = ps.executeQuery();
dataForBillsJspList = new ArrayList<Event>();
while (rs.next()) {
dataForBillsJspList.add(new Event(rs.getString("EVENT_ID"),rs.getString("EVENT_NAME"),
rs.getString("COMPANY_NAME"),rs.getString("CONTACT_PERSON"),rs.getString("CONTACT_NO"),rs.getString("EMAIL_ID"),rs.getString("EVENT_VENUE"), rs
.getString("dateAsFrom"), rs
.getString("dateAsTo"),rs.getString("EVENT_TIME")));
//System.out.println(rs.getString("EVENT_NAME"));
state.add(rs.getString("EVENT_NAME"));
System.out.println(rs.getString("EVENT_ID"));
}
System.out.println("Data Collected ...");
}catch(Exception e)
{
e.printStackTrace();
}
//Here for displaying the data on UI, we are using few hardcoded values//
}
}
After loading dynamic dropdown list now i am trying to call selected value in action class by S.O.P but it gives null pointer exception. Below is my POJO class:
package com.ca.pojo;
public class Dropdown
{
private String eventState;
private String companyState;
public Dropdown() {
// TODO Auto-generated constructor stub
}
public String getEventState() {
return eventState;
}
public void setEventState(String eventState) {
this.eventState = eventState;
}
public String getCompanyState() {
return companyState;
}
public void setCompanyState(String companyState) {
this.companyState = companyState;
}
}
and below is action class where I am trying to call that selected value by using name attribute :
package com.ca.actions;
import com.ca.pojo.Dropdown;
import com.opensymphony.xwork2.ActionSupport;
public class DropdownAction extends ActionSupport
{
Dropdown dp;
public DropdownAction() {
// TODO Auto-generated constructor stub
}
public Dropdown getDp() {
return dp;
}
public void setDp(Dropdown dp) {
this.dp = dp;
}
#Override
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println(dp.getEventState());
return "success";
}
}
struts.xml is properly configured. Now after selecting two values I want to display data in the below table accordingly without any button click but in jsp i have created button just to see whether i am getting the selected value in action class but in actual i want it without any button click.
Well, there is a huge mess here :D
First of all, the NullPointerException is thrown because the values are not sent, and the values are not sent because they're not in the form.
You should enclose them in the form like this for them to be sent to the ActionSelect action:
<s:form action="ActionSelect">
<div class="invoicetext1">Event Name :</div>
<s:select name="dp.eventState"
list="%{state}"
class="billlistbox1"
id="eventName" />
<div>
<s:select name="dp.companyState"
class="billlistbox2"
listKey="companyState"
list="%{status}">
</s:select>
</div>
<div class="invoicetext2">Company Name :</div>
<div class="clear"></div>
</div>
<s:submit value=" Click Here"/>
</s:form>
Solved the mistery, this doesn't solve your problem, though.
You have two main ways to contact actions from a page:
Using a standard submit (as you're doing):
you either submit a form with its content, or call a link by eventually passing parameters in the querystring. This creates a Request, that will contact an action, that will return an entire JSP, that will be loaded in place of the page you're on now.
Using AJAX:
you POST or GET to an action without changing the current page, and the action can return anything, like a JSP snippet, a JSON result, a binary result (through the Struts2 Stream result), etc...
You then can choose what to do with the returned data, for example load it inside a <div> that before was empty, or had different content.
Now your problem is that you're contacting an action that is not the one you're coming from (is not able to re-render the entire JSP you're on) and you're calling it without using AJAX, then whatever the object mapped to the "success" result is (the whole JSP, or a JSP snippet), it will be loaded in place of the JSP you're on, and it will fail.
Since you seem to be quite new to this, I suggest you start with the easy solution (without AJAX), and after being expert with it, the next time try with AJAX.
That said,
avoid putting logic in getters and setters;
avoid calling methods that are not setter as setters (setState, setStatus...);
always make your attributes private;
try giving speaking names to variables: state and status for event states and company states are really confusing; and what about "state" instead of "name" (in jsp and on DB is "name");
consider loading informations like selectbox content in a prepare() method, so they will be available also in case of errors;
you're not closing the connections (and BTW it would be better to use something more evoluted, like Spring JDBC, or better Hibernate, or even better JPA, but for now keep going with the raw queries)
The following is a refactoring of your code to make it achieve the goal. I'll use #Getter and #Setter only for syntactic sugar (they're Lombok annotations, but you keep using your getters and setters, it's just for clarity):
<head>
<script>
$(function(){
$("#event, #company").on('change',function(){
$("#myForm").submit();
});
});
</script>
</head>
<body>
<form id="myForm">
<div>
...
<s:select id="event" name="event" list="events" />
...
<s:select id="company" name="company" list="companies" />
...
</div>
</form>
<div>
...
Table - iterate **dataForBillsJspList** here
...
</div>
</body>
public class RetrieveEvNaCoNaAction extends ActionSupport {
private static final long serialVersionUID = -5418233715172672477L;
#Getter private List<Event> dataForBillsJspList = new ArrayList<Event>();
#Getter private List<String> events = new ArrayList<String>();
#Getter private List<String> companies = new ArrayList<String>();
#Getter #Setter private String event = null;
#Getter #Setter private String company = null;
#Override
public void prepare() throws Exception {
Connection con;
try {
con = new Database().Get_Connection();
// load companies
PreparedStatement ps = con.prepareStatement("SELECT DISTINCT company_name FROM event");
ResultSet rs = ps.executeQuery();
while (rs.next()) { companies.add(rs.getString("company_name")); }
// load events
ps = con.prepareStatement("SELECT DISTINCT event_name FROM event");
rs = ps.executeQuery();
while (rs.next()) { events.add(rs.getString("event_name")); }
} catch(Exception e) {
e.printStackTrace();
} finally {
con.close();
}
}
#Override
public String execute() {
Connection con;
try {
con = new Database().Get_Connection();
// load the table. The first time the table is loaded completely
String sql = "SELECT EVENT_ID, EVENT_NAME, COMPANY_NAME, CONTACT_PERSON, CONTACT_NO, EMAIL_ID, EVENT_VENUE, " +
"date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom, date_format(TO_DATE,'%d/%m/%Y') as dateAsTo ,EVENT_TIME " +
"FROM event";
String where = "";
// if instead this action has been called from the JSP page,
// the result is filtered on event and company:
if (event!=null && company!=null) {
where = " WHERE event_name = ? AND company_name = ?";
}
// load companies
PreparedStatement ps = con.prepareStatement(sql + where);
if (where.length()>0) {
ps.setString(1,event);
ps.setString(2,company);
}
ResultSet rs = ps.executeQuery();
while (rs.next()) {
dataForBillsJspList.add(new Event(rs.getString("EVENT_ID"),rs.getString("EVENT_NAME"),rs.getString("COMPANY_NAME"),
rs.getString("CONTACT_PERSON"),rs.getString("CONTACT_NO"),rs.getString("EMAIL_ID"),
rs.getString("EVENT_VENUE"), rs.getString("dateAsFrom"), rs.getString("dateAsTo"),
rs.getString("EVENT_TIME")));
}
} catch(Exception e) {
e.printStackTrace();
} finally {
con.close();
}
return SUCCESS;
}
}
It is a kickoff example, but it should work.
The next steps are:
create a POJO with id and description, show the description in the select boxes, but send the id
use header values ("please choose an event"...) and handle in action conditional WHERE (only company, only event, both)
PAGINATION
Good luck
Using Javascript/jQuery you can do this, it depends on what you want to do after reached action class.
If you want to navigate to another page use the code below.
Add onchange event as an attribute to your dropdown,
onchange="customFunction(this.value)"
create customFunction in header part,
function customFunction(selectedValue){
window.location="Action_URL?myValue="+selectedValue;
}
Or if you want to return back the same page use jQuery ajax,
$("#eventName").change(function(e){
var selectedValue = $(this).val();
$.ajax({
type : 'post',
url : 'Action_URL',
data: { myValue: selectedValue},
success : function(data) {
alert(data);
console.log(data);
}
});
});
Hope this helps.

Java - get garbled result(List) from MySQL

The result should be like [1,2,3,4],
but i get garbled result like this
[com.test.db.Network#383c7b61, com.test.db.Network#7f87898,
com.test.db.Network#6b93f47a, com.test.db.Network#50fb09cc]
Below is my related class
private static void doLocationList(PrintWriter responseOut) throws Exception
{
//---testing show network ID list
int x=0;
Network network = new Network();
responseOut.println("this is I: " +network.getNetworkID(x));
......
}
This is from another class
public static List<Network> getNetworkID(int networkID) throws Exception
{
List<Network> idList = new ArrayList<Network>();
Connection conn = getConnection();
PreparedStatement Statement = conn.prepareStatement("Select id from network");
ResultSet result = Statement.executeQuery();
while(result.next()) {
Network network = new Network();
network.setId(result.getInt("id"));
idList.add(network);
}
return idList;
}
Any idea? Please help.
If you want to print the list of objects directly, you need to override the toString() method in the Network class and specify how to print the values when an object of this class is printed directly.
The default toString() method is as shown in Object class docs. Have a look at this post about toString()

Jersey delivers an empty JSON

I'm working on a project for the university which makes me mad. I need to develop a webservice with jersey, but every request sends me just this empty JSON:
[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]
The database query is test and delivers content. I just don't know what it could be.
Java:
#Path("/getFachbereiche")
public class GetFachbereiche {
#GET
#Produces("application/json")
public Fachbereich[] getFachbereiche() {
List<Fachbereich>fList = new ArrayList<Fachbereich>();
Connection conn = MySQLConnection.getInstance();
if (conn != null) {
try {
// Anfrage-Statement erzeugen.
Statement query;
query = conn.createStatement();
// Ergebnistabelle erzeugen und abholen.
String sql = "SELECT * FROM Fachbereich";
ResultSet result = query.executeQuery(sql);
//Ergebniss zurückliefern
while (result.next()) {
fList.add(new Fachbereich(result.getInt(1), result.getString(2)));
}
} catch(SQLException e) {
e.printStackTrace();
}
}
return fList.toArray(new Fachbereich[fList.size()]);
}
}
Your attributes from Fachbereich are private, by default, private attributes are not serialized.
You have two solutions :
Put XmlElement annotation on each attribute so it will be serialized
Or define a public getter for each attribute.

Categories