ホームページ php教程 PHP开发 springmvc は jfinal WeChat WeChat サービス アカウント開発を統合します

springmvc は jfinal WeChat WeChat サービス アカウント開発を統合します

Nov 22, 2016 pm 01:17 PM
springmvc

最近、WeChat サービス アカウントの開発について調べたところ、jfinal によってパッケージ化された SDK が非常に優れていることがわかったので、それを使用することにしました。

そこで質問は、git にはデモがあるのですが、それを自分のプロジェクトにどのように統合するかということです。ただ勉強して勉強してください。私たちのフレームワークは springmvc を使用しています。統合方法と発生したいくつかの問題を記録しましょう:

1. プロジェクトでは、まず jfinal WeChat に必要な jar パッケージと jfinal の SDK パッケージを参照する必要があります。

2. web.xml で jfinal 関連の設定を開始するように設定します (すべてのインターセプターの上に配置する必要があります)

	<filter>
		<filter-name>jfinal</filter-name>
		<filter-class>com.jfinal.core.JFinalFilter</filter-class>
		<init-param>
			<param-name>configClass</param-name>
			<param-value>com.jfinal.weixin.demo.WeixinConfig</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>jfinal</filter-name>
		<url-pattern>/weixin/*</url-pattern>
	</filter-mapping>
ログイン後にコピー

3. クラス WeixinMsgController を継承して、メッセージ受信機能を実現するメソッドを書き換えます

4.ここについては

WeChatリクエストをインターセプトするインターセプターを自分で書く

<bean id="methodInvokerIntercepterManager"
		class="org.springframework.web.servlet.mvc.annotation.MethodInvokerIntercepterManager">
		<property name="intercepters">
			<list>
				<bean class="com.xtwl.reporter.weixin.NeedOpenId"></bean><!-- 处理是否微信认证 -->
				<bean class="com.xtwl.framework.security.utils.MethodPrivilegeIntercepter">
				<property name="loginPage" value="/workspace/login" />
                <property name="noauthPage" value="global/error/401.ftl" />
				<property name="rejectMessage" value="您无权访问" />
				<property name="loginPrompt" value="请先登录" />
				</bean>
			</list>
		</property>
	</bean>
ログイン後にコピー

クラスOpenidをアノテーションとして記述し、それを使用して

package com.xtwl.reporter.weixin;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//检查是否需要登录
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Openid {

}
ログイン後にコピー

NeedOpenIdにログインしているかどうかを確認します(メソッドに上記のアノテーションがあるかどうかを確認してWeChatを実行します)そうであれば検証してください)

package com.xtwl.reporter.weixin;import java.lang.reflect.Method;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.ui.Model;import org.springframework.web.servlet.mvc.annotation.IMethodIntercepterHolder;import org.springframework.web.servlet.mvc.annotation.IMethodInvokerIntercepter;import com.jfinal.kit.PropKit;import com.jfinal.weixin.sdk.api.ApiConfig;import com.jfinal.weixin.sdk.api.ApiConfigKit;import com.jfinal.weixin.sdk.api.SnsAccessToken;import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;import com.xtwl.reporter.business.StudentService;import com.xtwl.reporter.domain.Student;import com.xtwl.water.business.AdminInfoService;import com.xtwl.water.domain.AdminInfo;@Componentpublic class NeedOpenId implements IMethodInvokerIntercepter {	@Autowired
	private AdminInfoService adminInfoService;	@Autowired
	private StudentService studentService;	@Override
	public Object invokeHandlerMethod(Method handlerMethod, Object handler,
			HttpServletRequest request, HttpServletResponse response,
			Model model, IMethodIntercepterHolder chain) throws Exception {		if (handlerMethod.isAnnotationPresent(Openid.class)) {
			ApiConfigKit.setThreadLocalApiConfig(getApiConfig());  
			Openid access = handlerMethod.getAnnotation(Openid.class);			if (access != null) {// 如果有标签
				System.out.println("需要检查openid");				//String openid = WeiXinSession.getOpenid();
				String openid="oWDxdt8F5UTP8L3XV-KcmZdLmP2Q";//测试用的
				System.out.println("session中的openid 为:" + openid);
				System.out.println(request.getRequestURL()+"=======request.getRequestURL()2");				if (openid != null && openid.length() > 5) {// session中已经有了。放行
					return todo(chain, handlerMethod, handler, request,
							response, model, openid);
				}				if (openid == null || openid.length() < 5) {// 没有openid 需要重新获取
					String url = SnsAccessTokenApi.getAuthorizeURL(ApiConfigKit
							.getApiConfig().getAppId(), request.getRequestURL().toString(),							true);
					String code = (String) request.getParameter("code");
					System.out.println("code为:" + code + "  这是微信返回的请求");					if (code != null && code.length() > 1) {// 是请求微信之后返回来的
															// 带着openid
						SnsAccessToken sn = SnsAccessTokenApi
								.getSnsAccessToken(ApiConfigKit.getApiConfig().getAppId(),ApiConfigKit.getApiConfig().getAppSecret(), code);
						System.out.println("微信返回的openid:" + sn.getOpenid());
						WeiXinSession.setOpenid(sn.getOpenid());						return todo(chain, handlerMethod, handler, request,
								response, model, sn.getOpenid());
					} else {
						System.out.println("重定向到微信获取openid:" + url);						return "redirect:" + url;
					}
				}
			}
		}		return chain.doChain(handlerMethod, handler, request, response, model);
	}	private Object todo(IMethodIntercepterHolder chain, Method handlerMethod,
			Object handler, HttpServletRequest request,
			HttpServletResponse response, Model model, String openid)
			throws Exception {		try {
			System.out.println(request.getRequestURL()+"=======request.getRequestURL()1");			if(request.getRequestURL().toString().indexOf("/mobile/post_bind/")>0){//绑定页面 放行
				return chain.doChain(handlerMethod, handler, request, response, model);
			}			// 根据openid获取用户信息 本地的
			AdminInfo admin = adminInfoService.getItemByOpenid(openid);
			System.out.println(admin + "========数据库中的admin");			if (admin == null || admin.getId() == null) {// 未绑定
				System.out.println("redirect:/mobile/bind_phone");				return "redirect:/mobile/bind_phone";
			} else {
				Student s = studentService.getItemById(admin.getOtherid());
				WeiXinSession.setWeiXinAdminInfo(admin);
				WeiXinSession.setWeiXinStudent(s);
			}			return chain.doChain(handlerMethod, handler, request, response, model);
			
		} catch (Exception e) {
			e.printStackTrace();			return chain.doChain(handlerMethod, handler, request, response, model);
		}
	}	
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();		
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));		
		/**
		 *  是否对消息进行加密,对应于微信平台的消息加解密方式:
		 *  1:true进行加密且必须配置 encodingAesKey
		 *  2:false采用明文模式,同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));		return ac;
	}
}
ログイン後にコピー

次のステップはそれを使用することです

@RequestMapping("/mobile/myself")@Openidpublic String toIndex(Map<String, Object>model, Principal principal,HttpServletRequest request){
			model.put("principal", principal);			try {
				AdminInfo admin = WeiXinSession.getWeiXinAdminInfo();;
				Student s = WeiXinSession.getWeiXinStudent();
			
				model.put("classes", classes);
				model.put("admin", admin);
				model.put("student", s);
				
			} catch (Exception e) {
				e.printStackTrace();
			}		return "mobile/person.ftl";
	}
ログイン後にコピー


このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

SpringBootとSpringMVCの比較と差異分析 SpringBootとSpringMVCの比較と差異分析 Dec 29, 2023 am 11:02 AM

SpringBoot と SpringMVC はどちらも Java 開発で一般的に使用されるフレームワークですが、それらの間には明らかな違いがいくつかあります。この記事では、これら 2 つのフレームワークの機能と使用法を調べ、その違いを比較します。まず、SpringBoot について学びましょう。 SpringBoot は、Spring フレームワークに基づいたアプリケーションの作成と展開を簡素化するために、Pivo​​tal チームによって開発されました。スタンドアロンの実行可能ファイルを構築するための高速かつ軽量な方法を提供します。

SpringBoot と SpringMVC の違いは何ですか? SpringBoot と SpringMVC の違いは何ですか? Dec 29, 2023 am 10:46 AM

SpringBoot と SpringMVC の違いは何ですか? SpringBoot と SpringMVC は、Web アプリケーションを構築するための 2 つの非常に人気のある Java 開発フレームワークです。これらは別々に使用されることが多いですが、両者の違いは明らかです。まず、SpringBoot は Spring フレームワークの拡張版または強化版とみなすことができます。 Spring アプリケーションの初期化と構成プロセスを簡素化し、開発者を支援するように設計されています。

SpringBoot と SpringMVC の違いは何ですか? SpringBoot と SpringMVC の違いは何ですか? Dec 29, 2023 pm 05:19 PM

SpringBootとSpringMVCはJava開発でよく使われるフレームワークで、どちらもSpringフレームワークで提供されていますが、機能や使用方法にいくつかの違いがあります。この記事では、SpringBootとSpringMVCそれぞれの特徴と違いを紹介します。 1. SpringBoot の特徴: 構成の簡素化: SpringBoot は、構成より規約の原則により、プロジェクトの構成プロセスを大幅に簡素化します。プロジェクトや開発者に必要なパラメータを自動的に設定できます。

spring と springmvc の違いは何ですか spring と springmvc の違いは何ですか Dec 29, 2023 pm 05:02 PM

spring と springmvc の違い: 1. 位置付けと機能、2. コア機能、3. アプリケーション領域、4. 拡張性。詳細な紹介: 1. 位置付けと機能 Spring は、依存関係の注入、アスペクト指向プログラミング、トランザクション管理などの機能を提供する包括的なアプリケーション開発フレームワークであり、エンタープライズ レベルのアプリケーションの開発を簡素化するように設計されており、Spring MVC はそのSpring フレームワーク。そのモジュールは Web アプリケーションの開発に使用され、MVC パターンを実装します。2. コア機能など。

springboot と springmvc の違いは何ですか springboot と springmvc の違いは何ですか Jun 07, 2023 am 10:10 AM

springboot と springmvc の違いは、1. 意味の違い、2. 構成の違い、3. 依存関係の違い、4. 開発時間の違い、5. 生産性の違い、6. JAR パッケージ化機能の実装方法の違い、7. バッチ処理の有無です。提供される機能、8. さまざまな機能、9. さまざまなコミュニティおよびドキュメントのサポート、10. デプロイメント記述子が必要かどうか。

Java API開発におけるWebサービス処理にSpringMVCを利用する Java API開発におけるWebサービス処理にSpringMVCを利用する Jun 17, 2023 pm 11:38 PM

インターネットの発展に伴い、Web サービスはますます一般的になってきています。アプリケーション プログラミング インターフェイスとして、JavaAPI はさまざまなアプリケーション シナリオに適応するために新しいバージョンを常にリリースしています。 SpringMVC は、人気のあるオープンソース フレームワークとして、Web アプリケーションを簡単に構築するのに役立ちます。この記事では、SpringMVC の設定、コントローラーの作成、使用方法など、JavaAPI 開発における Web サービス処理に SpringMVC を使用する方法を詳しく説明します。

SpringBoot と SpringMVC の類似点と相違点を比較する SpringBoot と SpringMVC の類似点と相違点を比較する Dec 29, 2023 am 08:30 AM

SpringBoot と SpringMVC の類似点と相違点の分析 SpringBoot と SpringMVC は、Java 分野では非常に重要な開発フレームワークです。どちらも Spring フレームワークの一部ですが、使用方法と機能には明らかな違いがいくつかあります。この記事では、SpringBoot と SpringMVC を比較し、それらの類似点と相違点を分析します。まず、SpringBoot について学びましょう。スプリングボー

JavaのSpringMVCインターセプターの使い方 JavaのSpringMVCインターセプターの使い方 May 13, 2023 pm 02:55 PM

インターセプタの役割 SpringMVC のインターセプタは、サーブレット開発におけるフィルタに似ており、プロセッサの前処理と後処理に使用されます。インターセプタが一定の順序でチェーン状に接続されており、このチェーンをインターセプタチェーン(InterceptorChain)と呼びます。インターセプトされたメソッドまたはフィールドにアクセスすると、インターセプター チェーン内のインターセプターが、以前に定義された順序で呼び出されます。インターセプターは、AOP のアイデアを具体的に実装したものでもあります。インターセプターとフィルターの違い: フィルター (フィルター) インターセプター (インターセプター) の使用範囲はサーブレット仕様の一部であり、任意の JavaWeb プロジェクトで使用できます。

See all articles