发表代码测试

PetStore 代码 MainServlet.java
package com.sun.j2ee.blueprints.waf.controller.web;

import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;

// J2EE Imports
import javax.naming.NamingException;

// WAF imports
import com.sun.j2ee.blueprints.waf.util.I18nUtil;
import com.sun.j2ee.blueprints.waf.exceptions.GeneralFailureException;
import com.sun.j2ee.blueprints.util.tracer.Debug;
import com.sun.j2ee.blueprints.waf.controller.web.URLMappingsXmlDAO;
import com.sun.j2ee.blueprints.waf.controller.web.RequestProcessor;
import com.sun.j2ee.blueprints.waf.controller.web.util.WebKeys;
import com.sun.j2ee.blueprints.waf.util.JNDINames;
import com.sun.j2ee.blueprints.waf.controller.web.flow.FlowHandlerException;
import com.sun.j2ee.blueprints.waf.controller.web.flow.ScreenFlowManager;
import com.sun.j2ee.blueprints.waf.controller.web.WebController;

public class MainServlet extends HttpServlet {

    private ServletContext context;
    private HashMap urlMappings;
    private HashMap eventMappings;
    private Locale defaultLocale = null;

    private RequestProcessor requestProcessor;


    public void init(ServletConfig config) throws ServletException {
        String defaultLocaleString = config.getInitParameter("default_locale");
        defaultLocale = I18nUtil.getLocaleFromString(defaultLocaleString);
        this.context = config.getServletContext();
        String requestMappingsURL = null;
        try {
            requestMappingsURL = context.getResource("/WEB-INF/mappings.xml").toString();
        } catch (java.net.MalformedURLException ex) {
            System.err.println("MainServlet: initializing ScreenFlowManager malformed URL exception: " + ex);
        }
       urlMappings = URLMappingsXmlDAO.loadRequestMappings(requestMappingsURL);
       context.setAttribute(WebKeys.URL_MAPPINGS, urlMappings);
       eventMappings = URLMappingsXmlDAO.loadEventMappings(requestMappingsURL);
       context.setAttribute(WebKeys.EVENT_MAPPINGS, eventMappings);
       getScreenFlowManager();
       getRequestProcessor();
    }

     public  void doGet(HttpServletRequest request, HttpServletResponse  response)
        throws IOException, ServletException {
        doProcess(request, response);
    }

    public  void doPost(HttpServletRequest request, HttpServletResponse  response)
        throws IOException, ServletException {
        doProcess(request, response);

    }

    private void doProcess(HttpServletRequest request, HttpServletResponse response)
                   throws IOException, ServletException {
        // set the locale of the user to default if not set
        if (request.getSession().getAttribute(WebKeys.LOCALE) == null) {
            request.getSession().setAttribute(WebKeys.LOCALE, defaultLocale);
        }
        try {
                 getRequestProcessor().processRequest(request);
                 getScreenFlowManager().forwardToNextScreen(request,response);
        } catch (Throwable ex) {
            String className = ex.getClass().getName();
            String nextScreen = getScreenFlowManager().getExceptionScreen(ex);
            // put the exception in the request
            request.setAttribute("javax.servlet.jsp.jspException", ex);
            if (nextScreen == null) {
                // send to general error screen
                ex.printStackTrace();
                throw new ServletException("MainServlet: unknown exception: " + className);
            }
            context.getRequestDispatcher(nextScreen).forward(request, response);
      }



    }

    private RequestProcessor getRequestProcessor() {
         RequestProcessor rp = (RequestProcessor)context.getAttribute(WebKeys.REQUEST_PROCESSOR);
         if ( rp == null ) {
             rp = new RequestProcessor();
             rp.init(context);
             context.setAttribute(WebKeys.REQUEST_PROCESSOR, rp);
        }
       return rp;
    }

    private ScreenFlowManager getScreenFlowManager() {
            ScreenFlowManager screenManager = (ScreenFlowManager)context.getAttribute(WebKeys.SCREEN_FLOW_MANAGER);
            if (screenManager == null ) {
                screenManager = new ScreenFlowManager();
                screenManager.init(context);
                context.setAttribute(WebKeys.SCREEN_FLOW_MANAGER, screenManager);
             }
        return screenManager;
    }

    /**
     * The UrlMapping object contains information that will match
     * a url to a mapping object that contains information about
     * the current screen, the HTMLAction that is needed to
     * process a request, and the HTMLAction that is needed
     * to insure that the propper screen is displayed.
    */

    private URLMapping getURLMapping(String urlPattern) {
        if ((urlMappings != null) && urlMappings.containsKey(urlPattern)) {
            return (URLMapping)urlMappings.get(urlPattern);
        } else {
            return null;
        }
    }
}





        //读取Hibernate.cfg.xml配置文件,并读到内存中为后续操作作准备 
        Configuration config = new Configuration().configure(); 
        //SessionFactory缓存了生成的SQL语句和Hibernate在运行时使用的映射元数据。 
        SessionFactory sessionFactory = config.buildSessionFactory(); 
        //Session是持久层操作的基础,相当于JDBC中的Connection。 
        Session session = sessionFactory.openSession(); 

        try{  
//为保持事务的原子性,必须捕捉异常。所有事务都放在这一代码块里。 
            //操作事务时(增、删、改)必须显式的调用Transaction(默认:autoCommit=false)。 
            Transaction tx = session.beginTransaction(); 
            for(int i=0; i<=1000; i++){ 
              Student stu = new Student(...); 
              session.save(stu);//set value to stu 
              //批量更新:为防止内存不足,分成每20个一批发送过去。  
              if(i%20==0){session.flush();session.clear();}//不是大批量更新,则不需要写这一行 
              //默认时,会自动flush:查询之前、提交时。 
            } tx.commit();//提交事务,Hibernate不喜欢抛异常,如有需要,自己捕捉。 

            //查询方法。如果有必要,也可以用事务(调用Transaction)  
            String hql = "from Student s where s.stuNo like ? and s.Sal > ?";//Student是类而不是表 
            List list = session.createQuery(hql) 
                               .setString(0, "a00_").setDouble(1, 3000.0)//设置HQL的第一二个问号取值 
                               .list();//Hibernate里面,没有返回值的都默认返回List 
            StringBuffer sb = new StringBuffer(); 
            for(Student st :(List<Student>)list){//(List<Student>)强制类型转换 
              sb.append(st.getOid()+"  "+st.getName()+"\n");//拿到Student类里的属性 
            }System.out.print(sb.toString());//直接打印sb也可以,它也是调用toString,但这样写效率更高 
        } catch (HibernateException e) { 
            e.printStackTrace(); 
            session.getTransaction().rollback();//如果事务不成功,则rollback 
        } finally { 
            session.close();//注意关闭顺序,session先关,Factory最后关(因为它可以启动多个session)  
            sessionFactory.close();//关闭SessionFactory,虽然这里没看到它,但在HbnUtil里开启了。 
        } 

你可能感兴趣的:(sql,Web,Hibernate,servlet,sun)