servlet实战

1.servlet工作模式:

  • 客户端发送请求至服务器
  • 服务器启动并调用Servlet,Servlet根据客户端请求生成响应内容并将其传给服务器
  • 服务器将响应返回客户端

 

2. 在html 界面中,要是没有设定提交的方法,默认以doGet的方法进行处理。servlet有两种处理客户请求的方法,分别是doGet和doPost: 

      (1). 如果客户以get方法请求,请求的参数会以名值对的形式显示在浏览器的地址栏,请求发送的数据,不能大于1024K,在服务器端的servlet中,必须以doGet方法接收 
      (2).如果是客户以post方法请求,请求的参数不会显示在地址栏,请求的发送的数据可以是无限大,例如上传文件时,肯定是post方法,在服务器端的servlet中,就必须以doPost方法接收。

   

 

3.init()方法可用于初始化加载service服务。

   

    servlet里的init代码:

/**
	 * 初始化servlet注入service
	 */
	public void init(ServletConfig servletConfig) throws ServletException {
		//把webApplicationContext的service服务向servlet传递
	    ServletContext servletContext = servletConfig.getServletContext(); //ServletContext为servlet-api.jar包
	    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);//WebApplicationContext为spring组件
	    providerFacade = (ProviderFacade)ctx.getBean("providerFacade");//根据id加载providerFacade服务
	    packageProductLineFacade = (PackageProductLineFacade)ctx.getBean("packageProductLineFacade");
	}

   

   spring配置文件:

   

<bean id="providerFacade" parent="baseTransactionProxy" abstract="false" lazy-init="default" autowire="default" dependency-check="default">
        <property name="target">
            <bean class="com.mangocity.api.facade.impl.ProviderFacadeImpl" parent="facade" abstract="false" lazy-init="default" autowire="default" dependency-check="default">
                <property name="providerDAO">
                    <ref bean="providerDAO"/>
                </property>
            </bean>
        </property>
    </bean>

 

 

4.servlet根据参数分派给不同的方法处理--相当于struts分派不同的action

   例如两请求如下:1. var QUERYURL="providerProductServlet?method=query&providerCD="+providerCD+"&data="+data;

                               2.var QUERYURL="providerProductServlet?method=delete&providerCD="+providerCD+"&data="+data;

   则在servlet中处理可如下:

   

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		request.getParameter("name");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		if(request.getParameter("method").equals("query"))//再分别编写pagingQueryProduct以及deleteProduct方法
		{
			pagingQueryProduct(request, response);
		}
		if(request.getParameter("method").equals("delete"))
		{
			deleteProduct(request, response);
		}
	}

    

	/**
	 * 删除单个产品
	 * @param request
	 * @param response
	 */
	private void deleteProduct(HttpServletRequest request, HttpServletResponse response) {
		long lineId = Long.valueOf(request.getParameter("lineId"));
		PackageProductLine productLine = (PackageProductLine) packageProductLineFacade.find(lineId);
		productLine.setStatus("N");
		packageProductLineFacade.saveProductlineInfo(productLine);
		try {
			pagingQueryProduct(request, response);
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("删除id为:" + productLine.getId());
	}
	
	/**
	 * 分页查询产品
	 * @param request
	 * @param response
	 */
	private void pagingQueryProduct(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		int pageNum = 1; 
		int pageSize = 10;
		String data = request.getParameter("data");
		String providercd = (String) request.getSession().getAttribute("providerCD");
		if(providercd == null || "".equals(providercd))
		{
			providercd = request.getParameter("providerCD");
			request.getSession().setAttribute("providerCD", providercd);
		}
		Map map = (HashMap) JSONObject.toBean(JSONObject.fromObject(data),HashMap.class);
		if(providercd != null && !"".equals(providercd))
		{
			if(map != null && !"".equals(map))
			{
				pageNum = Integer.valueOf(map.get("pageNum").toString());
				pageSize = Integer.valueOf(map.get("pageSize").toString());
			}
		}
		if (map != null && map.size() > 0)
		{
			if (map.containsKey("id"))
			{
				String id = (String)map.get("id");
				
				if (null != id && !id.equals("")) {
					if(!isNumeric(id)) {
						map.put("id", "0");
					} 
				}
			}
			if (map.containsKey("name"))
			{
				String name =  (String)map.get("name");
				if (name != null && "产品名称".equals(name.trim()))
				//if (name != null && "产品名称".equals(new String(name.trim().getBytes("ISO8859-1"), "GBK")))
				{
					map.put("name", null);
				}
			}
		}
		PageModel model = packageProductLineFacade.pagingQueryProduct(providercd, map, pageNum, pageSize);
		
		JsonConfig config = new JsonConfig();
		config.setExcludes(new String[]{"pageModel", "hibernateLazyInitializer","handler","tProvince"});
		String page = JSONObject.fromObject(model,config).toString();
		String jsonpCallback = request.getParameter("jsonpCallback");
		out.println(jsonpCallback+"("+page.toString()+")");
		/*out.flush();*/
		out.close();
	}

   注:// 解决延迟加载产生异常的问题

             JsonConfig config = new JsonConfig();

             config.setExcludes(new String[]{"pageModel", "hibernateLazyInitializer","handler","tProvince"});

             String page = JSONObject.fromObject(model,config).toString();

 

 

5.web.xml映射

   

<servlet>
    <servlet-name>providerProductServlet</servlet-name>
    <servlet-class>*.*.*.*.ProviderProductServlet</servlet-class>
  </servlet>

<servlet-name>providerProductServlet</servlet-name>
    <url-pattern>/providerProductServlet</url-pattern>
  </servlet-mapping>

 

 

 

 

 

你可能感兴趣的:(servlet)