今天准备写一个在线电子书应用,SSH作为后台,使用JSON进行数据交互
数据库字段
其实做这个小小应用,也没得必要什么Struts,Spring,Hibernate 都上,有点大材小用了,所以配置的时候就用了
Struts,和Hibernate,就不用Spring管理了,为了节约时间,也省了Service 层也取消了
Struts的struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="book" extends="struts-default" namespace="/">
<action name="addbook" class="com.book.action.AddBookAction" >
<result name="success" >/AddBookSuccess.jsp</result>
<result name="error" >/AddBookError.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
<package name="booktype" extends="json-default">
<action name="booktype" class="com.book.action.ShowTypeAction" method="showtype">
<result type="json" ></result>
</action>
<action name="bookstbt" class="com.book.action.ShowTitleByTypeAction" method="showtitle">
<result type="json" ></result>
</action>
<action name="bookcbt" class="com.book.action.ShowContentByTitleAction" method="showcontent">
<result type="json" ></result>
</action>
</package>
</struts>
实体映射文件xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.book.model.Book" table="book" catalog="book">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native"></generator>
</id>
<property name="title" type="java.lang.String">
<column name="title" length="16777215" />
</property>
<property name="content" type="java.lang.String">
<column name="content" length="16777215" />
</property>
<property name="time" type="java.lang.String">
<column name="time" length="100" />
</property>
<property name="type" type="java.lang.String">
<column name="type" length="100" />
</property>
</class>
</hibernate-mapping>
管理数据库dao层,BookDAO.ava
package com.book.dao;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.book.model.Book;
/**
* A data access object (DAO) providing persistence and search support for Book
* entities. Transaction control of the save(), update() and delete() operations
* can directly support Spring container-managed transactions or they can be
* augmented to handle user-managed Spring transactions. Each of these methods
* provides additional information for how to configure it for the desired type
* of transaction control.
*
* @see com.book.model.Book
* @author MyEclipse Persistence Tools
*/
public class BookDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory.getLogger(BookDAO.class);
// property constants
public static final String TITLE = "title";
public static final String CONTENT = "content";
public static final String TIME = "time";
public static final String TYPE = "type";
public void save(Book transientInstance) {
log.debug("saving Book instance");
try {
Transaction tx=getSession().beginTransaction();
getSession().save(transientInstance);
tx.commit();
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(Book persistentInstance) {
log.debug("deleting Book instance");
try {
getSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Book findById(java.lang.Integer id) {
log.debug("getting Book instance with id: " + id);
try {
Book instance = (Book) getSession().get("com.book.dao.Book", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public ArrayList<String> findtypes() {
String hql ="select distinct b.type from Book as b";
List list = null;
ArrayList<String> booktype=new ArrayList<String>();
try{
Query query =getSession().createQuery(hql);
list=query.list();
for (int i = 0; i < list.size(); i++) {
String st = (String) list.get(i);
booktype.add(st.toString());
}
}catch (Exception e) {
e.printStackTrace();
}
return booktype;
}
public List findByExample(Book instance) {
log.debug("finding Book instance by example");
try {
List results = getSession().createCriteria("com.book.dao.Book")
.add(Example.create(instance)).list();
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding Book instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Book as model where model."
+ propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List findByTitle(Object title) {
return findByProperty(TITLE, title);
}
public List findByContent(Object content) {
return findByProperty(CONTENT, content);
}
public List findByTime(Object time) {
return findByProperty(TIME, time);
}
public List findByType(Object type) {
return findByProperty(TYPE, type);
}
public List findAll() {
log.debug("finding all Book instances");
try {
String queryString = "from Book";
Query queryObject = getSession().createQuery(queryString);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public Book merge(Book detachedInstance) {
log.debug("merging Book instance");
try {
Book result = (Book) getSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(Book instance) {
log.debug("attaching dirty Book instance");
try {
getSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(Book instance) {
log.debug("attaching clean Book instance");
try {
getSession().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
}
这个是添加书籍的action
package com.book.action;
import java.util.Date;
import com.book.dao.BookDAO;
import com.book.model.Book;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class AddBookAction extends ActionSupport implements ModelDriven<Book>{
private Book book;
private BookDAO dao;
public AddBookAction() {
dao=new BookDAO();
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
try {
if (getModel().getTitle()!=null) {
Book b1=new Book();
b1.setTitle(getModel().getTitle());
b1.setContent(getModel().getContent());
b1.setTime(new Date().toLocaleString());
b1.setType(getModel().getType());
dao.save(b1);
}
return SUCCESS;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return ERROR;
}
}
public Book getModel() {
// TODO Auto-generated method stub
if (book==null) {
book=new Book();
}return book;
}
}
这个是显示书籍类别的Action
package com.book.action;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.book.dao.BookDAO;
import com.book.model.Book;
import com.opensymphony.xwork2.ActionSupport;
public class ShowTypeAction extends ActionSupport implements ServletResponseAware ,ServletRequestAware{
private HttpServletResponse response;
private HttpServletRequest request;
private String title;
private BookDAO dao;
public ShowTypeAction() {
dao=new BookDAO();
}
public void showtype() {
try {
// TODO Auto-generated method stub
ArrayList<String> types=dao.findtypes();
this.response.setContentType("text/html;charset=utf-8");
this.response.setCharacterEncoding("UTF-8");
JSONObject json=new JSONObject();
Map map=new HashMap<Object, String>();
for (int i = 0; i < types.size(); i++) {
map.put("type"+i, types.get(i));
}
json.put("Types", map);
response.getWriter().write(json.toString());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void setServletResponse(HttpServletResponse arg0) {
// TODO Auto-generated method stub
response=arg0;
}
public void setServletRequest(HttpServletRequest arg0) {
// TODO Auto-generated method stub
request=arg0;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
这个是根据 文章类型查找 显示 文章标题 .action
package com.book.action;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.book.dao.BookDAO;
import com.book.model.Book;
import com.opensymphony.xwork2.ActionSupport;
public class ShowTitleByTypeAction extends ActionSupport implements ServletRequestAware,ServletResponseAware{
private HttpServletResponse response;
private HttpServletRequest request;
private BookDAO dao;
private String typename;
private ArrayList<Book> books;
//private ArrayList<String> strings;
public ShowTitleByTypeAction() {
dao=new BookDAO();
}
public void showtitle() {
try {
// TODO Auto-generated method stub
this.response.setContentType("text/html;charset=utf-8");
this.response.setCharacterEncoding("UTF-8");
Map map=new HashMap<Object, String>();
books=(ArrayList<Book>) dao.findByType(typename);
System.out.println("---"+typename);
for (int i = 0; i < books.size(); i++) {
map.put("title"+i,books.get(i).getTitle());
}
JSONObject json=new JSONObject();
json.put("Titles", map);
response.getWriter().write(json.toString());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void setServletResponse(HttpServletResponse arg0) {
// TODO Auto-generated method stub
this.response=arg0;
}
public void setServletRequest(HttpServletRequest arg0) {
// TODO Auto-generated method stub
this.request=arg0;
}
public String getTypename() {
return typename;
}
public void setTypename(String typename) {
this.typename=typename;
}
}
这个是根据文章标题查找 文章类容.action,其实这里应该有主键id 查找了,要是标题重复就麻烦了,先这样弄了,以后慢慢完善....
package com.book.action;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.book.dao.BookDAO;
import com.book.model.Book;
import com.opensymphony.xwork2.ActionSupport;
public class ShowContentByTitleAction extends ActionSupport implements ServletRequestAware,ServletResponseAware{
private HttpServletResponse response;
private HttpServletRequest request;
private BookDAO dao;
private String titlename;
private ArrayList<Book> books;
//private ArrayList<String> strings;
public ShowContentByTitleAction() {
dao=new BookDAO();
}
public void showcontent() {
try {
// TODO Auto-generated method stub
this.response.setContentType("text/html;charset=utf-8");
this.response.setCharacterEncoding("UTF-8");
Map map=new HashMap<Object, String>();
books=(ArrayList<Book>) dao.findByContent(titlename);
System.out.println("---"+titlename);
for (int i = 0; i < books.size(); i++) {
map.put("content"+i,books.get(i).getTitle());
}
JSONObject json=new JSONObject();
json.put("ContentS", map);
response.getWriter().write(json.toString());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void setServletResponse(HttpServletResponse arg0) {
// TODO Auto-generated method stub
this.response=arg0;
}
public void setServletRequest(HttpServletRequest arg0) {
// TODO Auto-generated method stub
this.request=arg0;
}
public String getTitlename() {
return titlename;
}
public void setTitlename(String titlename) {
this.titlename = titlename;
}
}
由于这个tomcat 有个很让我不爽的东西,那就是 get请求的编码,转换了还是iso-8859-1编码,查了一下各种资料,视乎永远使用的iso-8859-1编码,蛋疼了!还是用post请求了,在web上就不模拟了,在android手机上再提交
、
开始android客服端了...............