這邊是單純的query及insert,使用hibernate來操作DB 的部份。
一、 Java (Action的部份)
package com.blog;
import com.hibernate.hibernateUtil;
import com.opensymphony.xwork2.ActionContext;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.Transaction;
import orm.User;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import org.hibernate.Query;
public class blogAction extends ActionSupport {
public String execute() throws Exception {
init();
if (this.action != null && this.action.equals("a")) {
if (this.username != null && this.username != "") {
System.out.println("Ready to do save users");
this.SaveUsers();
}
} else if (this.action != null && this.action.equals("q")) {
System.out.println("Ready to do query users");
queryUser();
}
return "blog_add";
}
//初始化
private void init(){
session = ActionContext.getContext().getSession();
session.clear();
}
// Save Data To Pojo
private void SaveUsers() {
User user = new User();
user.setName(this.username);
user.setAge(age);
Session session = hibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.save(user);
tx.commit();
session.close();
}
//query Data
private void queryUser() {
Session s = hibernateUtil.getSessionFactory().openSession();
Query q = s.createQuery("from User");
List l = q.list();
//set session
//ActionContext.getContext().getSession().put("blog", l);
session.put("blog", l);
// Map s =getSession();
// s.put("blog", age);
// this.setSession(s);
// Map s = ActionContext.getContext().getSession();
// s.put("blogSession", l);
// for(java.util.Iterator it = l.iterator(); it.hasNext();){
// User user = (User)it.next();
//System.out.println("User:"+user.getName());
// System.out.println(it.next());
// }
s.close();
}
private String username;
private int age;
private String action;
private Map session;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
}
二、 JSP (View的部份)
<%--
Created on : 2008/9/8, 下午 02:33:31
Author : jimmy
--%>
< form action="blog.action" method="post">
< input type="text" name="username" value="" />
< input type="text" name="age" value="" />
< input type="hidden" name="action" value="a">
< input type="submit" value="Add" name="Add" />
< /form>
< %
if( s ession.getAttribute("blog")!=null){
java.util.List blog = (j ava.util.List)session.getAttribute("blog");
if(blog!=null){
for(int i = 0 ; i < blog.size();i++){
out.println("
orm.User user = (orm.User) blog.get(i);
out.println("
out.println("
out.println("
out.println("
out.println("
} } }
%>
< /table>
沒有留言:
張貼留言