ssm 电商笔记

jersey demo

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
public class jerseyDemo
{

public static void main(String[] args) throws IOException
{
Client client=new Client();
String URL="http://localhost:8088/UploadImg/upload/test.jpg";
String path="D:\\img_man\\image\\001\\021_001_201309061050001.jpg";

byte[] readFileToByteArray = FileUtils.readFileToByteArray(new File(path));

WebResource resource = client.resource(URL);

resource.put(String.class, readFileToByteArray);

System.out.println("发送完毕");
}
}

需要以下三个包

jersey-client-1.18.1.jar
jersey-core-1.18.1.jar

commons-io-1.3.2.jar


ajax上传图片到图片服务器

<script type="text/javascript">
  function uploadfile()
  { 	  
	 
	var options = {
			url : "/upload/uploadPic.do",
			dataType : 'json',
			type : "post",
			success : function(data) {
				// 'data' is an object representing the the evaluated json data 
				// 如果图片上传成功则保存表单注册数据 				
					$("#allImgUrl").attr("src",data.url);
					$("#imgUrlPath").val(data.path);
			}
		};

		$('#jvForm').ajaxSubmit(options)

	}
</script><span style="font-family: Arial, Helvetica, sans-serif;">     </span>
<pre name="code" class="html">                <form id="jvForm" action="add.do" method="post"
			enctype="multipart/form-data">
<table>
      <tr>
						<td width="20%" class="pn-flabel pn-flabel-h"></td>
						<td width="80%" class="pn-fcontent">
						<img width="100" height="100" id="allImgUrl" /> 
						<input type="hidden" id="imgUrlPath" name="imgUrl"></input>
						<input type="file" name="pic" οnchange="uploadfile()"/>
						</td>
					</tr>
	</table>
		</form>

 
</pre><pre name="code" class="html">import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


import javax.servlet.http.HttpServletResponse;


import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import cn.qht.common.Utils.ResponseUtils;

import com.sun.jersey.api.client.Client;

import com.sun.jersey.api.client.WebResource;

@Controller
public class UploadController
{
	@RequestMapping(value="/upload/uploadPic.do")
    public void UploadPic(@RequestParam(required=false) MultipartFile pic,HttpServletResponse response)
    {
		DateFormat df=new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String format = df.format(new Date());
    

    	String randomAlphanumeric = RandomStringUtils.randomAlphanumeric(3);
    	
    	String ext = FilenameUtils.getExtension(pic.getOriginalFilename());
    	
    	String path="/upload/"+format+randomAlphanumeric+"."+ext;
    	
    	String fullURLPath="http://localhost:8088/UploadImg"+path;
    	
    	Client client=new Client();
    	WebResource resource = client.resource(fullURLPath);
		try
		{
			resource.put(String.class, pic.getBytes());
			JSONObject jsObject = new JSONObject();
			jsObject.append("url", fullURLPath);
			jsObject.append("path", path);
			ResponseUtils.renderJson(response, jsObject.toString());
		}
		catch (IOException e)
		{
			
			e.printStackTrace();
		}
    	
    }
	
}

ResponseUtils

package cn.qht.common.Utils;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

public class ResponseUtils
{
	public static void render(HttpServletResponse response,String ContentType,String Content)
	{
		try
		{
			response.setContentType(ContentType);
			response.getWriter().write( Content);
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void renderJson(HttpServletResponse response,String Content)
	{
		String ContentType="application/json;charset=UTF-8";
		render(response, ContentType, Content);
	}
	public static void renderXML(HttpServletResponse response,String Content)
	{
		String ContentType="text/xml;charset=UTF-8";
		render(response, ContentType, Content);
	}
	public static void renderText(HttpServletResponse response,String Content)
	{
		String ContentType="text/plain;charset=UTF-8";
		render(response, ContentType, Content);
	}
}

js函数调用时字符串需要在变量前加''

例如

οnclick="optDelete('${name}',${isDispaly});"


 function optDelete(name,isDispaly)
       {
    	 
    	var size= $("input[name='ids']:[checked]").length ;
    	if(size<=0)
    	{
    		alert("请至少选择一个");
    		return;
    	}
    	
    	  $("#jvform").attr("action","deleteIds.do?name="+name+"&isDisplay="+isDispaly);
    	  $("#jvform").attr("method","post").submit();
         }
      
         </script>


		<div style="margin-top:15px;"><input class="del-button" type="button" value="删除" οnclick="optDelete('${name}',${isDispaly});"/></div>

mybatis foreach 总结

dao中接口的参数维数组

例如  public void deletes(Integer [] ids)

<foreach collection="array" >foreach标签的collection 中填array

若dao接口中参数为对象,对象中包含一个数组

例如 public void deletes(User user)

 Class user

 private  Integer [] ids;

}

<foreach collection="ids" >foreach标签的collection 中填ids

getsession().getId() 与 getRequestSessionId()的差异

HttpServletRequest.getSession().getId()是服务器端的概念

HttpServletRequest.getRequestedSessionId()是客户端就是浏览器的概念,getRequestedSessionId()获取的是在url上传递的id例如http://localhost:8080/ssw.shtml?JESSIONID=wrs12dssdw9283


JSP页面静态化

1. 

StaticPageImpl类

package cn.qht.core.service.Freemarker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class StaticPageImpl implements StaticPage,ServletContextAware
{
    private Configuration con;
    
    private FreeMarkerConfigurer freeMarkerConfigurer;

/*	public FreeMarkerConfigurer getFreeMarkerConfigurer()
	{
		con=freeMarkerConfigurer.getConfiguration();
		return freeMarkerConfigurer;
	}
    */
	public void StaticProductPage(Map<String, Object> rootMap,Integer productId)
	{
		Writer out=null;
		try
		{
			String path=getRealPath("/html/product/"+productId+".html");
			File file=new File(path);
			File parentPathFile=file.getParentFile();
			if(!parentPathFile.exists())
			{
				parentPathFile.mkdir();
			}
			out=new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
			
			Template template = con.getTemplate("productDetail.html");
			template.process(rootMap, out); 
		} catch (Exception e)	
		{			
			e.printStackTrace();
		}
		finally
		{
			if(out!=null)
			{
				try
				{
					out.close();
				} catch (IOException e)
				{					
					e.printStackTrace();
				}
			}
		}
	}

	public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer)
	{
		con=freeMarkerConfigurer.getConfiguration();
	}

	public String getRealPath(String path)
	{
		return servletContext.getRealPath(path);
	}
	public ServletContext servletContext;
	@Override
	public void setServletContext(ServletContext servletContext)
	{
		this.servletContext=servletContext;
		
	}
}



2.创建freemarker.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    
    <bean id="staticPage" class="cn.qht.core.service.Freemarker.StaticPageImpl">
      <property name="freeMarkerConfigurer" >
         <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
            <property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
            <property name="defaultEncoding" value="UTF-8"/>
         </bean>
      </property>
    </bean>
	
</beans>

springMVC拦截器

配置映射器和适配器

<!-- 映射器 -->
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
		<property name="interceptors">
			<list>
				<bean class="cn.qht.core.web.SpringmvcInterceptor">
				
				</bean>
			</list>
		</property>
	</bean>
	<!-- 适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
拦截器
package cn.qht.core.web;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.qht.common.Utils.Web.SessionProvider;
import cn.qht.core.domain.user.Buyer;


public class SpringmvcInterceptor implements HandlerInterceptor
{
	@Autowired
	private SessionProvider sessionProvider;
	
	private Integer adminId;
	//常量
	private static final String INTERCEPTOR_URL = "/buyer/";

	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception
	{
		boolean isLogin=false;
		Buyer buyer = (Buyer)sessionProvider.getAttribute(request, Constants.BUYER_SESSION);
		if(buyer==null)
		{			
			String Uri = request.getRequestURI();
			if(Uri.startsWith(INTERCEPTOR_URL))
			{
				response.sendRedirect("/shopping/login.jsp?returnUrl="+request.getRequestURL());
				return false;
			}
		}
		else {
			isLogin=true;
		}
		request.setAttribute("isLogin", isLogin);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception
	{
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception
	{
		// TODO Auto-generated method stub
		
	}
	public Integer getAdminId()
	{
		return adminId;
	}

	public void setAdminId(Integer adminId)
	{
		this.adminId = adminId;
	}

}

设置select的值,省市县联动

 function  changeProvince(value)
 {
	 var url="/buyer/getCity.shtml";
	 var params={"province":value};	
	 var html="<option value='' selected>省/直辖市</option>";
	 $.post(url,params,function(data){
		     var citys=data.citys;
		 	for(var i=0;i<citys.length;i++)
		 	{  
		 		html+="<option value="+citys[i].code+" selected>"+citys[i].name+"</option>";
			}
		 	$("#city").html(html);
                        //设置选中value为""的项
		 	 $("#city").val("");
			$("#town").html("<option value='' selected>县/区</option>");
	 },			 
	 "json");
 }

<select name="province"  id="province" οnchange="changeProvince(this.value)">
								<option value="" selected>省/直辖市</option>
								<c:forEach items="${provinces}" var="province">
								    <option value="${province.code}" <c:if test="${buyer.province==province.code}">selected="selected"</c:if> >${province.name}</option>
								</c:forEach>
							</select>


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值