Javaweb常用工具类及配置文件备份
做一个代码备份,以后常用到的。
hibernate工具类备份
package com.dly.service; /* * hibernate获取session 的工具类 */ import java.io.Serializable; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.Session; public final class HibernateUtil { private static SessionFactory sessionFactory; public static SessionFactory getSessionFactory() { return sessionFactory; } private HibernateUtil(){ } static{ Configuration cfg=new Configuration(); cfg.configure();//配置文件名 sessionFactory=cfg.buildSessionFactory(); } public static Session getSession(){ return sessionFactory.openSession(); } /** * 添加信息 * @param entity */ public static void add(Object entity){ Session s=null; Transaction tx=null; try{ s=HibernateUtil.getSession(); tx=s.beginTransaction(); s.save(entity); tx.commit(); }finally{ if(s!=null){ s.close(); } } } /** * 更新信息 * @param entity */ public static void update(Object entity){ Session s=null; Transaction tx=null; try{ s=HibernateUtil.getSession(); tx=s.beginTransaction(); s.update(entity); tx.commit(); }finally{ if(s!=null){ s.close(); } } } /** * 删除信息 * @param entity */ public static void delete(Object entity){ Session s=null; Transaction tx=null; try{ s=HibernateUtil.getSession(); tx=s.beginTransaction(); s.delete(entity); tx.commit(); }finally{ if(s!=null){ s.close(); } } } /** * 根据id查询 * @param clazz * @param id * @return */ public static Object get(Class clazz,Serializable id){ Session s=null; try{ s=HibernateUtil.getSession(); Object obj=s.get(clazz, id); return obj; }finally{ if(s!=null){ s.close(); } } } }
操作数据库举例:
package com.dly.service; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import com.dly.entity.Users; public class UserDao { public static String queryByname(String name){ Session s=null; String result=null; //System.out.println("调用了"); try{ s=HibernateUtil.getSession(); String hql="from Users as user where user.username=:username";//里面User是类名,不是表名,为类名起别名user,查询的是对象 Query query=s.createQuery(hql); query.setString("username", name); Users u=(Users) query.uniqueResult();//确定只有一个数据,限制用户名唯一时使用 // System.out.println(u.getUsername()); if(u!=null){ result=u.getUsername(); System.out.println(result); } return result; }finally{ if(s!=null){ s.close(); } } } public static Users queryByusername(String username,String pwd){ Users user=null; Session s=null; try{ s=HibernateUtil.getSession(); String hql="from Users as users where users.username=:username";//里面User是类名,不是表名,为类名起别名user,查询的是对象 Query query=s.createQuery(hql); query.setString("username", username); List<Users>list =query.list(); for(Users users:list){ String u=users.getUsername(); String p=users.getPassword(); if(u.equals(username)&&p.equals(pwd)){ user=users; } } return user; }finally{ if(s!=null){ s.close(); } } } }
servlet常用代码举例:
package com.dly.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import com.dly.entity.Shop; import com.dly.service.BuyCarDao; import com.dly.service.HibernateUtil; @WebServlet("/BuyCarList") public class BuyCarList extends HttpServlet { private static final long serialVersionUID = 1L; // Class clazz=BuyCar.class; Class<Shop> clazz=Shop.class; List<Shop> shop=new ArrayList<Shop>(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); int userid=Integer.parseInt(request.getParameter("userid")); List<Integer> list=new ArrayList<Integer>(); list=BuyCarDao.querayByuserid(userid); Iterator<Integer> it=list.iterator(); List<Shop>shop=new ArrayList<Shop>(); while(it.hasNext()){ int shopid=(Integer) it.next(); shop.add((Shop) HibernateUtil.get(clazz, shopid)); } JSONArray shoplist=new JSONArray(shop); response.getWriter().println(shoplist.toString()); } }
package com.dly.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dly.entity.BuyCar; import com.dly.service.BuyCarDao; import com.dly.service.HibernateUtil; @WebServlet("/AddBuyCar") public class AddBuyCar extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); BuyCar buycar; int shopid = Integer.parseInt(request.getParameter("shopid")); int userid=Integer.parseInt(request.getParameter("userid")); BuyCar result =BuyCarDao.queryByshopid(shopid); if(result==null){ buycar=new BuyCar(); buycar.setShopid(shopid); buycar.setUserid(userid); HibernateUtil.add(buycar); response.getWriter().print("添加成功"); response.getWriter().flush(); }else{ response.getWriter().print("该商品已在购物车中"); response.getWriter().flush(); } } }
hibernate配置文件编写
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 映射文件 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/trade?useUnicode=true&characterEncoding=UTF-8</property> <property name="connection.username">root</property> <property name="connection.password"></property> <property name="dialect"> org.hibernate.dialect.MySQLDialect</property> <mapping resource="com/dly/entity/Users.hbm.xml"/> </session-factory> </hibernate-configuration>
Users.hbm.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"> <hibernate-mapping package="com.dly.entity"> <class name="Users" table="users" > <!-- id值 --> <id name="userid" type="int" length="11"> <generator class="native"/> </id> <property name="username" type="string" length="32" column="username"></property> <property name="password" type="string" length="32" column="password"></property> <property name="school" type="string" length="64" column="school"></property> <property name="userphone" type="string" length="32" column="userphone"></property> </class> </hibernate-mapping>
此代码正在完善中。。。。。。