spring mvc /ibetis/jquery 項目結構

1.項目結構如下


2. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>custSys wechat</display-name>




    <!--加載spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- spring容器監聽 初始化數據 -->
<listener>
<description>Initialize the Application Scope Data</description>
<display-name>ApplicationInitializer</display-name>
<listener-class>com.hj.custsys.wechat.util.Initializer</listener-class>
</listener>
<!-- 日誌 -->
<context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.properties</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
    <!-- 配置spring mvc -->
<servlet>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath:servletContext.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <url-pattern>*.json</url-pattern>
    </servlet-mapping>
    <!-- 處理亂碼 -->
     <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
     <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
       <jsp-config>
        <taglib>
            <taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
            <taglib-location>/WEB-INF/c.tld</taglib-location>
        </taglib>
    </jsp-config>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

3.applicationContent.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" 
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
">
<!-- datasource -->
<context:property-placeholder location="classpath:jdbc.properties"
ignore-unresolvable="true" />
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource">
<property name="driverClass" value="${jdbc.driver.class}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="idleConnectionTestPeriodInMinutes" value="60" />
<property name="idleMaxAgeInMinutes" value="60" />
<property name="maxConnectionsPerPartition" value="10" />
<property name="minConnectionsPerPartition" value="5" />
<property name="partitionCount" value="1" />
<property name="acquireIncrement" value="5" />
<property name="statementsCacheSize" value="100" />
<property name="releaseHelperThreads" value="3" />
<property name="logStatementsEnabled" value="true" />
</bean>
<!-- 配置 sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 加載mybatis全局配置 -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="mapperLocations">
<array>
<value>classpath:com/hj/custsys/wechat/dao/*/*.xml</value>
</array>
</property>
</bean>
<!-- 配置 Mapper掃描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<property name="basePackage" value="com.hj.custsys.wechat.dao" />
</bean>
<!-- 掃描service組件 -->
<context:component-scan base-package="com.hj.custsys.wechat">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- 事務管理器 -->
    <bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 添加aspectj自動代理支持 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
<!--  -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

4.servletContext.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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.hj.custsys.wechat.controller" />


 <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
                <property name="features">
                    <array>
                        <value>WriteMapNullValue</value>
                        <value>WriteNullStringAsEmpty</value>
<value>DisableCircularReferenceDetect</value>
</array>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <bean id="DisableCircularReferenceDetect" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
<property name="staticField" value="com.alibaba.fastjson.serializer.SerializerFeature.DisableCircularReferenceDetect"></property>
</bean>


<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/wechat/"/>
<property name="suffix" value=".jsp"/>
</bean>

<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8"
p:maxUploadSize="52428800"
p:maxInMemorySize="10240"/>
</beans>
5.mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias type="java.lang.Integer" alias="int" />
        <typeAlias type="java.lang.String" alias="String" />
        <typeAlias type="java.util.LinkedHashMap" alias="linkMap" />
    </typeAliases>
</configuration>

6. Controller

package com.hj.custsys.wechat.controller;


import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


import javax.servlet.http.HttpServletRequest;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


import com.hj.custsys.wechat.entity.Customer;
import com.hj.custsys.wechat.entity.ReceiptInfo;
import com.hj.custsys.wechat.service.CustomerService;
import com.hj.custsys.wechat.service.ReceiptInfoService;
import com.hj.custsys.wechat.util.Constants;
import com.hj.custsys.wechat.util.KeyUtils;
/*
 * 
 * 二維碼購買頁面
 */
@Controller
@RequestMapping("order")
public class OrderController extends WechatBaseController{
private Map<String, Object> resultMap = new ConcurrentHashMap<>();
@Autowired
private CustomerService customerService;
@Autowired
private ReceiptInfoService receiptInfoService;

/**

* @return 跳轉到授權頁面
*/
@RequestMapping("get_oauth_page_url.html")
public String  getOauthPageUrl(){
String getCodeUrl = Constants.GET_CODE_URL;
getCodeUrl=getCodeUrl.replace("APPID", Constants.APPID);
getCodeUrl=getCodeUrl.replace("REDIRECT_URI", Constants.REDIRECT_URI);
System.out.println("getCodeURL::"+getCodeUrl);
//String str = "http://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=https%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
       return "redirect:"+getCodeUrl;
      
}
/**
* 通過code獲取openId
* -openId已存在,跳轉到購買確認頁面
* -openId不存在,跳轉到手機綁定頁面
* @param request
* @return
*/
@RequestMapping("wechat_oauth2.html")
public ModelAndView wechatOauth2(){
//String code = request.getParameter("code");
String code="123";
   String oauth2URL = Constants.GET_OPENID_URL;
   oauth2URL=oauth2URL.replace("APPID", Constants.APPID);
   oauth2URL=oauth2URL.replace("APPSECRET", Constants.APPSECRET);
   oauth2URL=oauth2URL.replace("CODE", code);
       System.out.println("oauth2URL::"+oauth2URL);
/*        String authResponseJsonStr=HttpUtil.getUrl(oauth2URL);
       System.out.println("authResponseJsonStr::"+authResponseJsonStr);
       JSONObject responseJsonObject=JSONObject.parseObject(authResponseJsonStr);
       String openId = responseJsonObject.getString("openId"); */  
       String openId="111";
       Customer customer = customerService.loadCustomerByOpenId(openId); 
        getSession().setAttribute("companyId", 115);
       if(customer==null){          
        modelAndView.setViewName("register");
       }else{        
        getSession().setAttribute("phone", customer.getPhone());
        getSession().setAttribute("customerId", customer.getId());
        //購買確認頁面        
        super.modelAndView.setViewName("forward:/order/get_receipt_info.html");
       }
return modelAndView;
}
/**
* 調用第三方接口,獲取驗證碼
*/
@RequestMapping("send_verify_code.html")
@ResponseBody
public Object sendVerifyCode(String phone){
resultMap.clear();
System.out.println(phone);
//調用第三方接口
try{
String verifyCode = "1";
resultMap.put("result", true);
resultMap.put("verifyCode", verifyCode);
System.out.println(verifyCode);
}catch(Exception e){
resultMap.put("result",false);
}
return resultMap;
}
/**
* 用戶綁定頁面提交
* - update the user if the phone is exist
* - otherwise update only
* @param phone
* @return
*/
@RequestMapping("save_customer.html")
@ResponseBody
public Object saveCustomer(String phone){
resultMap.clear();
Integer companyId = Integer.valueOf(getSession().getAttribute("companyId").toString());
String openId="123";
try{
Customer customer = customerService.loadCustomerByPhone(phone);
getSession().setAttribute("phone", phone);
if(customer ==null){//insert
Customer customerInsert = new Customer();
customerInsert.setId(KeyUtils.getUUID());
customerInsert.setOpenId(openId);
customerInsert.setPhone(phone);   
customerInsert.setCreateDate(new Date());
customerInsert.setEntryCompanyId(companyId);
customerService.saveCustomer(customerInsert);
getSession().setAttribute("customerId", customerInsert.getId());
resultMap.put("result", true);
resultMap.put("method", "insert");
}else{//update
customer.setOpenId(openId);
customer.setEditDate(new Date());
customerService.updateCustomer(customer);
getSession().setAttribute("customerId", customer.getId());  
resultMap.put("result", true);
resultMap.put("method", "update");
}
}catch(Exception e){
resultMap.put("result", false);
}
//購買確認頁面
return resultMap;
}

/**
* 進入訂單確認前查詢收貨信息
* @return
*/
@RequestMapping("get_receipt_info.html")
public ModelAndView getReceiptInfo(){
String phone = getSession().getAttribute("phone").toString();
Integer companyId = Integer.valueOf(getSession().getAttribute("companyId").toString());
String customerId = getSession().getAttribute("customerId").toString();
List<ReceiptInfo> receipts = receiptInfoService.loadReceipt(companyId, customerId);
modelAndView.addObject("receipts", receipts);
modelAndView.addObject("customerId", customerId);
modelAndView.addObject("companyId",companyId);
modelAndView.addObject("phone",phone);
modelAndView.addObject("productId",1);
modelAndView.addObject("price",200);
modelAndView.addObject("count",10);
modelAndView.addObject("freight",10);
modelAndView.setViewName("orderConfirm");
return modelAndView;
}
@RequestMapping("submit_order.html")
@ResponseBody
public Object submitOrder(){
resultMap.clear();



return resultMap;
}
}
7. daomapping.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hj.custsys.wechat.dao.ReceiptInfoDao" >
  <resultMap id="receiptInfo" type="com.hj.custsys.wechat.entity.ReceiptInfo" >
     <id column="id" property="id" />
     <result column="receipt_name" property="receiptName"/>
     <result column="address" property="address"/>
     <result column="customer_id" property="customerId"/>
     <result column="postcode" property="postcode"/>
     <result column="contact_no" property="contactNo"/>
     <result column="create_date" property="createDate"/>
     <result column="is_default" property="isDefault"/>
     <result column="is_delete" property="isDelete"/>
  </resultMap> 
  <!-- 通過customerId查詢收貨地址 -->
  <select id="selectByCustomerId" resultMap="receiptInfo">
        select * from fnt_${companyId}_receiptInfo where customer_id=#{customerId}
    </select> 
  <!-- 刪除收貨地址 -->
  <!-- 保存收貨地址 -->
      <!-- 修改收貨地址 -->
</mapper>

8.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="yes" name="apple-mobile-web-app-capable">
<meta content="yes" name="apple-touch-fullscreen">
<meta content="telephone=no" name="format-detection">
<meta content="black" name="apple-mobile-web-app-status-bar-style">
<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1;user-scalable=no;">
<link rel="stylesheet" href="../css/bootstrap.css">
<link rel="stylesheet" href="../css/custSysWechat.css">
 <script type="text/javascript" src="../js/jquery.min.js"></script>
 <script type="text/javascript" src="../js/jquery.form.js" ></script>
<title>訂單確認</title>
</head>
<body>
<div class="maincontainer">
<div class="nav">
<a class="nav-left back-icon" href="javascript:history.back();">返回</a>
<p class="text-center tit">訂單確認</p>
</div>
<div class="container">
<div class="receiverContainer">
<div class="container itemdetail mini-innner">
      <div class="row">
         <div class="col-md-12 tal mt20">          
             <div class="input-group input-group-lg">  
                  <span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span>            
                  <select name="receipt" id="receipt" class="form-control ">
                  <c:forEach items="${receipts}" var="receipt">
<option value=${receipt.id} <c:if test='${receipt.isDefault == 1}'>selected="selected"</c:if>>
${receipt.receiptName}&nbsp;${receipt.contactNo}&nbsp;${receipt.address}</option>
</c:forEach>  
    </select>      
              </div>
              <br>
<div class="input-group input-group-lg">  
                  <span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span>  
                     <select name="deliveryTime" id="address" class="form-control" data-style="btn-primary">
<option value="whenever">時間不限</option>
<option value="workday">週一至週五</option>
<option value="holiday">週末及公衆假期</option>
  </select>
              </div>


</div>
</div>
</div>
<div class = "orderDetailContainer">
<div class="titleBackground"> <h3 style="align:center">訂單詳情</h3></div>
<div class = "productDetail">  
<span>1.艾爾麗斯背背褲</span><span>¥${price}</span> <span>X${count}</span>

</div>
<br>
<textarea rows="3" cols="50" style="width:400px;align:center">
備註
</textarea>
</div>
<div class="confirmInfoContainer">
<p><span class="titleLabel">商品金額:</span><span class="valueLabel">¥${price}</span></p>
<p><span class="titleLabel">運費金額:</span><span class="valueLabel">¥${freight} </span></p>
<p><span class="titleLabel">應付總額:</span><span class="valueLabel">¥${price+freight }</span></p>
</div>
<button type="button" class="btn btn-info btn-block " οnclick="submitOrder();" style="margin-top:10px" >提交訂單</button> 
</div>
</div>

</body>
<script>
function submitOrder(){
$.ajax({
type:"post",
  dataType:"json",
url:"save_customer.html",
data:{
  phone:$("#phone").val(),
 },
 success:function(resp){
 


 },
 error:function(resp){
 
  console.log("register error...");
 }
 });
}
</script>
</html>
9.serviceImp

package com.hj.custsys.wechat.service.impl;


import javax.annotation.Resource;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.hj.custsys.wechat.dao.CustomerDao;
import com.hj.custsys.wechat.entity.Customer;
import com.hj.custsys.wechat.service.CustomerService;
@Service("CustomerService") 
public class CustomerServiceImp implements CustomerService {
@Resource
private CustomerDao customerDao;


public Customer loadCustomerByOpenId(String openId) {
return customerDao.selectCustomerByOpenId(openId);
}


@Override
public Customer loadCustomerByPhone(String phone) {
return customerDao.selectCustomerByPhone(phone);
}


@Override
public boolean saveCustomer(Customer customer) {
return customerDao.insertCustomer(customer);
}

@Override
public boolean updateCustomer(Customer customer) {
return customerDao.updateCustomer(customer);
}




}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章