应用背景
早先做权限控制都是采用自己编写的interceptor进行过滤拦截,适合仅针对登录进行校验的场景,随着要求复杂多样化,就需要寻求一款稳定便捷的框架。shiro和security都是不错的选择,我这次姑且先选型shiro。
项目地址
该demo我开放为公共项目,地址为
https://gitee.com/fzuzhanghao/shiro-demo.git
有兴趣可以拉下来看看
shiro简介
Apache Shiro是一款提供了身份认证、授权管理、加密以及session管理的强大且便捷的框架,通过其便捷的API可以有效地加强后台服务器安全校验,且应用范围广泛。
总的来说有以下几点
- Authentication:身份认证/登录,验证用户是不是拥有相应的身份;
- Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限;
- Session Manager:会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通JavaSE环境的,也可以是如Web环境的;
- Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;
- Web Support:Web支持,可以非常容易的集成到Web环境;
- Caching:缓存,比如用户登录后,其用户信息、拥有的角色/权限不必每次去查,这样可以提高效率;
- Concurrency:shiro支持多线程应用的并发验证,即如在一个线程中开启另一个线程,能把权限自动传播过去;
- Testing:提供测试支持;
- Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问;
- Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录了。
环境准备
jdk 1.7
tomcat7
spring 4.0.2
mybatis 3.2.6
shiro 1.3.0
工程搭建
系统采用了springMVC+mybatis+maven这种传统架构,当然也可以换成ssm啊,ssh啦这些都随意,总体工程构建这里就不予以赘述,新建simple maven工程,然后通过project facets转换为web dynamic即可,转换过程中忘记添加web.xml也可以手动增加src/main/webapps目录以及web.xml。
接下来主要列出配置文件以及POM的内容。
在pom中需要引入spring,shiro-all以及mybatis等配置信息
主要配置文件
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.testshiro</groupId>
<artifactId>testshiro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>testshiro</name>
<description>testshiro</description>
<properties>
<!-- spring版本号 -->
<spring.version>4.0.2.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.6</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<shiro.version>1.3.0</shiro.version>
</properties>
<dependencies>
<!-- 基础模块 -->
<dependency>
<groupId>com.ld.baseMode</groupId>
<artifactId>baseMode</artifactId>
<version>0.0.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>
<!-- spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- 导入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-all -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>${shiro.version}</version>
</dependency>
<!-- JSTL标签类 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 格式化对象,方便输出日志 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<!-- 引入新版JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
<!-- 上传组件包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
</dependencies>
</project>
接下来我们要配置web.xml告诉容器对shiro进行加载以及拦截。
web.xml
<!--spring配置文件以及shiro配置文件声明-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/spring-base.xml,classpath:/spring/spring-shiro.xml</param-value>
</context-param>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>webapp.testshiro</param-value>
</context-param>
……
<!-- shiro filter -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--springmvc配置-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
随后配置spring主文件
spring-base.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:aop="http://www.springframework.org/schema/aop"
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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
>
<context:property-placeholder location="classpath*:/*.properties" />
<context:component-scan base-package="com.testshiro" />
<!-- 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="initialPoolSize" value="${jdbc.c3p0.initialPoolSize}" />
<property name="minPoolSize" value="${jdbc.c3p0.min_size}" />
<property name="maxPoolSize" value="${jdbc.c3p0.max_size}" />
<property name="maxIdleTime" value="${jdbc.c3p0.max_idle_time}" />
<property name="acquireIncrement" value="${jdbc.c3p0.acquire_increment}" />
<property name="maxStatements" value="${jdbc.c3p0.max_statements}" />
<property name="idleConnectionTestPeriod" value="${jdbc.c3p0.idle_connection_test_period}" />
<property name="checkoutTimeout" value="${jdbc.c3p0.checkout_timeout}" />
<property name="testConnectionOnCheckin" value="${jdbc.c3p0.test_connection_on_checkin}" />
<property name="automaticTestTable" value="${jdbc.c3p0.automatic_test_table}" />
<property name="preferredTestQuery" value="${jdbc.c3p0.preferred_test_query}" />
</bean>
<!-- sessionfactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" lazy-init="false" >
<property name="configLocation" value="classpath:/mybatis/mybatis-config.xml" />
<property name="mapperLocations" value="classpath*:/mybatis/mappers/*.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
<!-- only one datasource -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="annotationClass" value="org.springframework.stereotype.Repository" />
<property name="basePackage" value="com.**.dao" />
</bean>
<!-- 事务配置 -->
<!-- Spring TransactionManager -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
<qualifier value="trans" />
<property name="defaultTimeout" value="${jdbc.transation_timeout}" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>resource/config</value>
</list>
</property>
</bean>
</beans>
spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
">
<mvc:annotation-driven>
<!-- 处理responseBody 里面日期类型 -->
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
</bean>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- controller包(自动注入)subject -->
<context:component-scan base-package="com.testshiro.controller" />
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".html" />
</bean>
</beans>
mybatis-config.xml
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="false" />
<setting name="lazyLoadingEnabled" value="false" />
<setting name="multipleResultSetsEnabled" value="true" />
<setting name="useColumnLabel" value="true" />
<setting name="useGeneratedKeys" value="false" />
<setting name="defaultExecutorType" value="SIMPLE" />
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
c3p0连接池配置
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3360/shiro_test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
jdbc.username=test
jdbc.password=test123
jdbc.c3p0.acquire_increment=2
jdbc.c3p0.initialPoolSize=2
jdbc.c3p0.min_size=2
jdbc.c3p0.max_size=10
jdbc.c3p0.max_idle_time=180
jdbc.c3p0.max_statements=0
jdbc.c3p0.idle_connection_test_period=180
jdbc.c3p0.checkout_timeout=30000
jdbc.c3p0.test_connection_on_checkin=true
jdbc.c3p0.automatic_test_table=c3p0_test
jdbc.c3p0.preferred_test_query=select * from "c3p0_test"
jdbc.transation_timeout=1800
然后在spring-shiro.xml配置文件中,配置shiro的相关信息,包括URL规则、自定义realm等。
spring-shiro.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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd"
>
<!-- Shiro Filter 拦截器相关配置 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- securityManager -->
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/login.jsp" />
<property name="unauthorizedUrl" value="/403.jsp" />
<!-- <property name="filters">
<util:map>
<entry key="anAlias" value-ref="someFilter"/>
</util:map>
</property> -->
<!-- 过滤链定义 -->
<property name="filterChainDefinitions">
<value>
/data/sysaccount/login*=anon
/data/sysaccount/**=authc,perms[sysAccount]
/data/sysautho/**=authc,perms[sysAutho]
/data/sysrole/**=authc,perms[sysRole]
</value>
</property>
</bean>
<!-- securityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm" />
</bean>
<!-- 自定义Realm实现 -->
<bean id="myRealm" class="com.testshiro.realm.CustomRealm" />
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
</beans>
常用的配置规则包括:
tag | 作用 | 示例 |
---|---|---|
anno | 该URL不需要进行校验 | login*=anon |
authc | 该URL需要进行登录校验 | /data/sysaccount/**=authc |
roles | 校验用户是否拥有某角色信息 | /data/sysaccount/**=roles[admin] |
perms | 校验用户是否拥有某权限信息 | /data/sysautho/**=perms[sysAutho] |
到此shiro相关的配置就已经完成了,我们可以开始编写上面提到的com.testshiro.realm.CustomRealm这个控制类。
实体类编写
主要工程结构如下图,可以作为参考,service,dao无非就是crud操作,所以关键会讲需要调用的登录、获取权限两个接口功能以及controller中的登录登出操作,其他代码就略去了。
service、dao以及mapper简览,会配置的可以跳过了。
关键部分:
1、CustomRealm
CustomRealm需要继承自AuthorizingRealm,并且实现doGetAuthorizationInfo和doGetAuthenticationInfo方法,前者用于提取权限,后者用于返回账户授权信息。
CustomRealm是在Security Manager校验过再进行调用,shiro会首先调用自己的filter,确认登录权限过后才会进入CustomRealm,刚开始学容易误解,容易跟之前interceptor自定义校验模式混淆。所以未登录未设置token的情况下去访问自己的资源,会发现CustomRealm中的doGetAuthenticationInfo方法并没有调用到。
很多blog中登录校验会放在doGetAuthenticationInfo这个方法中做,我直接在自己的登录方法中做掉了,所以这里只是简单地赋个值然后踢给Security Manager。
package com.testshiro.realm;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import com.testshiro.entity.SysAutho;
import com.testshiro.service.SysAccountService;
public class CustomRealm extends AuthorizingRealm {
private final static Logger log = Logger.getLogger(CustomRealm.class);
@Resource
private SysAccountService sysaccountService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
log.info("getAuthoCheck");
String username = (String) arg0.fromRealm(getName()).iterator().next();
if (username != null) {
List<SysAutho> pers = sysaccountService
.getAuthosByUserName(username);//通过用户名拉取该用户的权限信息,读出列表后丢给security Manager,因为每次调用都会执行该方法,所以生产环境中会启用redis或是其他缓存
if (pers != null && !pers.isEmpty()) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
for (SysAutho each : pers) {
// 将权限资源添加到用户信息中
info.addStringPermission(each.getMark());
}
return info;
}
}
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken arg0) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) arg0;
if (token != null) {
return new SimpleAuthenticationInfo(token.getUsername(),
token.getPassword(), getName());
} else {
return null;
}
}
}
CustomRealm这个类中出现的UsernamePasswordToken为用户令牌,我们在登录方法中对其进行操作赋值
2、SysAccountController
.....
@Controller
@RequestMapping(value = "/data/sysaccount")
public class SysAccountController {
private final static Logger log = Logger
.getLogger(SysAccountController.class);
@Resource
private SysAccountService sysaccountService;
@RequestMapping(value = "login", method = RequestMethod.POST)
@ResponseBody
public RetMsg login(HttpServletRequest request, HttpServletResponse response)
throws Exception {
RetMsg retmsg = new RetMsg();
List<SysAccount> ret = null;
Map<String, Object> tmp = new HashMap<String, Object>();
String loginName = request.getParameter("loginName");
String password = request.getParameter("password");
Page page = new Page();
page.clear();
page.setCondition(tmp);
ret = sysaccountService.login(loginName, MD5.MD5Encode(password));
if (ret.size() < 1) {
retmsg.setCode(-1);
retmsg.setMsg("错误的用户名或密码!");
} else {
SysAccount account = ret.get(0);
if (account.getIsDel() == 0) {
//清空security中的信息
SecurityUtils.getSecurityManager().logout(
SecurityUtils.getSubject());
//根据自身情况也可以利用httpsession,该操作与shiro无关
HttpSession session = request.getSession();
session.setAttribute("loginUser", account);
//设置token
UsernamePasswordToken token = new
UsernamePasswordToken(account.getPassword());
Subject subject = SecurityUtils.getSubject();
subject.login(token);
} else {
retmsg.setCode(-1);
retmsg.setMsg("您的账户已经被禁用!请联系管理员!");
}
}
return retmsg;
}
@RequestMapping(value = "logout", method = RequestMethod.GET)
@ResponseBody
public RetMsg logout(HttpServletRequest request,
HttpServletResponse response) throws Exception {
RetMsg retmsg = new RetMsg();
HttpSession session = request.getSession();
session.setAttribute("loginUser", null);
session.removeAttribute("loginUser");
SecurityUtils.getSecurityManager().logout(
SecurityUtils.getSubject());
return retmsg;
}
.....
}
ps:由于系统架构采用的是ajax操作,所以返回使用json,页面跳转可以自己改为modelandview。下一章会专门针对ajax数据返回进行记录。
CustomRealm类中调用的getAuthosByUserName方法以及SysAccountController调用的login方法即是我们自己定义的业务接口,主要功能从数据库读取权限信息以及登录校验,这里给出mybatis接口声明代码作为参考。
<select id="getAuthosByUserName" resultMap="SysAuthoMap" parameterType="java.lang.String">
SELECT
au.*
FROM
sys_account a
INNER JOIN sys_account_2_role a2r ON a.seq_id = a2r.account_id
AND a.login_name = #{username}
INNER JOIN sys_role r ON a2r.role_id = r.seq_id
AND r.is_del = 0
INNER JOIN sys_role_2_autho r2a ON r.seq_id = r2a.role_id
INNER JOIN sys_autho au ON au.seq_id = r2a.autho_id
AND au.is_del = 0
AND au.is_leaf = 1
</select>
<select id="login" resultMap="SysAccountMap" parameterType="Object">
select <include refid="Base_Column_List" />
from sys_account where login_name = #{loginName} and password = #{password}
</select>
核心内容到此已经完成,其余部分根据自己选型的框架搭建即可。
测试
将工程运行起来,不登录访问资源接口readById,即跳转到我配置的伪ajax页面login.jsp,如果工程采用JSP调整架构,这里可以做成自己的提示页面。
<%@ page language="java" contentType="text/html; charset=utf8"
pageEncoding="utf8"%>
{code=-1,msg="请登录!"}
未授权情况
<%@ page language="java" contentType="text/html; charset=utf8"
pageEncoding="utf8"%>
{code=-1,msg="未授权的页面!"}
再进行登录且授权后:
基础构建完成。
下一章记录真正ajax json数据返回的处理方法。