技术栈
前端界面使用 LayuiAdmin提供的后台管理模板系统
前端与后端数据交互全部采用JQuery提供的ajax异步请求
后端使用Servlet提供HTTP接口,一个Servlet实现类提供多个HTTP接口,由if条件分支映射到具体对应的Services方法处理业务
持久层使用JDBC访问数据库,并通过反射可以将查询结果集映射为java实体类对象或者Map对象
由于要实现后端权限控制,所以一些视图资源统一放在了web目录的WEB-INF文件夹下,由一个名为ViewResolver的servlet通过转发来实现视图的跳转以及非公共静态资源的访问
配置文件:配置文件使用properties文件管理,有统一的配置管理类在系统启动的时候加载配置文件
具体技术实现
持久层 JDBC工具类
public synchronized <T> List<T> executeQueryForList(String sql, Class<T> resultType,Object... params) {
List<T> result = new ArrayList<>();
T bean;
getConnection();
statement = getStatement(sql);
if (params !=null&¶ms.length!=0){
setParams(params);
}
try {
resultSet = statement.executeQuery();
while (resultSet.next()) {
bean = resultType.newInstance();
Field[] fields = resultType.getDeclaredFields();
for (Field field : fields) {
Object value = null;
try {
value = resultSet.getObject(field.getName());
}catch (SQLException e){
continue;
}
field.setAccessible(true);
field.set(bean, value);
}
result.add(bean);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
return result;
}
这是JDBC工具类中的一个方法,是一个实体方法,需要用对象去调用
sql执行使用了 PreparedStatement 可以避免sql注入带来的安全问题
执行sql完成之后返回结果集ResultMap之后,使用反射创建对应的Java实体类对象(方法参数提供了实体类的Class对象)。
�
默认映射方式是如果结果集中的列名和实体类的属性列表中属性名相同,就把结果集中的这个字段的值赋值给实体类对象的这个属性。具体实现方法见代码详情
while (resultSet.next()) {
bean = resultType.newInstance();
Field[] fields = resultType.getDeclaredFields();
for (Field field : fields) {
Object value = null;
try {
value = resultSet.getObject(field.getName());
}catch (SQLException e){
continue;
}
field.setAccessible(true);
field.set(bean, value);
}
其他返回实体类的方法都基于这个方法来实现
还有一个方法是结果集中的数据映射成Map:
·public synchronized List<Map<String, Object>> executeQueryForListMap(String sql,Object... params){
List<Map<String, Object>> result = new ArrayList<>();
Map<String, Object> bean;
getConnection();
statement = getStatement(sql);
if (params !=null&¶ms.length!=0){
setParams(params);
}
try {
resultSet = statement.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
while (resultSet.next()) {
bean = new HashMap<String, Object>();
for (int i = 1; i < columnCount+1; i++) {
bean.put(metaData.getColumnLabel(i),resultSet.getObject(i));
}
result.add(bean);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
return result;
}
直接把ResultMap中的一行数据映射为一个HashMap对象,列明作为Key值作为Value
多行数据作为多个HashMap对象放入一个List中返回
这种处理结果集的方式更为通用,更灵活
权限控制
全局的访问控制有一个名为AuthorityFilter的Filter实现控制:代码如下:
@WebFilter(filterName = "authorityFilter",urlPatterns = "/*")
public class AuthorityFilter implements Filter {
private final Logger logger = LoggerFactory.getLogger(AuthorityFilter.class);
private List<String> staticResourceList = null;
private List<String> adminList = null;
private List<String> studentList = null;
private List<String> teacherList = null;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
staticResourceList = ConfigUtil.getList("server.resource.static",",");
adminList = ConfigUtil.getList("server.user.authorityList.admin",",");
studentList = ConfigUtil.getList("server.user.authorityList.student",",");
teacherList = ConfigUtil.getList("server.user.authorityList.teacher",",");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpSession session = request.getSession();
String uri = request.getRequestURI().replace(request.getContextPath(),"");
Integer type = (Integer) session.getAttribute(SessionData.TYPE.getSessionKey());
//放行登录页
if (uri.equals("/")||uri.equals("/login")||uri.equals("/login.jsp")){
filterChain.doFilter(request,response);
return;
}
//放行错误页
if (uri.contains("error_page")){
filterChain.doFilter(request,response);
return;
}
//放行静态资源
if (test(uri,staticResourceList)){
filterChain.doFilter(request, response);
return;
}
//权限校验
if (type == null){
response.sendRedirect("/");
}else if (type.equals(AccountType.ADMIN.getCode())){
if (test(uri,adminList)) {
filterChain.doFilter(request,response);
}else{
response.sendRedirect("/error_page/401.html");
}
}else if (type.equals(AccountType.STUDENT.getCode())){
if (test(uri,studentList)) {
filterChain.doFilter(request,response);
}else{
response.sendRedirect("/error_page/401.html");
}
}else if (type.equals(AccountType.TEACHER.getCode())){
if (test(uri,teacherList)) {
filterChain.doFilter(request,response);
}else{
response.sendRedirect("/error_page/401.html");
}
}else{
response.sendRedirect("/error_page/401.html");
}
}
private boolean test(String uri,List<String> ruleList){
for (String s : ruleList) {
if (s.endsWith("/*")){
if (uri.startsWith(s.replace("/*",""))){
return true;
}
}else {
if (s.equals(uri)){
return true;
}
}
}
return false;
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
不同角色的权限列表也在properties配置文件中指定,如下:
#用户权限类型
server.user.types=admin,student,teacher
#用户权限列表
server.user.authorityList.admin=/login,/api/common/*,/api/admin/*,/view/common/*,/view/admin/*,/,/index,/api/student/*,/api/teacher/*
server.user.authorityList.student=/login,/api/common/*,/api/student,/view/common/*,/view/student/*,/,/index,/api/student/*
server.user.authorityList.teacher=/login,/api/common/*,/api/teacher/*,/view/common/*,/view/teacher/*,/,/index
server.resource.static=/static/*
视图跳转
由于要实现后端权限控制,视图的访问也要后端实现权限控制,所以将所有的非公共资源的视图资源放在了无法会直接访问的WEB-INF目录下。
前端访问视图资源统一访问一个名为ViewResolver的Servlet通过转发访问。代码如下:
@WebServlet(name = "viewResolver" , urlPatterns = "/view/*")
public class ViewResolver extends HttpServlet {
private static final long serialVersionUID = 8549443362991290786L;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uri = req.getRequestURI();
String contextPath = req.getContextPath();
uri = uri.replace(contextPath,"");
String viewPath = getViewPath(uri);
req.getRequestDispatcher(viewPath).forward(req,resp);
}
private String getViewPath(String uri){
uri = uri.substring(5);
String prefix = ConfigUtil.getString("server.viewResolver.prefix");
String suffix = ConfigUtil.getString("server.viewResolver.suffix");
return prefix + uri + suffix;
}
}
视图的前缀和后缀在配置文件中统一管理:
server.viewResolver.prefix=/WEB-INF/view
server.viewResolver.suffix=.jsp
这样就可以个不同的用户角色分配不同的文件夹放置视图资源,统一管理视图的访问权限
配置文件的读取
全部的配置文件都写在名为application.properties的配置文件中
通过ConfigUtil工具类读取配置文件的信息,代码如下:
/**
* 读取配置文件工具类
*
* @author 韩晓红
*/
public class ConfigUtil {
private static final Logger logger = LoggerFactory.getLogger(ConfigUtil.class);
private static final Properties PROPERTIES;
static {
InputStream resourceAsStream = ConfigUtil.class.getClassLoader().getResourceAsStream("application.properties");
PROPERTIES = new Properties();
try {
PROPERTIES.load(resourceAsStream);
} catch (IOException e) {
e.printStackTrace();
logger.error("load application.properties error!");
System.exit(0);
}
}
public static String getString(String key){
return PROPERTIES.getProperty(key);
}
public static List<String> getList(String key,String regex){
return Arrays.asList(PROPERTIES.getProperty(key).split(regex));
}
}
通过static代码块,在类加载的时候使用加载当前类的类加载器读取配置文件,将配置信息加载进内存,
通过两个staitc方法分别获取单项的配置和列表的配置