i just learned MVC design pattern using java, i have some problem with my MVC, the problem is why the data cannot inserted into database,,
package model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class Pembayaran {
private int bayar,kembalian,total;
private String terbilangBayar,terbilangTotal;
Koneksi koneksi= new Koneksi();
String pesan;
public String getPesan(){
return pesan;
}
public void setPesan(String pesan){
this.pesan=pesan;
}
public int getBayar() {
return bayar;
}
public void setBayar(int bayar) {
this.bayar = bayar;
}
public int getKembalian() {
return kembalian;
}
public void setKembalian(int kembalian) {
this.kembalian = kembalian;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public String getTerbilangBayar() {
return terbilangBayar;
}
public void setTerbilangBayar(String terbilangBayar) {
this.terbilangBayar = terbilangBayar;
}
public String getTerbilangTotal() {
return terbilangTotal;
}
public void setTerbilangTotal(String terbilangTotal) {
this.terbilangTotal = terbilangTotal;
}
public boolean simpan(){
boolean adaKesalahan=false;
Connection connection;
boolean simpan;
PreparedStatement pst;
if((connection=koneksi.getConnection())!=null){
String query="insert into pembayaran(bayar,total,kembalian) values(?,?,?)";
try {
int jumlahSimpan;
simpan=true;
pst=connection.prepareStatement(query);
pst.setInt(1, bayar);
pst.setInt(2, total);
pst.setInt(3, kembalian);
jumlahSimpan=pst.executeUpdate();
pst.close();
connection.close();
if(simpan==true){
if(jumlahSimpan<1){
JOptionPane.showMessageDialog(null,"model error");
}
}
} catch (SQLException ex) {
Logger.getLogger(Pembayaran.class.getName()).log(Level.SEVERE, null, ex);
pesan="error : model";
}
}
return !adaKesalahan;
}
}
this is the controller
package controller;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import model.Pembayaran;
import view.FormPembayaran;
import view.MainForm;
public class PembayaranController {
Pembayaran pembayaran=new Pembayaran();
FormPembayaran formPembayaran;
String pesan;
public String getPesan(){
return pesan;
}
public void setPesan(String pesan){
this.pesan=pesan;
}
public void simpan(JTextField bayar,JTextField kembalian,JTextField total){
if(!bayar.getText().equals("")){
pembayaran.setBayar(Integer.parseInt(bayar.getText()));
pembayaran.setTotal(Integer.parseInt(total.getText()));
pembayaran.setKembalian(Integer.parseInt(kembalian.getText()));
if(pembayaran.simpan()){
MainForm.formPembayaran.setTotal(0);
MainForm.formPembayaran.setTerbilangTotal("");
MainForm.formPembayaran.setTerbilangBayar("");
MainForm.formPembayaran.setKembalian(0);
MainForm.formPembayaran.setBayar(0);
JOptionPane.showMessageDialog(null,"sukses");
}
else{
pesan="error : controller";
}
}
else{
JOptionPane.showMessageDialog(null,"error dari kontroller : bayar tidak boleh kosong");
}
}
}
this is view package
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
pembayaranController.simpan(bayarTextField, kembalianTextField, totalTextField);
}
public void setBayar(int bayar){
this.bayarTextField.setText(Integer.toString(bayar));
}
public int getBayar(){
return Integer.parseInt(this.bayarTextField.getText());
}
public void setKembalian(int kembalian){
this.kembalianTextField.setText(Integer.toString(kembalian));
}
public int getKembalian(){
return Integer.parseInt(this.kembalianTextField.getText());
}
public void setTerbilangBayar(String terbilangBayar){
this.terbilangBayarTextField.setText(terbilangBayar);
}
public String getTerbilangBayar(){
return this.terbilangBayarTextField.getText();
}
public void setTerbilangTotal(String terbilangTotal){
this.terbilangTotalTextField.setText(terbilangTotal);
}
public String getTerbilangTotal(){
return this.terbilangTotalTextField.getText();
}
public void setTotal(int total){
this.totalTextField.setText(Integer.toString(total));
}
public int getTotal(){
return Integer.parseInt(this.totalTextField.getText());
}
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
this is database connection class
public class Koneksi {
private static final String driver = "com.mysql.jdbc.Driver";
private static final String database = "jdbc:mysql://localhost:3306/JualPulsa";
private static final String user = "andi";
private static final String password = "belajar";
private Connection connection;
private String pesanKesalahan;
public String getPesanKesalahan() {
return pesanKesalahan;
}
public Connection getConnection(){
connection = null;
pesanKesalahan = "";
try{
Class.forName(driver);
} catch (ClassNotFoundException ex){
pesanKesalahan = "JDBC Driver tidak ditemukan atau rusak\n"+ex;
}
if (pesanKesalahan.equals("")){
try {
connection = DriverManager.getConnection(database+"?user="+user+"&password="+password+"");
} catch (SQLException ex) {
pesanKesalahan = "Koneksi ke "+database+" gagal\n"+ex;
}
}
return connection;
}
}
i have no error code to debug,, thats why im so strugling here , i hope i can solve this problem with your help...
thanks b4..
Related
I am trying to display an arraylist in a JSP. I can query and display some of the elements in my model object, PoststackModel, but some of arraylist elements throw an error. In particular, I cannot display 'uniquedataid'. I do not understand why. Hope someone can help.
In my JSP, I can loop through some of the elements. This works:
<c:forEach var="input" items="${listInput}" >
${input.dataname},
${input.dataid},
${input.surveyname},
${input.surveyid},
${input.projectname},
${input.projectid},
${input.comments}<br>
</c:forEach>
But when I add 'uniquedataid', as such:
<c:forEach var="input" items="${listInput}" >
${input.uniquedataid},
${input.dataname},
${input.dataid},
${input.surveyname},
${input.surveyid},
${input.projectname},
${input.projectid},
${input.comments}<br>
</c:forEach>
I get the following error:
org.apache.jasper.JasperException: An exception occurred processing [/JSP/Viewers/Viewer_2D_Tabs_8.jsp] at line [114]
111: -->
112:
113: <c:forEach var="input" items="${listInput}" >
114: ${input.uniquedataid},
115: ${input.dataname},
116: ${input.dataid},
117: ${input.surveyname},
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:617)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:514)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
com.luminajio.viewers.Call_2DView.doGet(Call_2DView.java:47)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
javax.el.PropertyNotFoundException: Property [uniquedataid] not found on type [com.luminajio.input.poststack.PoststackModel]
javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:260)
javax.el.BeanELResolver$BeanProperties.access$300(BeanELResolver.java:212)
javax.el.BeanELResolver.property(BeanELResolver.java:333)
javax.el.BeanELResolver.getValue(BeanELResolver.java:92)
org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:113)
org.apache.el.parser.AstValue.getValue(AstValue.java:169)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:190)
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:944)
org.apache.jsp.JSP.Viewers.Viewer_005f2D_005fTabs_005f8_jsp._jspx_meth_c_005fforEach_005f0(Viewer_005f2D_005fTabs_005f8_jsp.java:618)
org.apache.jsp.JSP.Viewers.Viewer_005f2D_005fTabs_005f8_jsp._jspService(Viewer_005f2D_005fTabs_005f8_jsp.java:288)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
com.luminajio.viewers.Call_2DView.doGet(Call_2DView.java:47)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
My Data Model:
package com.luminajio.input.poststack;
public class PoststackModel {
private String uniquedataid;
private String uniquejobid;
private int dataid;
private String dataname;
private int projectid;
private String projectname;
private int surveyid;
private String surveyname;
private String dataformat;
private String comments;
public PoststackModel(String uniquedataid, String uniquejobid, int dataid, String dataname, int projectid,
String projectname, int surveyid, String surveyname, String dataformat, String comments) {
super();
this.uniquedataid = uniquedataid;
this.uniquejobid = uniquejobid;
this.dataid = dataid;
this.dataname = dataname;
this.projectid = projectid;
this.projectname = projectname;
this.surveyid = surveyid;
this.surveyname = surveyname;
this.dataformat = dataformat;
this.comments = comments;
}
public String getuniquedataId() {
return uniquedataid;
}
public void setuniquedataId(String uniquedataid) {
this.uniquedataid = uniquedataid;
}
public String getUniquejobId() {
return uniquejobid;
}
public void setuniquejobId(String uniquejobid) {
this.uniquejobid = uniquejobid;
}
public int getDataid() {
return dataid;
}
public void setDataid(int dataid) {
this.dataid = dataid;
}
public String getDataname() {
return dataname;
}
public void setDataname(String dataname) {
this.dataname = dataname;
}
public int getProjectid() {
return projectid;
}
public void setProjectid(int projectid) {
this.projectid = projectid;
}
public String getProjectname() {
return projectname;
}
public void setProjectname(String projectname) {
this.projectname = projectname;
}
public int getSurveyid() {
return surveyid;
}
public void setSurveyid(int surveyid) {
this.surveyid = surveyid;
}
public String getSurveyname() {
return surveyname;
}
public void setSurveyname(String surveyname) {
this.surveyname = surveyname;
}
public String getdataFormat() {
return dataformat;
}
public void setdataFormat(String dataformat) {
this.dataformat = dataformat;
}
public String getcomments() {
return comments;
}
public void setcomments(String comments) {
this.comments = comments;
}
}
My Data Access Object is:
package com.luminajio.input.poststack;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.luminajio.jdbc.JDBC;
public class PoststackDao {
//String schema = "petrolex";
String schema = "data";
String databaseURL = JDBC.JDBCURL + schema + "?allowPublicKeyRetrieval=true&useSSL=false" ;
String DBlogin= "root";
String DBpass= "lumi123";
public List<PoststackModel> list(String Survey) throws SQLException {
List<PoststackModel> listInput = new ArrayList<>();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try (Connection connection = DriverManager.getConnection(databaseURL, DBlogin, DBpass)) {
//String sql = "SELECT * FROM data ORDER BY DataName";
String sql = "SELECT * FROM data where surveyname = '" + Survey + "' ORDER BY DataName";
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(sql);
while (result.next()) {
String uniquedataid = result.getString("uniquedataid");
String uniquejobid = result.getString("uniquejobid");
int dataid = result.getInt("dataid");
String dataname = result.getString("dataname");
int projectid = result.getInt("projectid");
String projectname = result.getString("projectname");
int surveyid = result.getInt("surveyid");
String surveyname = result.getString("surveyname");
String dataformat = result.getString("dataformat");
String comments = result.getString("comments");
PoststackModel input = new PoststackModel(uniquedataid, uniquejobid, dataid, dataname, projectid, projectname, surveyid, surveyname, dataformat, comments);
listInput.add(input);
}
} catch (SQLException ex) {
ex.printStackTrace();
throw ex;
}
return listInput;
}
}
The servlet that calls the JSP is:
package com.luminajio.viewers;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.RequestDispatcher;
//import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.luminajio.input.poststack.PoststackDao;
import com.luminajio.input.poststack.PoststackModel;
import com.luminajio.jdbc.ConnectionFactory;
import com.luminajio.modules.Metadata;
import com.luminajio.modules.Notes;
import com.luminajio.modules.ParamOpts;
import com.luminajio.modules.Parameters;
import com.luminajio.modules.Rules;
public class Call_2DView extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String User = request.getParameter("User");
String Theme = request.getParameter("Theme");
String Survey = request.getParameter("Survey");
PoststackDao dao = new PoststackDao();
// Pass just the theme name 'darkness' rather than 'jquery-ui-darkness.css' (ThemeSubmit)
String ThemeSubmit = Theme.replace("jquery-ui-", "");
ThemeSubmit = ThemeSubmit.replace(".css", "");
try {
List<PoststackModel> listInput = dao.list(Survey);
request.setAttribute("listInput", listInput);
request.setAttribute("User",User);
request.setAttribute("Theme",Theme);
request.setAttribute("ThemeSubmit",ThemeSubmit);
request.setAttribute("Survey", Survey);
request.getRequestDispatcher("/JSP/Viewers/Viewer_2D_Tabs_8.jsp").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
throw new ServletException(e);
}
}
}
Any idea why I get an error when trying to display 'uniquedataid' in my JSP?
Why would this code be having memory issues? It runs fine once, and then when I try to run it again it hangs on "Enabling plugin". It'll then give me an OutOfMemoryException such as
"Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "Worker-Main-10""
The code I am using is as follows from the Spigot API
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Bat;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.UUID;
public class COVID19 extends JavaPlugin {
private static ArrayList<CovidInfection> infections;
#Override
public void onEnable() {
infections = new ArrayList<CovidInfection>();
System.out.println("1");
try {
readInfections();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
System.out.println("2");
this.getCommand("getInfected").setExecutor(new CommandGetInfected());
BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
#Override
public void run() {
batCovid();
}
}, 0, 10);
System.out.println(4);
}
#Override
public void onDisable() {
try {
writeInfections();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void batCovid() {
System.out.println(3);
for(Player player : Bukkit.getOnlinePlayers()) {
for(Entity nearby : player.getNearbyEntities(6, 6, 6)) {
if (nearby instanceof Bat) {
String name = player.getName();
UUID uuid = player.getUniqueId();
infections.add(new CovidInfection(uuid, name, 14));
}
}
}
}
public void readInfections() throws FileNotFoundException {
File file = new File("infected.txt");
if(file.length() == 0) {
return;
}
Scanner input = new Scanner(file);
String line = input.nextLine();
while (!(line.equals(""))) {
infections.add(parseInfectionLine(line));
}
input.close();
}
public void writeInfections() throws IOException {
//File will be written as UUID,Name,DaysRemaining
FileWriter writer = new FileWriter("infected.txt", false);
for(CovidInfection infection : infections) {
writer.write(infection.toString());
}
writer.close();
}
private CovidInfection parseInfectionLine(String line) {
String[] words = line.replace("\n","").split(",");
return new CovidInfection(UUID.fromString(words[0]), words[1], Integer.parseInt(words[2]));
}
public static String getInfected() {
String compiled = "";
for (CovidInfection infection : infections) {
compiled += infection.toString() + "\n";
}
return compiled;
}
}
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandGetInfected implements CommandExecutor {
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
String message = COVID19.getInfected();
if(!(message.equals(""))) {
sender.sendMessage(message);
} else {
sender.sendMessage("There are no infected!");
}
return(true);
}
}
import java.util.UUID;
public class CovidInfection {
private UUID uuid;
private String name;
private int days;
public CovidInfection(UUID uuid, String name, int days) {
this.uuid = uuid;
this.name = name;
this.days = days;
}
public int getDays() {
return days;
}
public String getName() {
return name;
}
public UUID getUuid() {
return uuid;
}
public void newDay() {
days--;
}
public String toString() {
return uuid.toString() + "," + name + "," + days + "\n";
}
}
Any help would be greatly appreciated, thank you!
Firstly, you are make I/O request on main thread.
To fix this issue, use multithreading such as explained here or here
Then, this :
Scanner input = new Scanner(file);
String line = input.nextLine();
Can't be used in a server.
An input like that already exist, it's the console sender.
To do that, I suggest you to use ServerCommandEvent and use spigot's console.
I'm writing a program (Java Application) for reading ePassport. For access I use the library org.jmrtd. What kind of object should I transfer in CardService.getInstance() ?
import net.sf.scuba.smartcards.CardService;
import net.sf.scuba.smartcards.CardServiceException;
import org.jmrtd.BACKeySpec;
import org.jmrtd.PassportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestComponent {
private static final Logger log = LoggerFactory.getLogger(MainApp.class);
public static void main(String args[]) {
try {
CardService cs = CardService.getInstance(???????);
PassportService ps = new PassportService(cs);
ps.open();
ps.sendSelectApplet(false);
ps.sendSelectApplet(false);
BACKeySpec bacKey = new BACKeySpec() {
public String getDocumentNumber() {
return "xxxxxxxx";
}
public String getDateOfBirth() {
return "yyMMdd";
}
public String getDateOfExpiry() {
return "yyMMdd";
}
};
ps.doBAC(bacKey);
ps.close();
} catch (CardServiceException e) {
e.printStackTrace();
}
}
}
Answer found:
add in pom
net.sf.scuba
scuba-sc-j2se
0.0.13
import net.sf.scuba.smartcards.TerminalCardService;
CardTerminal terminal =TerminalFactory.getDefault().terminals().list().get(0);
CardService cs = CardService.getInstance(terminal);
PassportService ps = new PassportService(cs);
ps.open();
I was given code that I have to make do something else. When I go to compile my servlet, it doesn't recognize my bean. I've deleted, recompiled, and tried from all different directories. I have no clue why this isn't working.
import BH.*;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.function.*;
import static java.util.Arrays.asList;
import java.text.DateFormat;
import java.util.concurrent.locks.ReentrantLock;
import java.util.Random;
public class sessionServlet extends HttpServlet {
private List<String[]> the_sessions;
private DateFormat df;
public static ReentrantLock thelock = new ReentrantLock();
public void init() throws ServletException {
the_sessions=new ArrayList<String[]>();
df=DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
}
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
if ((!(req.getParameter("task")==null))&&(req.getParameter("task").trim().equals("deploy"))) {
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<hr /><center><h1>sessionServlet Deployed</h1></center><hr />");
out.println("</body>");
out.println("</html>");
return;
}
Consumer <String> forwardTo =(s) ->ForwardTo(s,req,res);
boolean is_first_visit=true;
String[] this_session=new String[3];
String manager = req.getParameter("manager");
for (String [] a_session :the_sessions) {
if (a_session[0].equals(manager)) { //Found an active session
is_first_visit=false;
this_session=a_session;
break;
}
}
if ((req.getParameter("task")==null)&&(!is_first_visit)) {
the_sessions.remove(this_session);
is_first_visit=true; // just used http://hoare.cs.umsl.edu/servlet/js_test/sessionServlet
}
req.setAttribute("thesessioncount",the_sessions.size());
if (is_first_visit) {
if (the_sessions.size()==10) {
forwardTo.accept("noSessions.jsp"); //No Available Sessions
return;
}
String randomStr = getRandomString();
String[] new_session = {randomStr,df.format(new Date()),"need a name"};
the_sessions.add(new_session);
this_session=new_session;
req.setAttribute("manager",randomStr);
forwardTo.accept("startSession.jsp");
return;
}
String the_name="";
String the_pw="";
if (this_session[2].equals("need a name")) { //No name given yet
the_name=req.getParameter("whoisit");
the_pw=req.getParameter("passwd");
if ((the_name==null)||(the_name.trim().length()==0)||checkPW(the_name,the_pw)) { //checkPW returns false if correct
the_sessions.remove(this_session);
req.setAttribute("thesessioncount",the_sessions.size());
forwardTo.accept("startSession.jsp");
return; // didn't enter a name in startSession
}
}
this_session[2]=the_name.trim();
req.setAttribute("thename", this_session[2]);
if (tooLong(this_session[1],df.format(new Date()))) { //Has the session timed out?
the_sessions.remove(this_session);
forwardTo.accept("Expired.jsp");
return;
} else {
this_session[1]=df.format(new Date()); //reset the last session activity time
NotesBean thesenotes=new NotesBean();
if(req.getParameter("task").trim().equals("9")){
the_sessions.remove(this_session);
forwardTo.accept("exit.jsp");
return;
}
thelock.lock();
if (!req.getParameter("task").trim().equals("0")) { //add ACC here, also show/update posts
thesenotes.setAll(req.getParameter("java_source"),Integer.parseInt(req.getParameter("version")));
if (req.getParameter("task").trim().equals("2")) {
thesenotes.setNotes(req.getParameter("notes"),req.getParameter("java_source"),Integer.parseInt(req.getParameter("version")));
}
}
req.setAttribute("thesessioncount",the_sessions.size());
req.setAttribute("theBean",thesenotes);
req.setAttribute("manager",manager);
//req.setAttribute("theURL", "http://www.umsl.edu/~siegelj/turing.jpg");
forwardTo.accept("getNotes.jsp");
thelock.unlock();
return;
}
}//end doGet
boolean tooLong(String now,String then){
//Check amount of time that passed
return false;
}
boolean checkPW(String name,String password){
AccountBean theAccount = new AccountBean();
theAccount.setAccount(name);
if(theAccount.isPassword(password))
return false;
return true;
}
public void log(String s){
FileWriter fileWriter = null;
try {
String content =s+" at :"+new Date(System.currentTimeMillis()).toString()+"\n";
File theLogFile = new File("C:/Tomcat/webapps/js_test/session.log");
fileWriter = new FileWriter(theLogFile,true);
fileWriter.write(content);
} catch (IOException ex) {
} finally {
try {
fileWriter.close();
} catch (IOException ex) {
}
}
}
void ForwardTo(String s,HttpServletRequest req, HttpServletResponse res)
{
RequestDispatcher rd= req.getRequestDispatcher(s);
try {
rd.forward(req, res);
} catch (IOException|ServletException is) {
log(" req from "+s+" not forwarded at ");
try {
throw is;
} catch (Exception e) {
}
}
}
public void destroy()
{
log("The instance was destroyed");
}
public String getRandomString(){
byte[] randbyte=new byte[10];
Random rand = new Random(System.currentTimeMillis());
for (int idx = 0; idx <10; ++idx) {
int randomInt = rand.nextInt(26); //0<=randomInt<26
//System.out.println(randomInt);
randbyte[idx]=(byte)(randomInt+65);
}
try {
String rs=new String(randbyte, "UTF-8");
//System.out.println(rs);
return rs;
} catch (Exception e) {
//System.out.println("bad string");
return "bad";
}
}
}
AccountBean.java
package mybeans;
import BH.*;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.ArrayList;
import java.util.Arrays;
import static java.util.Arrays.asList;
import java.sql.*;
public class AccountBean implements java.io.Serializable {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/cs4010";
static final String USER = "cs4010";
static final String PASS = "cs4010";
private String account="";
private String password="";
public AccountBean(){
}
public void setAccount(String a)
{
account = a;
}
public String getAccount()
{
return account;
}
public void setPassword(String p)
{
password = p;
}
public String getPassword(){
return password;
}
public void createAccount()
{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
Statement stmt = conn.createStatement();
// System.out.println("here: "+Bytes_Hex.String2HexString(n));
String this_query="INSERT INTO ries_userpass (username, password) VALUES ("+account+","+password+");";
// System.out.println(this_query);
stmt.executeUpdate(this_query);
stmt.close();
conn.close();
} catch (Exception e) {
}
return ;
}
public boolean isPassword(String p) //make this to use
{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
Statement stmt = conn.createStatement();
String this_query=" SELECT * from ries_userpass WHERE username="+account+";";
ResultSet rs = stmt.executeQuery(this_query);
while (rs.next()) {
password=Bytes_Hex.HexString2String(rs.getString("posts"));
if(password.equals(p))
{
rs.close();
stmt.close();
conn.close();
return true;
}
}
rs.close();
stmt.close();
conn.close();
}
catch (Exception e) {
return false;
}
return false;
}
}
add this statement import mybeans.*;, since you are using AccountBean but you are not importing that class package;
import BH.*;
import mybeans.*;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.function.*;
import static java.util.Arrays.asList;
import java.text.DateFormat;
import java.util.concurrent.locks.ReentrantLock;
import java.util.Random;
public class sessionServlet extends HttpServlet {
private List<String[]> the_sessions;
private DateFormat df;
public static ReentrantLock thelock = new ReentrantLock();
public void init() throws ServletException {
the_sessions=new ArrayList<String[]>();
df=DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
}
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
if ((!(req.getParameter("task")==null))&&(req.getParameter("task").trim().equals("deploy"))) {
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<hr /><center><h1>sessionServlet Deployed</h1></center><hr />");
out.println("</body>");
out.println("</html>");
return;
}
Consumer <String> forwardTo =(s) ->ForwardTo(s,req,res);
boolean is_first_visit=true;
String[] this_session=new String[3];
String manager = req.getParameter("manager");
for (String [] a_session :the_sessions) {
if (a_session[0].equals(manager)) { //Found an active session
is_first_visit=false;
this_session=a_session;
break;
}
}
if ((req.getParameter("task")==null)&&(!is_first_visit)) {
the_sessions.remove(this_session);
is_first_visit=true; // just used http://hoare.cs.umsl.edu/servlet/js_test/sessionServlet
}
req.setAttribute("thesessioncount",the_sessions.size());
if (is_first_visit) {
if (the_sessions.size()==10) {
forwardTo.accept("noSessions.jsp"); //No Available Sessions
return;
}
String randomStr = getRandomString();
String[] new_session = {randomStr,df.format(new Date()),"need a name"};
the_sessions.add(new_session);
this_session=new_session;
req.setAttribute("manager",randomStr);
forwardTo.accept("startSession.jsp");
return;
}
String the_name="";
String the_pw="";
if (this_session[2].equals("need a name")) { //No name given yet
the_name=req.getParameter("whoisit");
the_pw=req.getParameter("passwd");
if ((the_name==null)||(the_name.trim().length()==0)||checkPW(the_name,the_pw)) { //checkPW returns false if correct
the_sessions.remove(this_session);
req.setAttribute("thesessioncount",the_sessions.size());
forwardTo.accept("startSession.jsp");
return; // didn't enter a name in startSession
}
}
this_session[2]=the_name.trim();
req.setAttribute("thename", this_session[2]);
if (tooLong(this_session[1],df.format(new Date()))) { //Has the session timed out?
the_sessions.remove(this_session);
forwardTo.accept("Expired.jsp");
return;
} else {
this_session[1]=df.format(new Date()); //reset the last session activity time
NotesBean thesenotes=new NotesBean();
if(req.getParameter("task").trim().equals("9")){
the_sessions.remove(this_session);
forwardTo.accept("exit.jsp");
return;
}
thelock.lock();
if (!req.getParameter("task").trim().equals("0")) { //add ACC here, also show/update posts
thesenotes.setAll(req.getParameter("java_source"),Integer.parseInt(req.getParameter("version")));
if (req.getParameter("task").trim().equals("2")) {
thesenotes.setNotes(req.getParameter("notes"),req.getParameter("java_source"),Integer.parseInt(req.getParameter("version")));
}
}
req.setAttribute("thesessioncount",the_sessions.size());
req.setAttribute("theBean",thesenotes);
req.setAttribute("manager",manager);
//req.setAttribute("theURL", "http://www.umsl.edu/~siegelj/turing.jpg");
forwardTo.accept("getNotes.jsp");
thelock.unlock();
return;
}
}//end doGet
boolean tooLong(String now,String then){
//Check amount of time that passed
return false;
}
boolean checkPW(String name,String password){
AccountBean theAccount = new AccountBean();
theAccount.setAccount(name);
if(theAccount.isPassword(password))
return false;
return true;
}
public void log(String s){
FileWriter fileWriter = null;
try {
String content =s+" at :"+new Date(System.currentTimeMillis()).toString()+"\n";
File theLogFile = new File("C:/Tomcat/webapps/js_test/session.log");
fileWriter = new FileWriter(theLogFile,true);
fileWriter.write(content);
} catch (IOException ex) {
} finally {
try {
fileWriter.close();
} catch (IOException ex) {
}
}
}
void ForwardTo(String s,HttpServletRequest req, HttpServletResponse res)
{
RequestDispatcher rd= req.getRequestDispatcher(s);
try {
rd.forward(req, res);
} catch (IOException|ServletException is) {
log(" req from "+s+" not forwarded at ");
try {
throw is;
} catch (Exception e) {
}
}
}
public void destroy()
{
log("The instance was destroyed");
}
public String getRandomString(){
byte[] randbyte=new byte[10];
Random rand = new Random(System.currentTimeMillis());
for (int idx = 0; idx <10; ++idx) {
int randomInt = rand.nextInt(26); //0<=randomInt<26
//System.out.println(randomInt);
randbyte[idx]=(byte)(randomInt+65);
}
try {
String rs=new String(randbyte, "UTF-8");
//System.out.println(rs);
return rs;
} catch (Exception e) {
//System.out.println("bad string");
return "bad";
}
}
}
I have created a RESTFUL webservice, witch returns a json, but at this time i only consult and show a simple select * , i need to create a complete CRUD solution, if anyone have some samples to share, i'll appreciate.
Best Regards to all
My code until now are:
DAO - Access.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import dto.Usuarios;
public class Access
{
public ArrayList<Usuarios> getUsuarios(Connection con) throws SQLException
{
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM usuarios");
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Usuarios usuariosObj = new Usuarios();
usuariosObj.setUsr_id(rs.getInt("usr_id"));
usuariosObj.setUsr_login(rs.getString("usr_login"));
usuariosObj.setUsr_pwd(rs.getString("usr_pwd"));
usuariosList.add(usuariosObj);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return usuariosList;
}
}
DTO - Usuarios.java
package dto;
public class Usuarios
{
private int usr_id;
private String usr_login;
private String usr_pwd;
public Usuarios()
{
}
public Usuarios(int usr_id, String usr_login, String usr_pwd)
{
super();
this.usr_id = usr_id;
this.usr_login = usr_login;
this.usr_pwd = usr_pwd;
}
public int getUsr_id()
{
return usr_id;
}
public void setUsr_id(int usr_id)
{
this.usr_id = usr_id;
}
public String getUsr_login()
{
return usr_login;
}
public void setUsr_login(String usr_login)
{
this.usr_login = usr_login;
}
public String getUsr_pwd()
{
return usr_pwd;
}
public void setUsr_pwd(String usr_pwd)
{
this.usr_pwd = usr_pwd;
}
#Override
public String toString()
{
return "[ {usr_id=" + usr_id + ", usr_login=" + usr_login + ", usr_pwd=" + usr_pwd + "} ]";
}
}
Model - AccessManager.java
package model;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import dao.Access;
import dao.Database;
import dto.Usuarios;
public class AccessManager
{
public ArrayList<Usuarios> getUsuarios() throws Exception
{
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
Database db = new Database();
Connection con = db.getConnection();
Access access = new Access();
usuariosList = access.getUsuarios(con);
return usuariosList;
}
}
WebService - UsuariosService.java
package webService;
import java.util.ArrayList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import com.google.gson.Gson;
import model.AccessManager;
import dto.Usuarios;
#Path("/UsuariosService")
public class UsuariosService
{
#GET
#Path("/usuarios")
#Produces("application/json")
public String usuarios()
{
String usuarios = null;
ArrayList<Usuarios> usuariosList = new ArrayList<Usuarios>();
try
{
usuariosList = new AccessManager().getUsuarios();
Gson gson = new Gson();
//usuarios = gson.toJson(usuariosList);
usuarios = "{\"usuarios\" :" + gson.toJson(usuariosList) + "}";
} catch (Exception e)
{
e.printStackTrace();
}
return usuarios;
}
}
Usually you should ask a specific trouble you have instead of ask for samples. It looks like you have a structured code and all you need is implement all operations exposing as a service.
In case you need a sample, there quite a lot of resources on the web. Something like this: https://code.google.com/p/javaee6-crud-example/
I'll try give you some quick tips below:
WebService - UsuariosService.java
#POST
#Path("/usuarios")
public Response save(Usuario user) {
try {
manager= new AccessManager();
manager.save(user);
return Response.ok("User has been created.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
#DELETE
#Path("/usuarios/{id}")
public Response delete(#PathParam("id") String id) {
try {
manager= new AccessManager();
manager.delete(id);
return Response.ok("User has been deleted.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
#PUT
#Path("/usuarios/{id}")
public Response delete(#PathParam("id") String id, Usuario user) {
try {
manager= new AccessManager();
manager.update(id, user);
return Response.ok("User has been updated.").build();
} catch (Exception e) {
e.printStackTrace();
}
return usuarios;
}
If you donĀ“t understand the usage of PUT, DELETE, POST and so on, I recommend you to read HTTP Method Tutorial. There is several discussion regarding this but you might skip it for a while.
I think you might get an idea from here. Your DAO needs to implement methods to perform CRUD interface as well. The link I've added has a very simple sample that might help as well. You might also check this JPA link.
Not sure whether info above helped but I think it is a start since you have to code it in order to understand more about it :)