这次由两人共同实现完成做到通过使用微信小程序的api来获取微信用户的唯一标识,在把唯一标识上传到服务器的数据库中,如果是第一次登陆服务器会返回第一次登陆上传到数据库,如果不是第一次登陆服务器会返回数据库已有用户到前台。这次是使用了完整的ssh框架。另一位小伙伴的CSDN地址https://blog.csdn.net/xk4500,我们都是大四学生,因为一个项目的需要所以做了这个基于ssh框架与微信小程序进行通信,如有不足,欢迎指出。
项目环境(Tomcat8.5+myeclipse2016 ci)
一、ssh框架所以需要的包
二、user,pojo类
//用户pojo
package com.wx.pojo;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "tbs_user")
public class User {
private int user_id;
private String wx_id;
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name = "id")
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
@Column(name = "wx")
public String getWx_id() {
return wx_id;
}
public void setWx_id(String wx_id) {
this.wx_id = wx_id;
}
public User(int user_id, String wx_id) {
super();
this.user_id = user_id;
this.wx_id = wx_id;
}
public User() {
super();
}
}
三、dao层代码
1.UserDao,java
package com.wx.dao;
import com.wx.pojo.User;
public interface UserDao {
User selectByWxid(User user);
int sava(User user);
}
2.UserDaoImp.java
package com.wx.dao;
import com.wx.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
@Repository
@Transactional
public class UserDaoImp implements UserDao{
@Autowired
private HibernateTemplate hibernateTemplate;
@Override
public User selectByWxid(User user) {
String hql="from User user where user.wx_id=?";
List<User> find = (List<User>) hibernateTemplate.find(hql, user.getWx_id());
if (find.size()==0){
return null;
}else {
return find.get(0);
}
}
@Override
public int sava(User user) {
Serializable row = hibernateTemplate.save(user);
return (int) row;
}
}
四、service层代码
1.UserService.java
package com.wx.Server;
import com.wx.pojo.User;
public interface UserService {
public String sava(User user);
}
2.UserServiceImp.java
package com.wx.Server;
import com.wx.dao.UserDao;
import com.wx.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@Service
public class UserServiceImp implements UserService {
@Autowired
private UserDao userDao;
public String sava(User user){
User selectByWxid = userDao.selectByWxid(user);
if (selectByWxid==null){
userDao.sava(user);
return "success";
}else {
return "input";
}
}
}
五、action代码
package com.wx.Action;
import com.wx.Server.UserService;
import com.wx.pojo.JsonResult;
import com.wx.pojo.User;
import org.apache.struts2.interceptor.RequestAware;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
@Controller
public class UserAction implements RequestAware {
private User user;
@Resource(name = "userServiceImp")
private UserService userService;
private Map<String, Object> request;
private JsonResult jsonResult;
Logger log = Logger.getLogger(this.getClass().getName());
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public JsonResult getJsonResult() {
return jsonResult;
}
public void setJsonResult(JsonResult jsonResult) {
this.jsonResult = jsonResult;
}
public String login(){
jsonResult = new JsonResult();
WebApplicationContext context = ContextLoaderListener.getCurrentWebApplicationContext();
log.info("user_____________"+user+"userServer_____________"+userService);
log.info("context:---"+context.getBeansWithAnnotation(Service.class));
userService = (UserService) context.getBeansWithAnnotation(Service.class).get("userServiceImp");
String login_msg=userService.sava(user);
if (login_msg.equals("success")){
jsonResult.setResult(login_msg+"第一次登陆上传到数据库");
}else {
jsonResult.setResult(login_msg+"数据库已有用户");
}
Map map = new HashMap<String, Object>();
map.put("user", user);
jsonResult.setMsg(map);
return "success";
}
@Override
public void setRequest(Map<String, Object> map) {
request=map;
}
}
六、微信前端代码
1.js代码
// pages/gerenyemian/grym.js
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function () {
wx.setNavigationBarTitle({
title: '个人中心',
})
wx.login({
success: function(res) {
var code = res.code //返回code
var appid = '自己的微信qppid';
var AppSecret = '自己的AppSecret';
console.log(code);
//发起网络请求
wx.request({
url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + AppSecret + '&js_code=' + code + '&grant_type=authorization_code',
data: {},
header: {
'content-type': 'application/json'
},
success: function (res) {
var openId = res.data.openid //返回openid
console.log(openId);
wx.request({
url: 'http://localhost:8080/wxserver/login.action',
data: {
'user.wx_id': openId,
},
header: {
'content-type': 'application/json' // 默认值
},
method: 'GET',
dataType: 'json',
responseType: 'text',
success: function (res) {
console.log(res.data);
},
fail: function (res) {
console.log("连接失败");
}
})
}
})
}
})
}
七、spring的配置文件
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"
>
<!--扫描spring注解 package为包的名字-->
<context:annotation-config/>
<context:component-scan base-package="com.wx"></context:component-scan>
<!--注入数据源-->
<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql:///wx?useUnicode=true&characterEncoding=UTF8" />
<property name="username" value="root" />
<property name="password" value="admin" />
</bean>
<!--注入sessionFactory-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<!--定义方言-->
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</prop>
<!--在控制台显示sql语句-->
<prop key="hibernate.show_sql">true</prop>
<!--定义为每次重启自动更新数据-->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!--session绑定-->
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>
</props>
</property>
<!--扫描hibernate注解-->
<property name="packagesToScan">
<list>
<value>com.wx.pojo</value>
</list>
</property>
</bean>
<!--注入hibernateTemplate-->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 事务管理器配置, Hibernate单数据源事务 -->
<bean id="defaultTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 使用annotation定义事务 -->
<tx:annotation-driven transaction-manager="defaultTransactionManager" proxy-target-class="true" />
</beans>
八、struts.xml文件(用于配置action)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default,json-default">
<action name="login" class="com.wx.Action.UserAction" method="login">
<result name="success" type="json">
<param name="root">jsonResult</param>
</result>
</action>
</package>
</struts>
九、web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml</param-value>
</context-param>
</web-app>
十、最终效果
第一次登陆
第二次登陆