Forráskód Böngészése

merge/异常返回错误码/新增properties文件引入类

zhuth 7 éve
szülő
commit
9b5bed83e8

+ 6 - 1
.gitignore

@@ -25,4 +25,9 @@ nbdist/
 .nb-gradle/
 
 ### Visual Studio Code ###
-.vscode
+.vscode
+
+### mvn
+.mvn/
+mvnw
+mvnw.cmd

BIN
.mvn/wrapper/maven-wrapper.jar


+ 0 - 1
.mvn/wrapper/maven-wrapper.properties

@@ -1 +0,0 @@
-distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip

BIN
lib/ojdbc7.jar


+ 0 - 225
mvnw

@@ -1,225 +0,0 @@
-#!/bin/sh
-# ----------------------------------------------------------------------------
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License.  You may obtain a copy of the License at
-#
-#    http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied.  See the License for the
-# specific language governing permissions and limitations
-# under the License.
-# ----------------------------------------------------------------------------
-
-# ----------------------------------------------------------------------------
-# Maven2 Start Up Batch script
-#
-# Required ENV vars:
-# ------------------
-#   JAVA_HOME - location of a JDK home dir
-#
-# Optional ENV vars
-# -----------------
-#   M2_HOME - location of maven2's installed home dir
-#   MAVEN_OPTS - parameters passed to the Java VM when running Maven
-#     e.g. to debug Maven itself, use
-#       set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
-#   MAVEN_SKIP_RC - flag to disable loading of mavenrc files
-# ----------------------------------------------------------------------------
-
-if [ -z "$MAVEN_SKIP_RC" ] ; then
-
-  if [ -f /etc/mavenrc ] ; then
-    . /etc/mavenrc
-  fi
-
-  if [ -f "$HOME/.mavenrc" ] ; then
-    . "$HOME/.mavenrc"
-  fi
-
-fi
-
-# OS specific support.  $var _must_ be set to either true or false.
-cygwin=false;
-darwin=false;
-mingw=false
-case "`uname`" in
-  CYGWIN*) cygwin=true ;;
-  MINGW*) mingw=true;;
-  Darwin*) darwin=true
-    # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
-    # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
-    if [ -z "$JAVA_HOME" ]; then
-      if [ -x "/usr/libexec/java_home" ]; then
-        export JAVA_HOME="`/usr/libexec/java_home`"
-      else
-        export JAVA_HOME="/Library/Java/Home"
-      fi
-    fi
-    ;;
-esac
-
-if [ -z "$JAVA_HOME" ] ; then
-  if [ -r /etc/gentoo-release ] ; then
-    JAVA_HOME=`java-config --jre-home`
-  fi
-fi
-
-if [ -z "$M2_HOME" ] ; then
-  ## resolve links - $0 may be a link to maven's home
-  PRG="$0"
-
-  # need this for relative symlinks
-  while [ -h "$PRG" ] ; do
-    ls=`ls -ld "$PRG"`
-    link=`expr "$ls" : '.*-> \(.*\)$'`
-    if expr "$link" : '/.*' > /dev/null; then
-      PRG="$link"
-    else
-      PRG="`dirname "$PRG"`/$link"
-    fi
-  done
-
-  saveddir=`pwd`
-
-  M2_HOME=`dirname "$PRG"`/..
-
-  # make it fully qualified
-  M2_HOME=`cd "$M2_HOME" && pwd`
-
-  cd "$saveddir"
-  # echo Using m2 at $M2_HOME
-fi
-
-# For Cygwin, ensure paths are in UNIX format before anything is touched
-if $cygwin ; then
-  [ -n "$M2_HOME" ] &&
-    M2_HOME=`cygpath --unix "$M2_HOME"`
-  [ -n "$JAVA_HOME" ] &&
-    JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
-  [ -n "$CLASSPATH" ] &&
-    CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
-fi
-
-# For Migwn, ensure paths are in UNIX format before anything is touched
-if $mingw ; then
-  [ -n "$M2_HOME" ] &&
-    M2_HOME="`(cd "$M2_HOME"; pwd)`"
-  [ -n "$JAVA_HOME" ] &&
-    JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
-  # TODO classpath?
-fi
-
-if [ -z "$JAVA_HOME" ]; then
-  javaExecutable="`which javac`"
-  if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
-    # readlink(1) is not available as standard on Solaris 10.
-    readLink=`which readlink`
-    if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
-      if $darwin ; then
-        javaHome="`dirname \"$javaExecutable\"`"
-        javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
-      else
-        javaExecutable="`readlink -f \"$javaExecutable\"`"
-      fi
-      javaHome="`dirname \"$javaExecutable\"`"
-      javaHome=`expr "$javaHome" : '\(.*\)/bin'`
-      JAVA_HOME="$javaHome"
-      export JAVA_HOME
-    fi
-  fi
-fi
-
-if [ -z "$JAVACMD" ] ; then
-  if [ -n "$JAVA_HOME"  ] ; then
-    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
-      # IBM's JDK on AIX uses strange locations for the executables
-      JAVACMD="$JAVA_HOME/jre/sh/java"
-    else
-      JAVACMD="$JAVA_HOME/bin/java"
-    fi
-  else
-    JAVACMD="`which java`"
-  fi
-fi
-
-if [ ! -x "$JAVACMD" ] ; then
-  echo "Error: JAVA_HOME is not defined correctly." >&2
-  echo "  We cannot execute $JAVACMD" >&2
-  exit 1
-fi
-
-if [ -z "$JAVA_HOME" ] ; then
-  echo "Warning: JAVA_HOME environment variable is not set."
-fi
-
-CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
-
-# traverses directory structure from process work directory to filesystem root
-# first directory with .mvn subdirectory is considered project base directory
-find_maven_basedir() {
-
-  if [ -z "$1" ]
-  then
-    echo "Path not specified to find_maven_basedir"
-    return 1
-  fi
-
-  basedir="$1"
-  wdir="$1"
-  while [ "$wdir" != '/' ] ; do
-    if [ -d "$wdir"/.mvn ] ; then
-      basedir=$wdir
-      break
-    fi
-    # workaround for JBEAP-8937 (on Solaris 10/Sparc)
-    if [ -d "${wdir}" ]; then
-      wdir=`cd "$wdir/.."; pwd`
-    fi
-    # end of workaround
-  done
-  echo "${basedir}"
-}
-
-# concatenates all lines of a file
-concat_lines() {
-  if [ -f "$1" ]; then
-    echo "$(tr -s '\n' ' ' < "$1")"
-  fi
-}
-
-BASE_DIR=`find_maven_basedir "$(pwd)"`
-if [ -z "$BASE_DIR" ]; then
-  exit 1;
-fi
-
-export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
-echo $MAVEN_PROJECTBASEDIR
-MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin; then
-  [ -n "$M2_HOME" ] &&
-    M2_HOME=`cygpath --path --windows "$M2_HOME"`
-  [ -n "$JAVA_HOME" ] &&
-    JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
-  [ -n "$CLASSPATH" ] &&
-    CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
-  [ -n "$MAVEN_PROJECTBASEDIR" ] &&
-    MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
-fi
-
-WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
-
-exec "$JAVACMD" \
-  $MAVEN_OPTS \
-  -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
-  "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
-  ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

+ 0 - 143
mvnw.cmd

@@ -1,143 +0,0 @@
-@REM ----------------------------------------------------------------------------
-@REM Licensed to the Apache Software Foundation (ASF) under one
-@REM or more contributor license agreements.  See the NOTICE file
-@REM distributed with this work for additional information
-@REM regarding copyright ownership.  The ASF licenses this file
-@REM to you under the Apache License, Version 2.0 (the
-@REM "License"); you may not use this file except in compliance
-@REM with the License.  You may obtain a copy of the License at
-@REM
-@REM    http://www.apache.org/licenses/LICENSE-2.0
-@REM
-@REM Unless required by applicable law or agreed to in writing,
-@REM software distributed under the License is distributed on an
-@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-@REM KIND, either express or implied.  See the License for the
-@REM specific language governing permissions and limitations
-@REM under the License.
-@REM ----------------------------------------------------------------------------
-
-@REM ----------------------------------------------------------------------------
-@REM Maven2 Start Up Batch script
-@REM
-@REM Required ENV vars:
-@REM JAVA_HOME - location of a JDK home dir
-@REM
-@REM Optional ENV vars
-@REM M2_HOME - location of maven2's installed home dir
-@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
-@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
-@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
-@REM     e.g. to debug Maven itself, use
-@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
-@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
-@REM ----------------------------------------------------------------------------
-
-@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
-@echo off
-@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
-@if "%MAVEN_BATCH_ECHO%" == "on"  echo %MAVEN_BATCH_ECHO%
-
-@REM set %HOME% to equivalent of $HOME
-if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
-
-@REM Execute a user defined script before this one
-if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
-@REM check for pre script, once with legacy .bat ending and once with .cmd ending
-if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
-if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
-:skipRcPre
-
-@setlocal
-
-set ERROR_CODE=0
-
-@REM To isolate internal variables from possible post scripts, we use another setlocal
-@setlocal
-
-@REM ==== START VALIDATION ====
-if not "%JAVA_HOME%" == "" goto OkJHome
-
-echo.
-echo Error: JAVA_HOME not found in your environment. >&2
-echo Please set the JAVA_HOME variable in your environment to match the >&2
-echo location of your Java installation. >&2
-echo.
-goto error
-
-:OkJHome
-if exist "%JAVA_HOME%\bin\java.exe" goto init
-
-echo.
-echo Error: JAVA_HOME is set to an invalid directory. >&2
-echo JAVA_HOME = "%JAVA_HOME%" >&2
-echo Please set the JAVA_HOME variable in your environment to match the >&2
-echo location of your Java installation. >&2
-echo.
-goto error
-
-@REM ==== END VALIDATION ====
-
-:init
-
-@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
-@REM Fallback to current working directory if not found.
-
-set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
-IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
-
-set EXEC_DIR=%CD%
-set WDIR=%EXEC_DIR%
-:findBaseDir
-IF EXIST "%WDIR%"\.mvn goto baseDirFound
-cd ..
-IF "%WDIR%"=="%CD%" goto baseDirNotFound
-set WDIR=%CD%
-goto findBaseDir
-
-:baseDirFound
-set MAVEN_PROJECTBASEDIR=%WDIR%
-cd "%EXEC_DIR%"
-goto endDetectBaseDir
-
-:baseDirNotFound
-set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
-cd "%EXEC_DIR%"
-
-:endDetectBaseDir
-
-IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
-
-@setlocal EnableExtensions EnableDelayedExpansion
-for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
-@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
-
-:endReadAdditionalConfig
-
-SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
-
-set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
-set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
-
-%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
-if ERRORLEVEL 1 goto error
-goto end
-
-:error
-set ERROR_CODE=1
-
-:end
-@endlocal & set ERROR_CODE=%ERROR_CODE%
-
-if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
-@REM check for post script, once with legacy .bat ending and once with .cmd ending
-if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
-if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
-:skipRcPost
-
-@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
-if "%MAVEN_BATCH_PAUSE%" == "on" pause
-
-if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
-
-exit /B %ERROR_CODE%

+ 8 - 1
pom.xml

@@ -111,7 +111,14 @@
 			<groupId>org.apache.httpcomponents</groupId>
 			<artifactId>httpmime</artifactId>
 		</dependency>
-		
+
+		<dependency>
+			<groupId>org.oracle</groupId>
+			<artifactId>oracle</artifactId>
+			<version>1.0</version>
+			<scope>system</scope>
+			<systemPath>${project.basedir}/lib/ojdbc7.jar</systemPath>
+		</dependency>
 	</dependencies>
 
 	<build>

+ 6 - 1
src/main/java/com/uas/eis/UasEisApplication.java

@@ -6,6 +6,8 @@ import org.springframework.cache.annotation.EnableCaching;
 import org.springframework.context.annotation.Import;
 
 import com.uas.eis.core.config.DynamicDataSourceRegister;
+import com.uas.eis.core.support.ActionPropertiesListener;
+import com.uas.eis.core.support.TokenPropertiesListener;
 
 @SpringBootApplication
 @EnableCaching
@@ -13,7 +15,10 @@ import com.uas.eis.core.config.DynamicDataSourceRegister;
 public class UasEisApplication {
 
 	public static void main(String[] args) {
-		SpringApplication.run(UasEisApplication.class, args);
+		SpringApplication application = new SpringApplication(UasEisApplication.class);
+		application.addListeners(new TokenPropertiesListener("token.properties"));
+		application.addListeners(new ActionPropertiesListener("action.properties"));
+		application.run(args);
 	}
 	
 }

+ 67 - 0
src/main/java/com/uas/eis/controller/LoginController.java

@@ -0,0 +1,67 @@
+package com.uas.eis.controller;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.uas.eis.service.QueryService;
+import com.uas.eis.utils.BaseUtil;
+
+@RestController
+@RequestMapping("/EIS")
+public class LoginController {
+
+	@Autowired
+	private QueryService queryService;
+	
+	/**
+	 * 首次登录请求token
+	 */
+	@RequestMapping("/login")
+	public Object login(HttpServletRequest request, String username, String password){
+		Map<String, Object> res = new HashMap<String, Object>();
+		String token = queryService.login(username, password);
+		request.getSession().removeAttribute("token");
+		if(token != null) {
+			request.getSession().setAttribute("token", token);
+			res.put("success", true);
+			res.put("token", token);
+		}else {
+			BaseUtil.showError("账户名或密码错误", "BAD_USERINFO");
+		}
+		return res;
+	}
+	
+	/**
+	 * 退出登录
+	 */
+	@RequestMapping("/logout")
+	public Object logout(HttpServletRequest request){
+		Map<String, Object> res = new HashMap<String, Object>();
+		request.getSession().removeAttribute("token");
+		res.put("success", true);
+		return res;
+	}
+	/**
+	 * hello1
+	 */
+	@RequestMapping("/hello1")
+	public Object hello1(HttpServletRequest request){
+		Map<String, Object> res = new HashMap<String, Object>();
+		res.put("message", "Hello World!");
+		return res;
+	}
+	/**
+	 * hello2
+	 */
+	@RequestMapping("/hello2")
+	public Object hello2(HttpServletRequest request){
+		Map<String, Object> res = new HashMap<String, Object>();
+		res.put("message", "Hello World..........................");
+		return res;
+	}
+}

+ 9 - 2
src/main/java/com/uas/eis/controller/QueryController.java

@@ -10,15 +10,22 @@ import org.springframework.web.bind.annotation.RestController;
 import com.uas.eis.service.QueryService;
 
 @RestController
+@RequestMapping("/EIS/")
 public class QueryController {
 
 	@Autowired
-	private QueryService userService;
+	private QueryService queryService;
 	
 	@RequestMapping("/api/query")
 	public Object query(String code, String param){
 		Map<String, Object> map = new HashMap<String, Object>();
-		return userService.query(code, param);
+		return queryService.query(code, param);
+	}
+	
+	@RequestMapping("/api/doAction")
+	public Object doAction(String code, String param){
+		Map<String, Object> map = new HashMap<String, Object>();
+		return queryService.doAction(code, param);
 	}
 	
 }

+ 4 - 5
src/main/java/com/uas/eis/core/WebAppConfig.java

@@ -16,19 +16,18 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupp
 
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.uas.eis.core.support.DataSourceInterceptor;
-import com.uas.eis.core.support.InterceptorConfig;
+import com.uas.eis.core.support.LoginInterceptor;
 
 @Configuration
 public class WebAppConfig extends WebMvcConfigurationSupport{
 
 	@Bean
-	public InterceptorConfig interceptorConfig(){
-		return new InterceptorConfig();
+	public LoginInterceptor loginInterceptor(){
+		return new LoginInterceptor();
 	}
 	
 	public void addInterceptors(InterceptorRegistry registry){
-		registry.addInterceptor(interceptorConfig()).addPathPatterns("/hello").excludePathPatterns("/login");
-//		registry.addInterceptor(new InterceptorConfig()).addPathPatterns("/*").excludePathPatterns("/login");
+		registry.addInterceptor(loginInterceptor()).addPathPatterns("/**").excludePathPatterns("/EIS/login");
 		registry.addInterceptor(new DataSourceInterceptor()).addPathPatterns("/*/**");
 	}
 	

+ 48 - 0
src/main/java/com/uas/eis/core/support/ActionProperties.java

@@ -0,0 +1,48 @@
+package com.uas.eis.core.support;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import org.springframework.beans.BeansException;
+import org.springframework.core.io.support.PropertiesLoaderUtils;
+
+public class ActionProperties {
+	
+	public static Map<String, String> propertiesMap = new HashMap<>();
+
+    private static void processProperties(Properties props) throws BeansException {
+        propertiesMap = new HashMap<String, String>();
+        for (Object key : props.keySet()) {
+            String keyStr = key.toString();
+            try {
+                // PropertiesLoaderUtils的默认编码是ISO-8859-1,在这里转码一下
+                propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8"));
+            } catch (UnsupportedEncodingException e) {
+                e.printStackTrace();
+            } catch (java.lang.Exception e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    public static void loadAllProperties(String propertyFileName) {
+        try {
+            Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName);
+            processProperties(properties);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+    public static String getProperty(String name) {
+        return propertiesMap.get(name).toString();
+    }
+
+    public static Map<String, String> getAllProperty() {
+        return propertiesMap;
+    }
+
+}

+ 19 - 0
src/main/java/com/uas/eis/core/support/ActionPropertiesListener.java

@@ -0,0 +1,19 @@
+package com.uas.eis.core.support;
+
+import org.springframework.boot.context.event.ApplicationStartedEvent;
+import org.springframework.context.ApplicationListener;
+
+public class ActionPropertiesListener implements ApplicationListener<ApplicationStartedEvent> {
+
+	private String propertyFileName;
+	
+	public ActionPropertiesListener(String propertyFileName) {
+        this.propertyFileName = propertyFileName;
+    }
+	
+	@Override
+	public void onApplicationEvent(ApplicationStartedEvent arg0) {
+		ActionProperties.loadAllProperties(this.propertyFileName);
+	}
+
+}

+ 30 - 36
src/main/java/com/uas/eis/core/support/InterceptorConfig.java → src/main/java/com/uas/eis/core/support/LoginInterceptor.java

@@ -15,43 +15,20 @@ import com.uas.eis.utils.BaseUtil;
 
 import io.jsonwebtoken.Claims;
 
-public class InterceptorConfig implements HandlerInterceptor{
+public class LoginInterceptor implements HandlerInterceptor{
 
 	@Autowired
 	private QueryService userService;
 	
-	private BaseDao baseDao;
-	
 	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
-		//token认证
 		String token = (String) request.getSession().getAttribute("token");
-		boolean flag = false;
-		String message = new String("程序错误");
-		if(token != null && !token.isEmpty()) { // 验证是否包含token
-			Claims claims = TokenHandler.parseToken(token); 
-			if(claims != null && checkToken(claims)) { // 验证token信息是否合法
-				String username = (String) claims.get("username");
-				String password = (String) claims.get("password");
-				if(checkUser(username, password)) { // 验证用户是否合法
-					String actionUrl = request.getRequestURI();
-					if(checkActionAccess(username, actionUrl)) { // 验证请求权限
-						flag = true;
-					}else {
-						message = "访问权限受限";
-					}
-				}else {
-					message = "请求用户无效";
-				}
-			}else {
-				message = "Token未通过验证或已过期";
-			}
-		}else {
-			message = "未授权的请求";
-		}
-		if(!flag) {
-			BaseUtil.showError(message);
-		}
-		return flag;
+		Claims claims = parseToken(token); // 验证并解析token
+		String username = (String) claims.get("username");
+		String password = (String) claims.get("password");
+		checkUser(username, password); // 验证用户是否合法
+		String actionUrl = request.getRequestURI();
+		checkActionAccess(username, actionUrl); // 验证请求权限
+		return true;
 	}
 	
 	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
@@ -62,16 +39,26 @@ public class InterceptorConfig implements HandlerInterceptor{
 			Exception ex) throws Exception {
 	}
 	
-	private boolean checkToken(Claims claims) {
+	private Claims parseToken(String token) {
+		if(token == null || token.isEmpty()) {
+			BaseUtil.showError("缺失token", "NULL_TOKEN");
+			return null;
+		}
+		Claims claims = TokenHandler.parseToken(token);
+		if(claims == null) {
+			BaseUtil.showError("无效的token", "INVALID_TOKEN");
+			return null;
+		}
 		Date now = new Date();
 		Date start = claims.getNotBefore();
 		Date end = claims.getExpiration();
 		
-		boolean flag = false;
 		if (now.after(start) && now.before(end)) {
-			flag = true;
+			return claims;
+		}else {
+			BaseUtil.showError("已过期的token", "OVERDUE_TOKEN");
+			return null;
 		}
-		return flag;
 	}
 	
 	private boolean checkUser(String username, String password) {
@@ -79,10 +66,17 @@ public class InterceptorConfig implements HandlerInterceptor{
 		if(username != null && password != null) {
 			enable = userService.checkUser(username, password);
 		}
+		if(!enable) {
+			BaseUtil.showError("无效用户", "INVALID_USER");
+		}
 		return enable;
 	}
 	
 	private boolean checkActionAccess(String username, String action) {
-		return userService.checkAction(username, action);
+		boolean enable = userService.checkAction(username, action);
+		if(!enable) {
+			BaseUtil.showError("受限的接口请求", "PERMISSION_DENIED_ACTION");
+		}
+		return enable;
 	}
 }

+ 48 - 0
src/main/java/com/uas/eis/core/support/TokenProperties.java

@@ -0,0 +1,48 @@
+package com.uas.eis.core.support;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import org.springframework.beans.BeansException;
+import org.springframework.core.io.support.PropertiesLoaderUtils;
+
+public class TokenProperties {
+	
+	public static Map<String, String> propertiesMap = new HashMap<>();
+
+    private static void processProperties(Properties props) throws BeansException {
+        propertiesMap = new HashMap<String, String>();
+        for (Object key : props.keySet()) {
+            String keyStr = key.toString();
+            try {
+                // PropertiesLoaderUtils的默认编码是ISO-8859-1,在这里转码一下
+                propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8"));
+            } catch (UnsupportedEncodingException e) {
+                e.printStackTrace();
+            } catch (java.lang.Exception e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    public static void loadAllProperties(String propertyFileName) {
+        try {
+            Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName);
+            processProperties(properties);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+    public static String getProperty(String name) {
+        return propertiesMap.get(name).toString();
+    }
+
+    public static Map<String, String> getAllProperty() {
+        return propertiesMap;
+    }
+
+}

+ 19 - 0
src/main/java/com/uas/eis/core/support/TokenPropertiesListener.java

@@ -0,0 +1,19 @@
+package com.uas.eis.core.support;
+
+import org.springframework.boot.context.event.ApplicationStartedEvent;
+import org.springframework.context.ApplicationListener;
+
+public class TokenPropertiesListener implements ApplicationListener<ApplicationStartedEvent> {
+
+	private String propertyFileName;
+	
+	public TokenPropertiesListener(String propertyFileName) {
+        this.propertyFileName = propertyFileName;
+    }
+	
+	@Override
+	public void onApplicationEvent(ApplicationStartedEvent arg0) {
+		TokenProperties.loadAllProperties(this.propertyFileName);
+	}
+
+}

+ 0 - 8
src/main/java/com/uas/eis/entity/TokenConfig.java

@@ -1,8 +0,0 @@
-package com.uas.eis.entity;
-
-public class TokenConfig {
-	public static String SECURITY_KEY = "36762702385535371444397399"; // 秘钥
-	public static String ISSUER = "UAS_EIS";
-	public static String AUDIENCE = "UAS_EIS";
-	public static long KEEP = 24*60*60*1000; // 保留时间1天
-}

+ 1 - 0
src/main/java/com/uas/eis/exception/ExceptionHandlerAdvice.java

@@ -47,6 +47,7 @@ public class ExceptionHandlerAdvice {
 	@ResponseBody
 	public ModelMap handleSystemError(SystemException ex, HttpServletRequest request) {
 		ModelMap map = new ModelMap();
+		map.put("exceptionCode", ex.getErrorCode());
 		map.put("exceptionInfo", ex.getMessage());
 		return map;
 	}

+ 17 - 2
src/main/java/com/uas/eis/exception/SystemException.java

@@ -12,6 +12,8 @@ public class SystemException extends RuntimeException {
 	 * 
 	 */
 	private static final long serialVersionUID = 4218425517031998401L;
+	
+	private String errorCode;
 
 	public SystemException() {
 	}
@@ -19,13 +21,26 @@ public class SystemException extends RuntimeException {
 	public SystemException(String paramString) {
 		super(paramString);
 	}
+	
+	public SystemException(String paramString, String errorCode) {
+		super(paramString);
+		this.errorCode = errorCode;
+	}
 
-	public SystemException(String paramString, Throwable paramThrowable) {
+	public SystemException(String paramString, String errorCode, Throwable paramThrowable) {
 		super(paramString, paramThrowable);
+		this.errorCode = errorCode;
 	}
 
 	public SystemException(Throwable paramThrowable) {
 		super(paramThrowable);
 	}
-
+	
+	public String getErrorCode() {
+		return this.errorCode;
+	}
+	
+	public void setErrorCode(String errorCode) {
+		this.errorCode = errorCode;
+	}
 }

+ 2 - 0
src/main/java/com/uas/eis/service/QueryService.java

@@ -9,5 +9,7 @@ public interface QueryService {
 	public abstract boolean checkAction(String username, String action);
 	
 	public Object query(String code, String param);
+	
+	public Object doAction(String code, String param);
 
 }

+ 39 - 9
src/main/java/com/uas/eis/serviceImpl/QueryServiceImpl.java

@@ -1,5 +1,7 @@
 package com.uas.eis.serviceImpl;
 
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
+
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -15,6 +17,7 @@ import org.springframework.stereotype.Service;
 import org.springframework.util.StringUtils;
 
 import com.alibaba.fastjson.JSON;
+import com.uas.eis.core.support.ActionProperties;
 import com.uas.eis.core.support.TokenHandler;
 import com.uas.eis.dao.BaseDao;
 import com.uas.eis.entity.QueryArgs;
@@ -33,7 +36,11 @@ public class QueryServiceImpl implements QueryService {
 	
 	@Override
 	public String login(String username, String password) {
-		return TokenHandler.createToken(username, password);
+		if(checkUser(username, password)) {
+			return TokenHandler.createToken(username, password);
+		}else {
+			return null;
+		}
 	}
 	
 	@Override
@@ -46,16 +53,30 @@ public class QueryServiceImpl implements QueryService {
 	@Cacheable(value="userActionEnableCache")
 	public boolean checkAction(String username, String action) {
 		boolean flag = false;
+		
 		String roles = baseDao.queryForObject("select eu_role from eis_user where eu_name='" + username + "'", String.class);
-		String[] fields = {"er_reg","er_action"};
 		if(roles == null) {
 			return false;
 		}
+		// 开放公共API的权限
+		String apiAction = ActionProperties.getProperty("api_action");
+		if(action.startsWith(apiAction)) {
+			return true;
+		}
+		// 判断是否在不需要权限控制的请求配置中
+		String[] publicActions = ActionProperties.getProperty("public_action").split(";");
+		for(String publicAction : publicActions) {
+			if(publicAction.equals(action)) {
+				return true;
+			}
+		}
+		String[] fields = {"er_reg","er_action"};
 		List<JSONObject> res = baseDao.getFieldsJSONDatasByCondition("EIS_ROLE", fields, "er_id in (" + roles + ")");
 		for(int o = 0; o< res.size(); o++) {
 			JSONObject data = res.get(o);
-			String reg = data.containsKey("er_reg")?data.getString("er_reg"):"";
-			String act = data.containsKey("er_action")?data.getString("er_action"):"";
+			String reg = data.containsKey("er_reg") ? data.getString("er_reg") : "(\\S)*";
+			String act = data.containsKey("er_action") ? data.getString("er_action") : "";
+			// 通过正则和预设接口校验请求权限
 			if(action.matches(reg) || act.indexOf(action) != -1) {
 				flag = true;
 				break;
@@ -190,6 +211,10 @@ public class QueryServiceImpl implements QueryService {
 		
 	}
 	
+	public Object doAction() {
+		return null;
+	}
+	
 	/**
 	 * 传入参数的合法性校验
 	 * @param code
@@ -198,30 +223,35 @@ public class QueryServiceImpl implements QueryService {
 	private void checkParam(String code, String param){
 		com.alibaba.fastjson.JSONObject json = JSON.parseObject(param);
 		if(StringUtils.isEmpty(code)){
-			BaseUtil.showError("查询方案编号不能为空");
+			BaseUtil.showError("查询方案编号不能为空", "NULL_QUERY_CODE");
 		}
 		if(json == null){
-			BaseUtil.showError("传入的参数个数不正确");
+			BaseUtil.showError("传入的参数个数不正确", "PARAM_AMOUNT_ERROR");
 		}
 		String getInParamsSql = "select * from queryArgs where qa_qccode = ? and qa_relation is null";
 		List<QueryArgs> inParamList = baseDao.query(getInParamsSql,  QueryArgs.class, code);
 		if(inParamList.size() != json.size()){
-			BaseUtil.showError("传入的参数个数不正确");
+			BaseUtil.showError("传入的参数个数不正确", "PARAM_AMOUNT_ERROR");
 		}else{
 			 for(QueryArgs queryArgs : inParamList){
 				 if(json.getString(queryArgs.getQa_param()) == null){
-					 BaseUtil.showError("传入的参数名不正确");
+					 BaseUtil.showError("传入的参数名不正确", "PARAM_NAME_ERROR");
 				 }else{
 					 if("array".equals(queryArgs.getQa_paramtype())){
 						 String stringArray = json.getString(queryArgs.getQa_param());
 						 if(!(stringArray.contains("[") && stringArray.contains("]"))){
-							 BaseUtil.showError("传入的参数:"+queryArgs.getQa_param()+"格式不正确");
+							 BaseUtil.showError("传入的参数:"+queryArgs.getQa_param()+"格式不正确", "PARAM_FORMAT_ERROR");
 						 }
 					 }
 				 }
 			 }
 		}
 	}
+
+	@Override
+	public Object doAction(String code, String param) {
+		return null;
+	}
 	
 	
 	

+ 5 - 0
src/main/java/com/uas/eis/utils/BaseUtil.java

@@ -31,6 +31,11 @@ public class BaseUtil {
 			throw new SystemException(error);
 	}
 	
+	public static void showError(String error, String errorCode) {
+		if (error != null && error.length() > 0)
+			throw new SystemException(error, errorCode);
+	}
+	
 	/**
 	 * List集合转化成字符串, null和空字符自动去掉
 	 * 

+ 7 - 7
src/main/java/com/uas/eis/utils/JwtUtil.java

@@ -2,13 +2,12 @@ package com.uas.eis.utils;
 
 import java.security.Key;
 import java.util.Date;
-import java.util.UUID;
+import java.util.Map;
 
 import javax.crypto.spec.SecretKeySpec;
 import javax.xml.bind.DatatypeConverter;
 
-import com.fasterxml.jackson.databind.deser.impl.ExternalTypeHandler.Builder;
-import com.uas.eis.entity.TokenConfig;
+import com.uas.eis.core.support.TokenProperties;
 
 import io.jsonwebtoken.Claims;
 import io.jsonwebtoken.JwtBuilder;
@@ -16,7 +15,8 @@ import io.jsonwebtoken.Jwts;
 import io.jsonwebtoken.SignatureAlgorithm;
 
 public class JwtUtil {
-	private static String base64Security = TokenConfig.SECURITY_KEY;
+	private static Map<String,String> tokenConfig = TokenProperties.getAllProperty();
+	private static String base64Security = tokenConfig.get("SECURITY_KEY");
 	
 	public static String createJWT(String username, String password) {
 		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
@@ -32,12 +32,12 @@ public class JwtUtil {
 		JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
 				.claim("username", username)
 				.claim("password", password)
-				.setIssuer(TokenConfig.ISSUER)
-				.setAudience(TokenConfig.AUDIENCE)
+				.setIssuer(tokenConfig.get("ISSUER"))
+				.setAudience(tokenConfig.get("AUDIENCE"))
 				.signWith(signatureAlgorithm, signingKey);
 		
 		// 添加Token过期时间
-		long expMillis = nowMillis + TokenConfig.KEEP;
+		long expMillis = nowMillis + Long.parseLong(tokenConfig.get("KEEP"));
 		Date exp = new Date(expMillis);
 		builder.setExpiration(exp).setNotBefore(now);
 

+ 2 - 0
src/main/resources/action.properties

@@ -0,0 +1,2 @@
+api_action=/EIS/api
+public_action=/EIS/logout;/EIS/hello1

+ 10 - 1
src/main/resources/application.yml

@@ -14,4 +14,13 @@ spring:
         encoding: UTF-8
 server:
     tomcat:
-        uri_encoding: UTF-8
+        uri_encoding: UTF-8
+token:
+    properties:
+        SECURITY_KEY: 435aMe9L5itTrckY35kfcOQvPkBGZtGo
+        ISSUER: EIS_ISS
+        AUDIENCE: EIS_AUD
+        KEEP: 86400000
+action:
+    api_action: /EIS/api
+    public_action: /EIS/logout;/EIS/hello1

+ 4 - 0
src/main/resources/token.properties

@@ -0,0 +1,4 @@
+SECURITY_KEY=435aMe9L5itTrckY35kfcOQvPkBGZtGo
+ISSUER=EIS_ISS
+AUDIENCE=EIS_AUD
+KEEP=86400000