$.getJSON not retrieving data from Struts 2 Action Class to JSP Page - java

I want to retrieve fields from Struts2 Action class in my jsp page.
My JavaScript code of JSP is able to trigger it's action class, but not showing set field value from action class to jsp page on calling the Id of supposed element through JavaScript.
My console is showing everything fine. I have gone through various examples & don't know why I run into same problem all time. I'm not able to figure out the exact problem.
Here is my code:
In new.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>getJSON example</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<s:select label="Category" id="category" name="category" list="{'Select','Animal','Bird'}"></s:select><br/>
<s:textfield label="Field1" id="field1" name="field1" ></s:textfield>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#category',function(){
var JScategory=$(this).val();
$.getJSON("getfield",
{category:JScategory},
function(data){
$('#field1').html(field);
});
}
);
});
</script>
</body>
</html>
In struts.xml:
<package name="jsonpack" namespace="/" extends="json-default">
<action name="getfield" class="com.mobile.TestDropDown">
<result type="json" name="success"></result>
</action>
</package>
Action Class:
package com.mobile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.db.AdDAO;
import com.opensymphony.xwork2.ActionSupport;
public class TestDropDown extends ActionSupport{
private String category;
private String field;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
#Override
public String execute() throws Exception {
System.out.println("cat:"+category);
if(category.equals("Animal")){
field="Tiger";
}else if(category.equals("Bird")){
field="Eagle";
}
return SUCCESS;
}
}

I don't see where you are initializing your field JS variable in the line:
$('#field1').html(field);
What is the value of field here?

The value from the category you should get as
var JScategory=$("#category").val();
and use
$.getJSON("<s:url namespace='/' action='getfield'/>", { category: JScategory })
.done(function(json) {
console.log( "JSON Data: " + json );
$("#field1").val(json.field);
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});

Every thing is ok just Use this
$('#field1').val(data.field);
Instead of
$('#field1').html(field);
Because the json returned with url
http://localhost:8083/yourProjectName/getfield?category=Bird is
{"category":"Bird","field":"Eagle"}
So to get Eagle in textbox we access variable data.field
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#category',function(){
var JScategory=$(this).val();
$.getJSON("getfield",
{category:JScategory},
function(data){
$('#field1').val(data.field);
});
}
);
});
</script>
Also let us know if you get any error or it is not working.

it return json Object,so,you should do following steps,it works fine.
json Object contains key and value,so to need to iterate the your data.then set into your field.
function(data) {
//it is Json Data
$.each(data,function(key,value){
$('#field1').val(value);
});
});

Are you missing your action suffix ? The default is .action
Try
$.getJSON("getfield.action",
{category:JScategory},
function(data){
$('#field1').html(field);
});

Related

Spring MVC modelAndView object in javascript

Problem:
I have a simple controller which returns me a list of hardcoded locations. When i want to get my locations in my javascript file using $.get and print it in my console, i get some weird "undefined" results.
Controller:
#RestController
#RequestMapping("/locationOverview")
public class LocationOverviewController {
private LocationGuide service;
public LocationOverviewController() {
this.service = new LocationGuide("Memory");
}
#RequestMapping(method = RequestMethod.GET)
protected ModelAndView getLocations() {
ArrayList<Location> locations = new ArrayList<Location>();
locations.add(new Location(1,"KHL",new Geolocation(51,51)));
locations.add(new Location(2,"KUL",new Geolocation(51,51)));
return new ModelAndView("locationOverview", "locations", locations);
}
}
mapScript JS:
function initialize() {
$.get("locationOverview.htm", function(data){
for(var i=0; i<data.length; i++){
console.log(data[i].name);
}
})
}
JSP file:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="domain.Location"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Leuven Speaks</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<script type="text/javascript" src="<c:url value="/js/mapScript.js" />"></script>
</head>
<body onload="initialize()">
<jsp:include page="header.jspf"/>
</body>
</html>
You should actually inspect with dev tools what that data contains. The controller method you show us looks like it is not the one mapped to locationOverview.htm. If you want to query data with ajax, return the list using the #ResponseBody annotation instead.
Data passed in a model would be available in the JSP page that you define as the view in ModelAndView.
Some learning resources:
http://www.beingjavaguys.com/2014/05/json-response-with-responsebody_31.html
https://developer.chrome.com/devtools/docs/javascript-debugging

How to fetch data entries from mysql in jsp using struts2 in eclipse environment?

EventDropDown.java //Page 1
package com.tutorialspoint.struts2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
//import java.util.List;
import com.mysql.jdbc.ResultSetMetaData;
import com.opensymphony.xwork2.ActionSupport;
#SuppressWarnings("serial")`enter code here`
public class EventDropdownAction extends ActionSupport {
ArrayList<Event> eventList=new ArrayList<Event>();
public ArrayList<Event> getList() {
return eventList;
}
public void setList(ArrayList<Event> eventList) {
this.eventList = eventList;
}
private String eventName;
public String execute()
{
logger.info("Message-execute");
return "";
}
public String getEventList()
{
Connection conn = null;
try {
String URL = "jdbc:mysql://localhost:3306/bookmyshow_dates";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, "dra2", "dr#2");
"CASE \r\n" +
" WHEN DATEDIFF(DATE,NOW()) = 0 THEN CONCAT('Today',',',DAY(DATE),' ',MONTHNAME(DATE))\r\n" +
" WHEN DATEDIFF(DATE,NOW()) = 1 THEN CONCAT('Tomorrow',',',DAY(DATE),' ',MONTHNAME(DATE))\r\n" +
" WHEN DATEDIFF(DATE,NOW()) > 1 THEN CONCAT(DAYNAME(DATE),',',DAY(DATE),' ',MONTHNAME(DATE))\r\n" +
"END AS EventDay\r\n" +
"FROM EVENTS\r\n" +
"WHERE DATE_FORMAT(DATE,'%d/%m/%Y') >= DATE_FORMAT(NOW(),'%d/%m/%Y')";
String sql ="SELECT * FROM user3333";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
int rowCount=0;
if(rs.last()){
rowCount= rs.getRow();
} else {
rowCount= 0; //just cus I like to always do some kind else statement.
}
while (rs.next()) {
Event objEvent=new Event();
objEvent.setEventId(rs.getInt("EventId"));
objEvent.setEventName(rs.getString("EventName"));
objEvent.setEventDay(rs.getString("EventDay"));
Event objEvent=new Event(rs.getInt(1),rs.getString(2));
eventList.add(objEvent);
ret = SUCCESS;
}
} catch (Exception e)
{
ret = ERROR;
return "error";
}
finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
return "eventDropdown";
}
}
Event.java //Page 2
package com.tutorialspoint.struts2;
public class Event {
public int EventId;
public String EventName,EventDay;
Event()
{
this.EventId = 0;
this.EventName = "";
}
Event(int eventId, String eventName)
{
this.EventId = eventId;
this.EventName = eventName;
}
public int getEventId() {
return EventId;
}
public void setEventId(int id) {
this.EventId = id;
}
public String getEventName() {
return EventName;
}
public void setEventName(String name) {
this.EventName = name;
}
public String getEventDay() {
return EventDay;
}
public void setEventDay(String eventDay) {
this.EventDay = eventDay;
}
}
Error.jsp //Page 3
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
error page.
</body>
</html>
**Success.jsp** //Page 3
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
success page.
</body>
</html>
EventDayDropdown.jsp //Page 4
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:select name="username" label="Username" list="{'Mike','John','Smith'}" />
<br>
<s:select label="Select Event" name="ddlEvent" headerKey="0" headerValue="--Select--" list="{eventList}" listKey="{EventId}" listValue="{EventName}"/>
<%-- <s:select label="Select Event" name="ddlEvent" headerKey="0" headerValue="--Select--" list="{eventList}" /> --%>
<%-- <s:select name="event" list="eventList" listKey="eventId" listValue="eventName" headerKey="0" headerValue="--Event--" label="Select a event" /> --%>
</body>
</html>
Struts.xml //Page 5
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="helloworld" extends="struts-default">
<action name="event" class="com.tutorialspoint.struts2.EventDropdownAction"
method="getEventList">
<result name="success">/success.jsp</result>
<result name="failure">/error.jsp</result>
<result name="eventDropdown">/EventDayDropdown.jsp</result>
</action>
</package>
</struts>
These are files that is done with struts 2 in Eclipse IDE.
My database contains
3 Columns with atrributes
Event_Id 1, 2, 3, 4
EventName 2 states, Hobbit, Gravity,Gladiator.
Dates 20/5/2014, 21/5/2014, 21/5/2014, 23/5/2014
Like this.
Please help me. I am beginner.
Try trace your code block by block my using logging framework or simply System.out.println statements and but them in the start middle before db call after db call during db fetch and before return from the methods and see, what are exactly your problems? is it in the db or from struts2 or from Java code.
Another solution is to create separate applications, create a standlone project to fetch data from mysql database and test it in the console and create a a struts2 project with static
contents instead of trying fetching the data from database and see if the web application
provide what you need. Finally join both projects. so if any errors happened you can solve
it separately.

Pass string from .JSP form to .Java class and execute main argument

Here is my index.jsp
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="ContentLoader" class="com.content.ContentLoader" scope="session"/>
<jsp:setProperty name="ContentLoader" property="*"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Content Loader</title>
</head>
<body>
<h1>Content API: Loader</h1>
<a>Select a CSV file from your computer.<br>
Enter the API key and secret for your account<br>
Click submit when you are ready to load the products!! <br>
</a>
<br>
<form action="index.jsp" method="GET">
API Key: <input type="text" name="api_key">
<br>
API Secret: <input type="text" name="api_secret" />
<br>
Choose CSV File: <input type="file" name="csv_file" />
<br>
<input type="submit" value="Submit To Content API" />
</form>
<br>
This is feedback from the program<br>
**strong text**
You entered<BR>
Name: <%= ContentLoader.getApi_key() %><BR>
Email: <%= ContentLoader.getApi_secret() %><BR>
Age: <%= ContentLoader.getCsv_file() %><BR>
</body>
</html>
When I hit the submit button, I want to pass the 3 strings to the Java application.
(key, secret, and the contents of my csv)
Right now I get "The requested resource is not available" error (HTTP Status 404)
Here is my ContentLoader.java
package com.content;
public class ContentLoader {
private String api_key = "testKey2";
private String api_secret= "testSecret";
private String csv_file = "testFileString";
public ContentLoader() {
// TODO Auto-generated constructor stub
}
public void setApi_key(String api_key) {
this.api_key = api_key;
}
public void setApi_secret(String api_secret) {
this.api_secret = api_secret;
}
public void setCsv_file(String csv_file) {
this.csv_file = csv_file;
}
public String getApi_key() {
return api_key;
}
public String getApi_secret() {
return api_secret;
}
public String getCsv_file() {
return csv_file;
}
}
The ContentLoader.java above is supposed to send and receive strings from the JSP form. When the submit button is hit, I need the 3 strings to pass to Application.java, and the main argument needs to be executed. Right now this is not happening, and I don't understand why. Thanks!!!!
This is my Application.java
import java.io.IOException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class Application implements ServletContextListener{
#Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("Tomcat just started");
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("Tomcat just stopped");
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("hi!! Your program is executing");
/**
//Null Credentials
String apiKey = "000";
String apiSecret = "000";
}
}
Web applications doesn't work like that, and Servlet don't need a main method to work, actually it doesn't know how to use it, instead of that you can use http request from your java application (main methode) to call a jsp file that returns 3 paramteres (in xml format or json) and you can pick those parametres and use them in your application as you want.

AJAX call to Jersey WebService doesn't work

I'm trying out AJAX for the first time. I'm using a Jersey Web Service as what gets called. But my call always executes the error part. Help! please
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Jquery Basic</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#submit1").click(function() {
alert("click");
var username = $("#textbox").val;
$("#para1").text(username);
$.ajax({
type: 'POST',
url: '/FirstProject/src/Resource/resource/welcome',
data: username,
success: function(){alert("Login Success!")},
error: function(){alert("Login Failure!")}
});
alert("ajax passed");
});
});
</script>
</head>
<body>
<a id="body1">JQuery Test Page</a><br>
<div id="heading"><a>Enter Your Details</a></div>
<div>
<div id="heading1"><a>UserName:</a></div>
<div><input id="textbox" type="text"/></div>
<button id="submit1">Submit</button>
</div>
<div><p id="para1"></p></div>
</body>
</html>
WebService is as follows
package Resource;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import POJO.passwordPojo;
import POJO.usernamePojo;
public class resource {
#POST
#Path("welcome")
public String welcomeFunction(#FormParam("username") String username)
{
setUserNameData(username);
return "success";
}
usernamePojo userName = new usernamePojo();
passwordPojo password = new passwordPojo();
public void setUserNameData(String userNameData)
{
userName.setUserName(userNameData.toString());
printuserName();
}
public void setpasswordData(String passwordData)
{
password.setPassword(passwordData.toString());
printPassword();
}
public void printuserName()
{
System.out.println("UserName:"+userName.getUserName());
}
public void printPassword()
{
System.out.println("Password"+password.getPassword());
}
}
Blast!! I know most of my question is code!! Bloody post it already!
Think data needs to be an array.
var usernameVal = $("#textbox").val;
$.ajax({
type: 'POST',
url: '/FirstProject/src/Resource/resource/welcome',
data: { username : usernameVal }
send data as json with index like {"username":username } in ajax data like
....,data: {"username":username },....

PrintWriter output to jsp page inside body tag

This is the code to print to my jsp page. However I have other code in the page. When I call this function I want it to print the message right after where it is called. I can't check for sure because I am using xhtml negotiation, but I suspect it prints after the /html tag.
This is my function
public Print(HttpServletRequest request,HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>haha</p>");
}catch(IOException e){
e.printStackTrace();
}
}
};
This is where I call it
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
<%# page import="com.otrocol.app.*" %>
<%
Print(request, response);
%>
</body>
</html>
This is what I think the result is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
</body>
</html>
"haha"
This is what I want the response to be:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
"haha"
</body>
</html>
This is the error I get:
The JSP uses its own PrintWriter, the JspWriter out. So pass this to the (static) function.
Otherwise you are taking a second writer, and with buffering everything goes haywire.
Also as output already did happen do not set the content type in the function.
At the top of the JSP is a nice location, also for the imports.
<%#page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
When having one writer the function would print at the correct spot in the body.
Nice intuition about the cause. BTW begin a function name with a small letter.
It's not a direct answer to your question but I believe what you're doing will cause you nothing but pain even if you get it to work. You're not using the right tool for the job; creating custom JSP tags is a better option for writing to JSP from Java code.
Code example:
register.jsp
<%# taglib prefix="custom" uri="/WEB-INF/custom-tags.tld" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
<p>
<c:out value="${custom:printHaha()}" />
</p>
</body>
</html>
custom-tags.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0"
xmlns="http://java.sun.com/xml/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
<tlibversion>1.0</tlibversion>
<jspversion>2.0</jspversion>
<shortname>custom-taglib</shortname>
<uri>CustomTags</uri>
<function>
<name>printHaha</name>
<function-class>com.yourpackage.Tags</function-class>
<function-signature>
java.lang.String print()
</function-signature>
</function>
(...)
Tags.class
public class Tags {
public static String print() {
return "haha";
}
}
More info on Tags: official docs
I din't check your code ... you can't do a out.print again using get writer in a jsp page ... because the response for this request is already committed by rendering the jsp
now to print something on asp you can do this any number of ways
print by expression tag
use out (which is an object the server creates)
out.print("Blah...");
and more
to understand what happens to a jsp look into /work/catalina/blah.../
There are two pages. The first one is the Main Page. This one performs some
pseudo calcs.
Based on those calcs, either Success.jsp or Failure.jsp is returned.
This code will do what you wanted to have achieved.....
Even though as the others pointed out, there are more advanced techniques as of
late, still in order to dance, first you have to know the moves....
Primarily look at this
cObj.Print(request, response); in the 2nd jsp page.
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<%# page import="rustler.Beans.Beany" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP and JavaBean</title>
<%-- create an instance of Customer class --%>
<jsp:useBean id="cObj" scope="request" class="rustler.Beans.Beany">
<%-- Set the value of attribute such as CustID --%>
<jsp:setProperty name="cObj" property="*" />
</jsp:useBean>
</head>
<body>
<%
int x=cObj.setStoreCust();
if(x>=1)
{
%>
<jsp:forward page="Success.jsp" />
<%
}
else
{
%>
<jsp:forward page="Failure.jsp" />
<%
}
%>
</body>
</html>
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<%# page import="rustler.Beans.Beany" %>
<%# page import="javax.servlet.http.HttpServletRequest" %>
<%# page import="javax.servlet.http.HttpServletResponse" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Failure!</title>
<%-- create an instance of Customer class --%>
<jsp:useBean id="cObj" scope="request" class="rustler.Beans.Beany">
<%-- Set the value of attribute such as CustID --%>
<jsp:setProperty name="cObj" property="*" />
</jsp:useBean>
</head>
<body>
<%cObj.Print(request, response);%>
</body>
</html>
Java Bean
package rustler.Beans;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Beany implements Serializable
{
public Beany()
{
}
/**
*
*/
private static final long serialVersionUID = 1L;
private String custID;
private String custName;
private int qty;
private float price;
private float total;
private int storeCust;
public String getCustID() {
return custID;
}
public void setJunk(String sStr)
{
//System.out.println("What a punk!");
custName = sStr;//"What a punk!";
}
public void Print(HttpServletRequest request,HttpServletResponse response)
{
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>haha</p>");
}catch(IOException e){
e.printStackTrace();
}
}
public String prntJunk()
{
//System.out.println("What a punk!");
return custName;//"What a punk!";
}
public void setCustID(String custID) {
this.custID = custID;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public float getTotal() {
return total;
}
public void setTotal(float total) {
this.total = total;
}
public int setStoreCust()
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/usermaster","admin","password");
PreparedStatement pstmt=null;
String query=null;
query="insert into customer values(?,?,?,?,?)";
pstmt=con.prepareStatement(query);
pstmt.setString(1,custID);
pstmt.setString(2,custName);
pstmt.setInt(3,qty);
pstmt.setFloat(4,price);
pstmt.setFloat(5,total);
int i=pstmt.executeUpdate();
this.storeCust=i;
}
catch(Exception e)
{
}
return storeCust;
}
}

Categories