I am writing this program in which I am using preparedStatements to make changes to an SQL Database. However, the UPDATE query is not working.
Here is the code:
package financials;
import java.net.URL;
import java.util.ResourceBundle;
import java.sql.*;
public void initialize(URL url, ResourceBundle rb) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/finances","root","P#ssword");
con.setAutoCommit(true);// TODO
}
catch(Exception ae)
{
System.out.println("Error in connection !");
}
#FXML
private void SaveOrAdd(ActionEvent event) { //This is button which on click executes the following code
String Action=save.getText();
if(Action.equals("Add Account"))
{
String SBNumber=LinkedSB.getText();
String newAccountType=AccountTypeF.getText();
String newFHolder=FHolderF.getText();
String newSHolder=SHolderF.getText();
String newTHolder=THolderF.getText();
String Bankcode=BankCodeF.getText();
if(newAccountType.equals("")||newFHolder.equals("")||newSHolder.equals("")||newTHolder.equals(""))
{
update.setText("Please fill in all the fields !");
}
else
{
try
{
PreparedStatement pst=con.prepareStatement("INSERT INTO banklines (Bank_Code,Linked_SB_Account,Sb_Account_Type,First_Holder,Second_Holder,Third_Holder) VALUES (?,?,?,?,?,?)");
pst.setString(1,Bankcode);
pst.setString(2,SBNumber);
pst.setString(3,newAccountType);
pst.setString(4,newFHolder);
pst.setString(5,newSHolder);
pst.setString(6,newTHolder);
int a=pst.executeUpdate();
System.out.println(a); //This returns a 1
}
catch(Exception ae)
{
update.setText("Update Failed !");
}
}}
else
{
String SBNumber=LinkedSB.getText();
String newAccountType=AccountTypeF.getText();
String newFHolder=FHolderF.getText();
String newSHolder=SHolderF.getText();
String newTHolder=THolderF.getText();
String Bankcode=BankCodeF.getText();
if(newAccountType.equals("")||newFHolder.equals("")||newSHolder.equals("")||newTHolder.equals(""))
{
update.setText("Please fill in all the fields !");
}
else //This is the block in concern
{
try
{
//Here is where the issue starts !
PreparedStatement pst2=con.prepareStatement("UPDATE banklines SET Sb_Account_Type=?,First_Holder=?,Second_Holder=?,Third_Holder=? WHERE Linked_SB_Account=? AND Bank_Code=?");
pst2.setString(1,newAccountType);
pst2.setString(2,newFHolder);
pst2.setString(3,newSHolder);
pst2.setString(4,newTHolder);
pst2.setString(5,SBNumber);
pst2.setString(6,Bankcode);
pst2.executeUpdate();
int a=pst2.executeUpdate();
System.out.println(a); //This returns a 0
update.setText("Successfully Updated !");
}
catch(Exception ae)
{
update.setText("Update Failed !");
}
}
}
}
The problem is that no error is being thrown, that is, the output is always Successfully Updated. However, the changes are not being reflected on the database. I have tried executing the query UPDATE banklines SET Sb_Account_Type=?,First_Holder=?,Second_Holder=?,Third_Holder=? WHERE Linked_SB_Account=? AND Bank_Code=? separately as a query in mySQL workbench, and it returns no error. I have also ensured that no variable is left blank. In-spite of all this, the update is not working. What confused me even more is that the previous query in the if-else block, that is the INSERT query works perfectly, and the results are updated in the database as well.
I am using NetBeans 8.2 with jdk 1.8 and mysql-connector-java-8.0.21.
P.S. I have stuck to java naming conventions to the best of my knowledge, ensuring that I follow CamelCase notation wherever I could. Please edit my code or suggest changes if you feel that anything is wrong.
The column names of your insert statement don't match the order of the bind variables which means that your inserted record has the wrong account id values.
For example you set SBNumber as index 6 when it should be:
pst.setString(2,SBNumber);
It is also good practice to check the number of rows changed by updates so that you can make further asserts / checks on your actions:
int rows = pst.executeUpdate();
if (rows != 1) throw new RuntimeException("Failed to update account: "+ SBNumber);
In your case rows is set to 0 as the row to update is never found - because Linked_SB_Account is not matched.
Related
I am currently reworking an ADF Fusion Web application using Jdev v12.2.1.4.0 (Oracle 12c).
On one of the jsf pages I have a SelectOneChoice inside a table column. The jsf-implementation looks like this:
<af:column
headerText="#{ManagedBean.column5HeaderText}"
sortable="false"
visible="true"
id="c5">
<af:selectOneChoice
binding="#{ManagedBean.bindingErrorCaseSelectOneChoice}"
label="error case"
unselectedLabel="---"
autoSubmit="true"
id="soc1">
<f:selectItems value="#{ManagedBean.errorCases}" id="si1"/>
</af:selectOneChoice>
</af:column>
I left out the required attribute because it is not necessary for the process to select a value here.
The coherent parts of my ManagedBean.java are as following:
//declaring
private RichSelectOneChoice bindingErrorCasesSelectOneChoice;
private List<SelectItem> errorCases = new ArrayList<SelectItem>();
//...
//populating errorCases List from a database
public void getErrorCasesFromDB() {
errorCases= new ArrayList<SelectItem>();
try {
//HC is a helper class to connect to a specific database
Conection conn = HC.getConn();
PreparedStatement pstmt = conn.prepareStatement("some SQL");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
errorCases.add(new SelectItem("i"+ rs.getRow(), rs.getString(1)));
}
conn.close();
} catch(Exception e) {
e.printStackTrace();
}
}
As I run the jsf page the SelectOneChoices inside the table get rendered and all the expected items are enlisted. I am facing a problem whenever i try to access the selected item of the SelectOneChoice.
I want to read the value of the selectedItem when I hit a button on the page, so I figured I could leave out having to deal with that in a valueChangeListener, and did the following in my button action:
public void buttonSaveReceivedResults(ActionEvent actionEvent) {
//...
if (bindingErrorCaseSelectOneChoice.getValue != null) {
//... insert the selected value into an SQL statement
//in the case the unselected label is selected, skip
System.out.println(bindingErrorCasesSelectOneChoice.getValue().toString())
}
}
This block always gets skipped. Also when i inspected the process, the getValue() call always returned null, even if i select an item from the list.
Now i'm asking you guys, where is the missing part in the chain? Did I do the data bindings correctly. Do I access the elements in the wrong way? Thanks in advance.
The value attribute stores the output of af:selectOneChoice component. Since you have not added it, value returned was null.
Im trying to parse a pipe delimited file and insert fields into a table. when i start the application nothing happens in my DB. My DB has 4 columns (account_name, command_name, and system_name, CreateDt). The file i am parsing has the date in the first row then extra data. The rows following i only need the first 3 fields in each the rest is extra data. the last row is the row count. i skipped the inserting date because for now but want to get back to it after at least able to insert the first 3 fields. I have little experience with parsing a file and storing data in a DB and have looked through jdbc examples to get to this point but im struggling and am sure there is a better way.
File Example
20200310|extra|extra|extra||
Mn1223|01192|windows|extra|extra|extra||
Sd1223|02390|linux|extra|extra|extra||
2
table format
account_name command_name system_name createDt
Mn1223 01192 windows 20200310
Sd1223 02390 linux 20200310
Code to parse and insert into DB
public List insertZygateData (List<ZygateEntity> parseData) throws Exception {
String filePath = "C:\\DEV\\Test_file.xlsx";
List<String> lines = Files.readAllLines(Paths.get(filePath));
// remove date and amount
lines.remove(0);
lines.remove(lines.size() - 1);
for (ZygateEntity zygateInfo : parseData){
new MapSqlParameterSource("account_name", zygateInfo.getAccountName())
.addValue("command_name", zygateInfo.getCommandName())
.addValue("system_name", zygateInfo.getSystemName())
.getValues();
}
return lines.stream()
.map(s -> s.split("[|]")).map(val -> new ZygateEntity(val[0],val[1],val[2])).collect(Collectors.toList());
}
public boolean cleantheTable() throws SQLException {
String sql = "INSERT INTO Landing.midrange_xygate_load (account_name,command_name,system_name)"+
"VALUES (:account_name,:command_name,:system_name)";
boolean truncated = false;
Statement stmt = null;
try {
String sqlTruncate = "truncate table Landing.midrange_xygate_load";
jdbcTemplate.execute(sqlTruncate);
truncated = true;
} catch (Exception e) {
e.printStackTrace();
truncated = false;
return truncated;
} finally {
if (stmt != null) {
jdbcTemplate.execute(sql);
stmt.close();
}
}
log.info("Clean the table return value :" + truncated);
return truncated;
}
}
Entity/Model
public ZygateEntity(String accountName, String commandName, String systemName){
this.accountName=accountName;
this.commandName=commandName;
this.systemName=systemName;
}
//getters and setters
#Override
public String toString() {
return "ZygateEntity [accountName=" + accountName + ", commandName=" + commandName + ", systemName=" + systemName + ", createDt=" + createDt +"]";
}
}
Taking a look at what you've provided, it seems you have a jumbled collection of bits of code, and while most of it is there, it's not all there and not quite all in the right order.
To get some kind of clarity, try to break down what it is you're doing into separate steps, and have a method that focuses on each step. In particular, you write
Im trying to parse a pipe delimited file and insert fields into a table
This naturally breaks down into two parts:
parsing the pipe-delimited file, and
inserting fields into a table.
For the first part, you seem to have most of the parts already in your insertZygateData method. In particular, this line reads all the lines of a file into a list:
List<String> lines = Files.readAllLines(Paths.get(filePath));
These lines then remove the first and last lines from the list of lines read:
// remove date and amount
lines.remove(0);
lines.remove(lines.size() - 1);
You then have some code that looks a bit out of place: this seems to be something to do with inserting into the database, but we haven't created our list of ZygateEntity objects as we haven't yet finished reading the file. Let's put this for loop to one side for the moment.
Finally, we take the list of lines we read, split them using pipes, create ZygateEntity objects from the parts and create a List of these objects, which we then return.
return lines.stream()
.map(s -> s.split("[|]")).map(val -> new ZygateEntity(val[0],val[1],val[2])).collect(Collectors.toList());
Putting this lot together, we have a useful method that parses the file, completing the first part of the task:
private List<ZygateEntity> parseZygateData() throws IOException {
String filePath = "C:\\DEV\\Test_file.xlsx";
List<String> lines = Files.readAllLines(Paths.get(filePath));
// remove date and amount
lines.remove(0);
lines.remove(lines.size() - 1);
return lines.stream()
.map(s -> s.split("[|]")).map(val -> new ZygateEntity(val[0],val[1],val[2])).collect(Collectors.toList());
}
(Of course, we could add a parameter for the file path to read, but in the interest of getting something working, it's OK to stick with the current hard-coded file path.)
So, we've got our list of ZygateEntity objects. How do we write a method to insert them into the database?
We can find a couple of the ingredients we need in your code sample. First, we need the SQL statement to insert the data. This is in your cleanThetable method:
String sql = "INSERT INTO Landing.midrange_xygate_load (account_name,command_name,system_name)"+
"VALUES (:account_name,:command_name,:system_name)";
We then have this loop:
for (ZygateEntity zygateInfo : parseData){
new MapSqlParameterSource("account_name", zygateInfo.getAccountName())
.addValue("command_name", zygateInfo.getCommandName())
.addValue("system_name", zygateInfo.getSystemName())
.getValues();
}
This loop creates a MapSqlParameterSource out of each ZygateEntity object, and then converts it to a Map<String, Object> by calling the getValues() method. But then it does nothing with this value. Effectively you're creating these objects and getting rid of them again without doing anything with them. This isn't ideal.
A MapSqlParameterSource is used with a Spring NamedParameterJdbcTemplate. Your code mentions a jdbcTemplate, which appears to be a field within the class that parses data and inserts into the database, but you don't show the full code of this class. I'm going to have to assume it's a NamedParameterJdbcTemplate rather than a 'plain' JdbcTemplate.
A NamedParameterJdbcTemplate contains a method update that takes a SQL string and a SqlParameterSource. We have a SQL string, and we're creating MapSqlParameterSource objects, so we can use these to carry out the insert. There's not a lot of point in creating one of these MapSqlParameterSource objects only to convert it to a map, so let's remove the call to getValues().
So, we now have a method to insert the data into the database:
public void insertZygateData(List<ZygateEntity> parseData) {
String sql = "INSERT INTO Landing.midrange_xygate_load (account_name,command_name,system_name)"+
"VALUES (:account_name,:command_name,:system_name)";
for (ZygateEntity zygateInfo : parseData){
SqlParameterSource source = new MapSqlParameterSource("account_name", zygateInfo.getAccountName())
.addValue("command_name", zygateInfo.getCommandName())
.addValue("system_name", zygateInfo.getSystemName());
jdbcTemplate.update(sql, source);
}
}
Finally, let's take a look at your cleanThetable method. As with the others, let's keep it focused on one task: it looks like at the moment you're trying to delete the data out of the table and then insert it in the same method, but let's have it just focus on deleting the data as we've now got a method to insert the data.
We can't immediately get rid of the String sql = ... line, because the finally block in your code uses it. If stmt is not null, then you attempt to run the INSERT statement and then close stmt.
However, stmt is never assigned any value other than null, so it remains null. stmt != null is therefore always false, so the INSERT statement never runs. Your finally block never does anything, so you would be best off removing it altogether. With your finally block gone, you can also get rid of your local variable stmt and the sql string, leaving us with a method whose focus is to truncate the table:
public boolean cleantheTable() throws SQLException {
boolean truncated = false;
try {
String sqlTruncate = "truncate table Landing.midrange_xygate_load";
jdbcTemplate.execute(sqlTruncate);
truncated = true;
} catch (Exception e) {
e.printStackTrace();
truncated = false;
return truncated;
}
log.info("Clean the table return value :" + truncated);
return truncated;
}
I'll leave it up to you to write the code that calls these methods. I wrote some code for this purpose, and it ran successfully and inserted into a database.
So, in summary, no data was being written to your database because you were never making a call to the database to insert any. In your insertZygateData method you were creating the parameter-source objects but not doing anything useful with them, and in your cleanThetable method, it looked like you were trying to insert data, but your line jdbcTemplate.execute(sql) that attempted to do this never ran. Even if stmt wasn't null, this line wouldn't work as you didn't pass the parameter values in anywhere: you would get an exception from the database as it would be expecting values for the parameters but you never gave it any.
Hopefully my explanation gives you a way of getting your code working and helps you understand why it wasn't.
I have a table which has a column named tripNumber which shouldnt have a duplicate.
I know, that I can alter the table and make that column unique but for some reason, I cant alter the table as it's already in production. Hence I wrote the following trigger which basically does the same thing.
USE [cst_abc]
GO
/****** Object: Trigger [dbo].[checkTripNumber] Script Date: 12/21/2019 18:37:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE trigger [dbo].[checkTripNumber] on [dbo].[tripDetails]
instead of insert
as
begin
if exists(select * from [dbo].[tripDetails] where tripNumber = (select [tripNumber] from inserted i))
RAISERROR ('Trip is already there.',15,0);
else
INSERT INTO [cst_abc].[dbo].[tripDetails]
([tripNumber]
,[noW]
,[EndTime]
,[someText]
,[totalInput]
,[totalOutput]
,[Difference]
,[start]
,[end]
,[StartTime]
,[EndTime]
,[serverSync])
SELECT[tripNumber],[noW],[EndTime]
,[someText]
,[totalInput]
,[totalOutput]
,[Difference]
,[start]
,[end]
,[StartTime]
,[EndTime]
,[serverSync] from inserted i
end
GO
It does work as expected. I wrote a small java code which basically starts a new thread and try to insert rows. What I do is to first check if a trip exists, if yes, does nothing, else inserts a new row with a particular id.
public static void startThread()
{
new Thread(() -> {
try {
showTimeInMilli("FuncA");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
showTimeInMilli("FuncB");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}).start();
}
public static void showTimeInMilli(String name) throws SQLException
{
System.out.println("called from "+name +"Current time is "+System.currentTimeMillis());
if(checkTripNumber(1))
{
System.out.println("called from "+name +" and trip exists.");
}
else
{
System.out.println("called from "+name +" and inserting new row.");
SqlUtil.startNewTrip(1,7,"ap1","2019-06-18 07:06:00",5,1576631560);
}
}
Point to be noted here is that, this trigger i.e to startTrip can be triggered from multiple source and I have seen that most of the times it gets triggered at the same time ( I store the epoch time for example from two sources it gets triggered at exactly 1576934304)
Problem
9 out of 10 times it works expected, i.e it doesnt let a new row added but at times, it adds a duplicate tripNumber. Any help is highly appreciated.
Ideal Log for the above java code is :
called from FuncACurrent time is 1576933097423
called from FuncBCurrent time is 1576933097423
td before sendig false
called from FuncB and inserting new row.
td before sendig false
called from FuncA and inserting new row.
com.microsoft.sqlserver.jdbc.SQLServerException: Trip is already there.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1655)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:440)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:385)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:191)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:166)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.execute(SQLServerPreparedStatement.java:367)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.execute(ProxyPreparedStatement.java:44)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.execute(HikariProxyPreparedStatement.java)
at database.SqlUtil.startNewTrip(SqlUtil.java:45)
at database.Hikari.showTimeInMilli(Hikari.java:122)
at database.Hikari.lambda$0(Hikari.java:44)
at java.lang.Thread.run(Unknown Source)
SQL Exception2 com.microsoft.sqlserver.jdbc.SQLServerException: Trip is already there.
Un-expected Log is :
called from FuncACurrent time is 1576933097323
called from FuncBCurrent time is 1576933097323
td before sendig false
called from FuncB and inserting new row.
td before sendig false
called from FuncA and inserting new row.
The case is INSERT is separated from checking for tripNumber existence:
INSERT INTO [cst_abc].[dbo].[tripDetails]
([tripNumber]
,[noW]
,[EndTime]
,[someText]
,[totalInput]
,[totalOutput]
,[Difference]
,[start]
,[end]
,[StartTime]
,[EndTime]
,[serverSync])
SELECT[tripNumber],[noW],[EndTime]
,[someText]
,[totalInput]
,[totalOutput]
,[Difference]
,[start]
,[end]
,[StartTime]
,[EndTime]
,[serverSync]
from inserted i
where NOT EXISTS (SELECT 1 FROM [dbo].[tripDetails] d WHERE i.[tripNumber] = d.[tripNumber]);
Anyway this kind of "workaround" is not good approach and normal "UNIQUE" constraint should be introduced instead.
EDIT:
I cant alter the table as it's already in production
How about adding unique index(technically speaking table is not altered, index is separate object):
CREATE UNIQUE INDEX udx_tripDetails(tripNumber) ON [dbo].[tripDetails](tripNumber)
WITH(ONLINE = ON);
I wanted to prevent my java program from accepting/inserting blank or "" value in the database. I already set columns username and password as not null though but it keeps on accepting blank or "" values.
heres a part my code for adding values into the DB:
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
try{
theQuery("insert into accounts (username,password) values ('"+user1.getText()+"', '"+pass1.getText()+"')");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Unable to add record to the database");
}
}
P.S. password is not hashed since this is for activity only.
try like this:
String str=user1.getText();
if ("".equals(str)){ //User have not entered anything.
JOptionPane.showMessageDialog(null,"Please enter your name.");
nameField.requestFocusInWindow();
//Do NOT loop here.
}
else {
//Do everything you need to do when the user have entered something
}
FYI You might also want to look at Apache Commons StringUtils for testing of null, empty, blank strings:
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
It has lots of handy (nullsafe) methods like "isBlank", "isEmpty" etc
Replacing idioms like:
if (myString != null && myString != "")
With:
if (!StringUtils.isBlank(myString))
I am new to this forum. I have a doubt about JSP/servlet in my application
I have developed an application in which user may search some data based on some criteria and he will get data from database(through Hibernate to servlet and to JSP). When some data is displayed on screen based on search he/she may try to copy the URL and forward to anyone or If he try to open in different browser it is showing an empty page.
eg: if i try to paste the link given bellow it is showing blank page
example link
but i need to display the data how this can be achieved.
Edited: After clicking on job search in menu bar as mentioned in comments the page will redirect to a servlet
if(action.equals("searchjob")){
String requireskills=request.getParameter("txt_requireSkills");
String location=request.getParameter("txt_locationName");
session.setAttribute("location",location);
String minexp1=request.getParameter("dd_minimum");
String maxexp1=request.getParameter("dd_maximum");
jobsearchDAO = new JobSearchDAOImpl();
List<JobPostInfo> data=jobsearchDAO.jobsearchlist(requireskills,location,minexp1,maxexp1);
if(data!=null && data.size()!=0){
//save data
if(!(session.getAttribute("LoginObject")==null)){
JobSeeker jobSeeker=(JobSeeker)session.getAttribute("LoginObject");
JobSearchCriteria jobsearchcriteria= new JobSearchCriteria();
jobsearchDAO=new JobSearchDAOImpl();
jobsearchcriteria.setKeyWords(requireskills);
jobsearchcriteria.setLocation(location);
JobSeeker jobseeker=(JobSeeker)session.getAttribute("jobseeker");
//
// jobsearchcriteria.setJobSeeker(jobseeker.getJobSeekerSn());
jobsearchcriteria.setJscTs(new Date());
int value=jobsearchDAO.savesearch(jobsearchcriteria);
System.out.println("savesearch value------>"+value);
}
session.setAttribute("jobsearchlist", data);
// session.setAttribute("success","Search Criteria is saved to database.");
response.sendRedirect("jobsearchresult.jsp");
}else
{
session.setAttribute("error","No Records found");
response.sendRedirect("jobsearch.jsp");
}
}
This is the code in DAOIMPL
public List<JobPostInfo> jobsearchlist(String requireskills,String location,String minexp1,String maxexp1) throws Exception{
long minexp;
long maxexp;
try{
session =getSession();
//Criteria Query
Criteria query=session.createCriteria(JobPostInfo.class,"jpost");
// if(minexp1.equals("0") && (maxexp1.equals("") || maxexp1==null)){
if((minexp1.equals("-1") || minexp1=="-1") && maxexp1==null){
}
else if(minexp1.equals("0")){
minexp=Long.parseLong(minexp1);
long min=1;
query.add(Restrictions.lt("jpost.experienceMin",min));
}else if(!(minexp1.equals("") || minexp1==null) && maxexp1.equals("-1")) {
minexp=Long.parseLong(minexp1);
query.add(Restrictions.ge("jpost.experienceMin",minexp));
}else if(!(minexp1==null && maxexp1==null)){
minexp=Long.parseLong(minexp1);
maxexp=Long.parseLong(maxexp1);
query.add(Restrictions.and(Restrictions.ge("jpost.experienceMin",minexp),Restrictions.le("jpost.experienceMax",maxexp)));
}
//For Location
if(!(location==null|| location.equals(""))){
query.createAlias("jpost.location","location");
query.add(Restrictions.like("location.locationName",location).ignoreCase());
}
//For Keyword
if(!(requireskills==null || requireskills.equals(""))){
query.add(Restrictions.like("jpost.requiredSkills","%"+requireskills+"%").ignoreCase());
}//requireskills
List<JobPostInfo> list = query.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
if(list.size()==0){
return null;
}else{
return list;
}
}catch(HibernateException e){
e.printStackTrace();
}finally {
close(session);
}
return null;
}
I solved my problem. It's a very basic mistake and I hope this will help others:
response.sendRedirect("jobsearchresult.jsp") is replaced by request.getRequestDispatcher("studentinformation.jsp").forward(request, response)
or include-method. The second thing is, the session is created and initialized with the servlet. When I copy the link in a different browser, a certain block of the servlet will be executed. Example:
action.equals("searchjob")
So at the time the session is not available yet, I initialize it in every block like separating declaration and initialization.