my action class is :-
package com.action;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.apache.struts2.convention.annotation.*;
import org.apache.struts2.rest.DefaultHttpHeaders;
import com.opensymphony.xwork2.ActionSupport;
@ParentPackage(value="default")
@Namespace("/")
@ResultPath(value="/")
public class noOfUsers extends ActionSupport {
private static final long serialVersionUID = 1L;
@Action(value="usersn",results={
@Result(name="create",type="tiles",location="users")
})
public static DefaultHttpHeaders create(){
EntityManagerFactory emf=Persistence.createEntityManagerFactory("tujpa");
Entity开发者_StackOverflow社区Manager em=emf.createEntityManager();
EntityTransaction entr=em.getTransaction();
entr.begin();
Query query=em.createQuery("SELECT U.firstname from User U");
List <User> list = query.getResultList();
System.out.println("password");
Iterator iterator = list.iterator();
System.out.println("password1");
while(iterator.hasNext()){
String empFirstName = (String)iterator.next();
System.out.print("Emp Name:"+empFirstName );
System.out.println("password2");
}
entr.commit();
em.close();
return new DefaultHttpHeaders("create");
}
}
and i want to display my result list on my jsp page, so please guide. thanks in advance.
Okay I can see why there has not been an answer... you've taken some JPA code which prints to the terminal and then pasted that into S2 class which you've found off the Internet?
Please start with a simple "Hello World" application: http://struts.apache.org/2.2.1.1/docs/getting-started.html
When that is running, there are plenty of examples of using the iterator tag. This tag goes on the JSP, and is documented on the above listed site.
Your action code then would become something like (quick hack job):
public class UserList extends ActionSupport {
List <User> list;
public String action(){
EntityManagerFactory emf=Persistence.createEntityManagerFactory("tujpa");
EntityManager em=emf.createEntityManager();
EntityTransaction entr=em.getTransaction();
entr.begin();
Query query=em.createQuery("SELECT U.firstname from User U");
list = query.getResultList();
em.close();
return SUCCESS;
}
}
Now you should research some DI framework... S2 has good Spring integration moving the EntityManagerFactory/EntityManager handling to Spring would make the above much cleaner. Something like:
public String action(){
list = em.createQuery("SELECT U.firstname from User U").getResultList();
return SUCCESS;
}
精彩评论