This question already has answers here:
Struts2 passing variables case
(3 answers)
Closed 1 year ago.
i recently try to learn java and struts.
i want to pass the selected value from my dropdown but all i receive in my action is null
here's my code
dropdown in my jsp
<s:select list="UrgencyList" listKey="name" listValue="name"
key="urgency" name="urgency" emptyOption="false" headerKey="12" required="true"
headerValue="--------------------------------------------------------" />
<font class="ui-widget-R"><s:property value="errors['urgency'][0]" /></font>
my xml, SavSharing is the post action used ob my button
<action name="SavSharing" class="com.ao.qshare.form.Sharing" method="Save">
<exception-mapping exception="org.apache.commons.fileupload.FileSizeLimitExceededException"
result="error" />
<result name="success">/qs/sharing.jsp</result>
<result name="input">/qs/sharing.jsp</result>
<interceptor-ref name="basicStack"/>
<interceptor-ref name="mydefault" />
</action>
public class Sharing extends ActionSupport {
public String Save() throws Exception {
String result = "";
SharingSqlManger sql = null;
SiteDeploySqlManger sSql=null;
try {
Log.info(getClass(), "-----Save start-----");
con = DbConnection.getDbConnection();// get account
con.setAutoCommit(false);
sql=new SharingSqlManger(con);
sSql= new SiteDeploySqlManger(con);
ActionContext actionContext = ActionContext.getContext();
Map<?,?> data=actionContext.getParameters();
String tp=SharingUtil.getString(data.get("tp"));
attachs=SharingUtil.getFile(this.sno,SharingConstants.sharing);
boolean isSameFile=SharingUtil.isSameFile(SharingUtil.getFileString(attachs),this.getUploadFileName());
// boolean isSameFile=SharingUtil.isSameFile(this.attach,this.getUploadFileName());
//save
this.setPara();
String oldStatus=entity.getStatus();
if (isSameFile){
this.addActionMessage(SharingConstants.messFileExists);
mess.add(SharingConstants.messFileExists);
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}else{
//upload!=null,do upload
if (!GenericValidator.isBlankOrNull(this.getUploadFileName())) {
this.setAttach(this.attach+this.getUploadFileName()+";");
entity.setAttach(this.attach);
}
if (tp.equals("File")){
if (this.lengthValidate() && this.isSaveValidate(sql)){
if (status.equals(SharingConstants.deployStatusKey)) {
SharingEntity shEntity = sql.getSharing(sno, "</p>");
entity.setAlertSite(shEntity.getAlertSite());
entity.setAlertDept(shEntity.getAlertDept());
entity.setDeployDept(shEntity.getDeployDept());
entity.setDeploySite(shEntity.getDeploySite());
entity.setDSite(shEntity.getDSite());
entity.setDDept(shEntity.getDDept());
//Start CR-2014-01727 Kevin
entity.setAlertCopy(shEntity.getAlertCopy());
entity.setDeployCopy(shEntity.getDeployCopy());
//End CR-2014-01727 Kevin
}
//save
sno = sql.save(entity,SharingConstants.saveDocument,SharingConstants.sharing,oldStatus);
this.setSno(sno);
entity=sql.getSharing(sno,"</p>");
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
if (upload != null)
SharingUtil.getFile(upload, this.getUploadFileName(), sno,
SharingConstants.sharing);
init(sql);
con.commit();
Log.info(getClass(), "-----Save end-----");
isValidate=true;
result = SUCCESS;
}else{
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}
}else{
if (this.status.equals(SharingConstants.newStatusKey)){
this.setStatus(SharingConstants.drafStatusKey);
if (this.lengthValidate() && this.isSaveValidate(sql)){
entity.setStatus(SharingConstants.drafStatusKey);
//save
sno = sql.save(entity,SharingConstants.saveDocument,SharingConstants.sharing,oldStatus);
Log.info(getClass(), sno + " status:"+this.getStatusName());
Log.info(getClass(), sno + " save finished");
this.setSno(sno);
entity=sql.getSharing(sno,"</p>");
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
con.commit();
if (upload != null)
SharingUtil.getFile(upload, this.getUploadFileName(), sno,
SharingConstants.sharing);
Log.info(getClass(), "-----Save end-----");
isValidate=true;
result = SUCCESS;
}else{
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}
}else{
if (status.equals(SharingConstants.deployStatusKey)){//deploy
if (this.lengthValidate() && isValidate(SharingConstants.Deployed,sql)) {
SharingEntity shEntity=sql.getSharing(sno,"</p>");
entity.setAlertSite(shEntity.getAlertSite());
entity.setAlertDept(shEntity.getAlertDept());
entity.setDeployDept(shEntity.getDeployDept());
entity.setDeploySite(shEntity.getDeploySite());
entity.setDSite(shEntity.getDSite());
entity.setDDept(shEntity.getDDept());
//Start CR-2014-01727 Kevin
entity.setAlertCopy(shEntity.getAlertCopy());
entity.setDeployCopy(shEntity.getDeployCopy());
//End CR-2014-01727 Kevin
sno=sql.save(entity,SharingConstants.saveDocument,SharingConstants.sharing,oldStatus);
this.setSno(sno);
entity=sql.getSharing(sno,"</p>");
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
con.commit();
if (upload != null)
SharingUtil.getFile(upload, this.getUploadFileName(), sno,
SharingConstants.sharing);
Log.info(getClass(), "-----Save end-----");
isValidate=true;
result = SUCCESS;
}else{
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}
}else{
if (this.lengthValidate() && isSaveValidate(sql)) {
sno=sql.save(entity,SharingConstants.saveDocument,SharingConstants.sharing,oldStatus);
this.setSno(sno);
entity=sql.getSharing(sno,"</p>");
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
con.commit();
if (upload != null)
SharingUtil.getFile(upload, this.getUploadFileName(), sno,SharingConstants.sharing);
Log.info(getClass(), "-----Save end-----");
isValidate=true;
result = SUCCESS;
}else{
this.setEntityDesc(sql,sSql);
this.setEntity(entity);
init(sql);
isValidate=false;
result = INPUT;
}
}
}
}
}
if (!tp.equals("Exit")){
isValidate=false;
}
} catch (SizeLimitExceededException e) {
Log.info(this.getClass(), "SizeLimitExceededException:" + e.getMessage());
mess.add("SizeLimitExceededException:"+e.getMessage());
this.setStatusName(SharingConstants.New);
result=INPUT;
if (con!=null) con.close();
} catch (IOException e) {
Log.info(this.getClass(), "IOException:" + e.getMessage());
mess.add("IOException:"+e.getMessage());
this.setStatusName(SharingConstants.New);
result=INPUT;
if (con!=null) con.close();
} catch (FileUploadException e) {
Log.info(this.getClass(), "FileUploadException:" + e.getMessage());
// this.addActionError("Exception:"+e.getMessage());
mess.add("FileUploadException:"+e.getMessage());
this.setStatusName(SharingConstants.New);
result=INPUT;
if (con!=null) con.close();
} catch (Exception e) {
Log.info(this.getClass(), "Save exception:" + e.getMessage());
mess.add("Exception:"+e.getMessage());
this.setStatusName(SharingConstants.New);
result=INPUT;
// this.addActionError("Exception:"+e.getMessage());
if (con!=null) con.close();
}finally{
// this.setEntityDesc(sql,sSql);
// this.setEntity(entity);
//
// init(sql);
// isValidate=false;
if (con!=null) con.close();
}
return result;
}
private String urgency="";
public String geturgency() {
return urgency;
}
public void seturgency(String urgency) {
this.urgency = urgency;
}
}
I think i supposed to get the value from the jsp going to my action but not doing what im expecting.
Note: there's other textfield and dropdown i remove on the code above all of that is working except to the urgency dropdown that i added.
Also no exception or error found on the console on debugging mode
Your urgency setter names are incorrect; they should follow the JavaBean naming convention and be setUrgency/getUrgency.
Unrelated:
The action method should be named save to follow Java naming convention.
All parameters should be retrieved via setters (or ModelDriven), there is no need to access the action context here.
Most of your exception handling could be handled with a single multi-catch.
This action does far, far too much in a single method: refactor.
In general, setters should just set. If a setter is doing much more than setting it should have a more-obvious name.
There's more, but that's enough for now :)
Related
I'm very new in spring development because I'm not a back developer.
I create a back to manage sports training.
I has several times a TransactionSystemException like
Exceptionorg.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
I don't understand what it mean.
I have a class Person who contains a Coordinates object on #OneToOne relation.
Each class have a Service class that has a method of adding.
In PersonService's add method, I call the Coordinates add method which save and return saved object.
This is the add method of PersonClass
public ResponseService<ObjectCreatedModel<UUID, PersonneMorale>> add(PersonneMorale personneMorale) {
String messageErreur = TAG + " - add - ";
StatusReturn status = StatusReturn.ERROR;
String message = null;
ObjectCreatedModel<UUID, PersonneMorale> objectCreatedModel = null;
if (personneMorale != null) {
if (personneMorale.getId() == null) {
personneMorale.setId(UUID.randomUUID());
try {
// Gestion des coordonnees
ResponseService<ObjectCreatedModel<UUID, Coordonnees>> responseServiceCoordonnees =
coordonneesService.add(personneMorale.getCoordonnees());
if (responseServiceCoordonnees.isSuccess() || responseServiceCoordonnees.exist()) {
ResponseService<Coordonnees> responseServiceCoordonneesGet = coordonneesService
.getOne(responseServiceCoordonnees.getObjectReturn().getId());
Coordonnees coordonnees = responseServiceCoordonneesGet.getObjectReturn();
personneMorale.setCoordonnees(coordonnees);
personneMorale = personneMoraleRepository.save(personneMorale);
if (personneMorale != null) {
status = StatusReturn.SUCCESS;
objectCreatedModel = new ObjectCreatedModel<>(personneMorale.getId(), null);
} else {
message = messageErreur + StringResource.E_OCCURRED;
}
} else {
status = responseServiceCoordonnees.getStatusReturn();
message = responseServiceCoordonnees.getMessage();
}
} catch (ConstraintViolationException violationException) {
status = StatusReturn.EXCEPTION;
message = messageErreur + ConstraintViolationReader.extractException(violationException);
} catch (Exception ex) {
status = StatusReturn.EXCEPTION;
message = messageErreur + ex.toString();
}
} else {
message = messageErreur + StringResource.E_MUST_NULL;
}
} else {
message = messageErreur + StringResource.E_SET_PARAMETER;
}
return new ResponseService<>(status, message, objectCreatedModel);
}
This is the add method of CoordinatesService
public ResponseService<ObjectCreatedModel<UUID, Coordonnees>> add(Coordonnees coordonnees) {
StatusReturn status = StatusReturn.ERROR;
String message = "";
ObjectCreatedModel<UUID, Coordonnees> objectCreatedModel = null;
if (coordonnees != null) {
if (coordonnees.getIdCoordonnees() == null) {
try {
coordonnees.setIdCoordonnees(UUID.randomUUID());
Coordonnees coordonneesBase = coordonneesRepository.save(coordonnees);
if (coordonneesBase != null) {
status = StatusReturn.SUCCESS;
objectCreatedModel = new ObjectCreatedModel<>(coordonneesBase.getIdCoordonnees(), null);
} else {
message = StringResource.E_ERROR_OCCURRED;
}
} catch (ConstraintViolationException violationException) {
status = StatusReturn.EXCEPTION;
message = "Exception" + ConstraintViolationReader.extractException(violationException);
} catch (Exception ex) {
status = StatusReturn.EXCEPTION;
message = "Exception" + ex.toString();
}
} else {
message = "Coordonnées" + ErrorsString.ERROR_COMMON_ID_MUST_BE_EMPTY;
}
} else {
message = ErrorsString.ERROR_COORDINATES_MANDATORY;
}
return new ResponseService<>(status, message, objectCreatedModel);
}
The error occurs when CoordinatesService try to save coordinates and pass to the catch (Exception e)
Could you help me to understand what Transaction error mean with an example like my code please ?
I am trying to use the user's selection of a JRadioButton as part of a SELECT query for a derby database. For some reason, when I click the search button (called diffSearchbtn), nothing happens. What should be happening is that the SELECT query puts all the entries that match the criteria of the radio button into a JTable on a panel called dispPanel.
Here is the code for the method that assigns a string based on what button the user clicks.
private String tagValid()
{
String diff = "";
if (dEasybtn.isSelected())
{
diff = "EASY";
System.out.println("easy");
}
else if (dMedbtn.isSelected())
{
diff = "MEDIUM";
System.out.println("medium");
}
else if (dHardbtn.isSelected())
{
diff = "HARD";
System.out.println("hard");
}
else
{
diff = null;
}
return null;
}
Here is the code that is meant to display the form:
private void diffSearchbtnActionPerformed(java.awt.event.ActionEvent evt) {
if(tagValid()!=null)
{
String q = String.format("Select* from Gabby.PData where DIFFICULTY = '%d'", tagValid());
ResultSet res = Backend.query(q);
guiTable.setModel(DbUtils.resultSetToTableModel(res));
int counter = 3;
try
{
while (res.next()) {
counter++;
System.out.println("increasing counter");
}
}
catch (SQLException ex) {
Logger.getLogger(WikiPlantGUI.class.getName()).log(Level.SEVERE, null, ex);
}
if (counter == 0)
{
basePanel.removeAll();
basePanel.add(NoMatchPanel);
basePanel.repaint();
basePanel.revalidate();
}
else
{
basePanel.removeAll();
basePanel.add(dispPanel);
basePanel.repaint();
basePanel.revalidate();
}
}
}
Here is the code from the class Backend:
public static ResultSet query(String q)
{
try {
System.out.println("a query");
Statement stat = myConObj.createStatement();
ResultSet res = stat.executeQuery(q);
return res;
}
catch (SQLException e)
{
e.printStackTrace(); // tells what the error is
return null; // returns nothing
}
}
GUI screenshot
There are no error messages, and the program otherwise runs perfectly. Any idea on what's going wrong?
I'm facing the problem about insert user in database. Im using Restful and JDBC to parse data to android, I have two classes to perform insert user following as:
Register.java
#Path("/register")
public class Register {
#GET
#Path("/doregister")
#Produces(MediaType.APPLICATION_JSON)
public String doLogin(#QueryParam("name") String name, #QueryParam("username") String uname, #QueryParam("password") String pwd){
String response = "";
int retCode = registerUser(name, uname, pwd);
if(retCode == 0){
response = Utitlity.constructJSON("register",true);
}else if(retCode == 1){
response = Utitlity.constructJSON("register",false, "You are already registered");
}else if(retCode == 2){
response = Utitlity.constructJSON("register",false, "Special Characters are not allowed in Username and Password");
}else if(retCode == 3){
response = Utitlity.constructJSON("register",false, "Error occured");
}
return response;
}
private int registerUser(String name, String uname, String pwd){
System.out.println("Inside check registerUser method() ");
int result = 3;
if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){
try {
if(DBConnection.insertUser(name, uname, pwd)){
System.out.println("RegisterUSer if");
result = 0;
}
} catch(SQLException sqle){
System.out.println("RegisterUSer catch sqle");
//When Primary key violation occurs that means user is already registered
if(sqle.getErrorCode() == 1062){
result = 1;
}
else if(sqle.getErrorCode() == 1064){
System.out.println(sqle.getErrorCode());
result = 2;
}
}
catch (Exception e) {
System.out.println("Inside checkCredentials catch e ");
result = 3;
}
}else{
System.out.println("Inside checkCredentials else");
result = 3;
}
return result;
}
}
DBConnect.java
public static boolean insertUser(String name, String uname, String pwd) throws SQLException, Exception {
boolean insertStatus = false;
Connection dbConn = null;
try {
try {
dbConn = DBConnection.createConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement stmt = dbConn.createStatement();
String query = "INSERT into ACCOUNT(name, username, password) values('"+name+ "',"+"'"
+ uname + "','" + pwd + "')";
//System.out.println(query);
int records = stmt.executeUpdate(query);
//System.out.println(records);
//When record is successfully inserted
if (records > 0) {
insertStatus = true;
}
} catch (SQLException sqle) {
//sqle.printStackTrace();
throw sqle;
} catch (Exception e) {
//e.printStackTrace();
// TODO Auto-generated catch block
if (dbConn != null) {
dbConn.close();
}
throw e;
} finally {
if (dbConn != null) {
dbConn.close();
}
}
return insertStatus;
}
My table ACCOUNT:
When I debugged on Eclipse, I see the result return is fine, but If I use Advanced rest client tool to get data, it happened an exception:
URL Json:
http://localhost:9999/webserver/register/doregister?name=tester&username=tester#gmail.com&password=test12345
status of result response:
{
"tag": "register",
"status": false,
"error_msg": "Error occured"
}
I have found and tried a lot of ways but not found the cause
How to fix the problem and insert user into database? Thank so much !
I want to make website blocker in my web browser, so I made a database which contain the names of website. Now I want to check the string from database with indexOf method, but it is giving me an error while I am trying to check. Please tell me where my mistake is. Rest of the code is correct and working only database part is not working.
public void loadURL(final String url) {
try {
Connection myconnection;
myconnection = DriverManager.getConnection("jdbc:mysql://localhost/bookmarks", "roo t", "");
try {
String q = "select * from block where url=?";
PreparedStatement mysat = myconnection.prepareStatement(q);
ResultSet myresult = mysat.executeQuery();
int index1;
while (myresult.next()) {
String s2 = myresult.setString("url");
String s1 = txtURL.getText();
index1 = s1.indexOf(s2);
}
if (index1 == -1) {
JOptionPane.showMessageDialog(rootPane, "You Cannot access this website", "Error", JOptionPane.ERROR_MESSAGE);
} else {
Platform.runLater(new Runnable() {
#Override
public void run() {
String tmp = toURL(url);
if (tmp == null) {
tmp = toURL("http://" + url);
}
engine.load(tmp);
}
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
myconnection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
if you use PreparedStatement you have to set a
value for each ? marker:
String q="select * from block where url=?";
PreparedStatement mysat=myconnection.prepareStatement(q);
mysat.setString(1,"www.google.com");
without you have an invalid sql syntax.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I created a website with JSP and Java, it simply displays a form (it's a user registration form) where the user can fill it, then I want it to be stored in a database.
I installed Eclipse, Tomcat (to host on localhost 8080) and Wampserver (to have phpmyadmin and my SQL database).
I've tried to create an ORM (Object-relational mapping), so when the client submits the form, it sends the datas to my ORM, my ORM then stores the datas in my database.
The issue is, when the user submit submits the form, my table is created (I can see it on phpmyAdmin), so it's very good. But it crashes on my website and creates an error
HTTP500, java.lang.NullPointerException.
It says the problem is on
com.jweb.bdd.Orm.Perform(Orm.java:139)
Here is my code in my CreateClient.java file, this java file handles the servlet of my registration form:
public class CreationClient extends HttpServlet {
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
[...]
String lastName= request.getParameter( CHAMP_LASTNAME);
String Name= request.getParameter( CHAMP_NAME);
String mailAdress = request.getParameter( CHAMP_MAILADRESS);
String phoneNumber= request.getParameter( CHAMP_PHONENUMBER);
String login= request.getParameter( CHAMP_LOGIN);
[...]
Orm orm = new Orm();
String[] field = {"login", "firstName", "lastName", "mailAdress", "adress", "phoneNumber", "password"};
String[] values = {login, firstName, lastName, mailAdress, adress, phoneNumber, password};
orm.Insert("client", field);
orm.Values(values);
orm.Perform();
orm.CloseConnection();
[...]
}
}
Here is my Perfom() function in my ORM class:
public void Perform(){
ResultSet rst = null;
if (select != null){
if (from != null && where != null){
try {
rst = statement.executeQuery(select + from + where);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
int i = 0;
while (rst.next()){
res[i] = rst.getString(0) + ":" + rst.getString(1)+ ":" + rst.getString(3) + ":" + rst.getString(4) +":" + rst.getString(5) + ":" + rst.getString(6)+ ":" + rst.getString(7) + ";";
i++;
}
} catch (SQLException e){
e.printStackTrace();
}
}
}
else if (insert != null){
if (values != null){
try {
// statement = connexion.creatStatemnt();
int res = statement.executeUpdate(insert + values);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
try {
rst.close();
} catch (SQLException ignore){
}
if ( statement != null ) {
try {
statement.close();
} catch ( SQLException ignore ) {
}
}
}
And the error on the line 139 is the int res = statement.executeUpdate(insert + values); :
else if (insert != null){
if (values != null){
try {
int res = statement.executeUpdate(insert + values);
} catch (SQLException e) {
e.printStackTrace();
}
}
Do you have any idea how to fix this issue of NullPointer?
Thanks.
You need to initialize your statement object, In your code you used statement.executeQuery() but not statement = connection.createStatement() initialize statement object.