前篇所需后端代码

SPA项目开发之登录注册所需
废话不多上代码:
先看要写的:
前篇所需后端代码_第1张图片

Biz层

ArticleBiz:

package com.lihao.vue.biz;

import java.util.List;

import com.lihao.vue.entity.Article;
import com.lihao.vue.util.PageBean;

public interface ArticleBiz {
	public List
list(Article article,PageBean pageBean); public int save(Article article); public int edit(Article article); public void del(Article article); }

ArticleBizImpl:

package com.lihao.vue.biz.impl;

import java.util.List;

import com.lihao.vue.biz.ArticleBiz;
import com.lihao.vue.dao.ArticleDao;
import com.lihao.vue.entity.Article;
import com.lihao.vue.util.PageBean;

public class ArticleBizImpl implements ArticleBiz {
	private ArticleDao articleDao;

	public ArticleDao getArticleDao() {
		return articleDao;
	}

	public void setArticleDao(ArticleDao articleDao) {
		this.articleDao = articleDao;
	}

	@Override
	public List
list(Article article, PageBean pageBean) { return articleDao.list(article, pageBean); } @Override public int save(Article article) { return articleDao.save(article); } @Override public void del(Article article) { articleDao.del(article); } @Override public int edit(Article article) { return articleDao.update(article); } }

TreeNodeBiz:

package com.lihao.vue.biz;

import java.util.List;

import com.lihao.vue.entity.TreeNode;

public interface TreeNodeBiz {
	public List list();
}

TreeNodeBizImpl:

package com.lihao.vue.biz.impl;


import java.util.List;

import com.lihao.vue.biz.TreeNodeBiz;
import com.lihao.vue.dao.TreeNodeDao;
import com.lihao.vue.entity.TreeNode;

public class TreeNodeBizImpl implements TreeNodeBiz{
	private TreeNodeDao treeNodeDao;
	

	public TreeNodeDao getTreeNodeDao() {
		return treeNodeDao;
	}


	public void setTreeNodeDao(TreeNodeDao treeNodeDao) {
		this.treeNodeDao = treeNodeDao;
	}


	@Override
	public List list() {
		return treeNodeDao.list();
	}

}

UserBiz:

package com.lihao.vue.biz;

import com.lihao.vue.entity.User;

public interface UserBiz {
	public User login(User user);
}

UserBizImpl :

package com.lihao.vue.biz.impl;

import com.lihao.vue.biz.UserBiz;
import com.lihao.vue.dao.UserDao;
import com.lihao.vue.entity.User;

public class UserBizImpl implements UserBiz {
	private UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public User login(User user) {
		return userDao.list(user, null).get(0);
	}

}

Dao层

ArticleDao:

package com.lihao.vue.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;

import com.lihao.base.dao.BaseDao;
import com.lihao.vue.entity.Article;
import com.lihao.vue.util.PageBean;
import com.lihao.vue.util.StringUtils;

public class ArticleDao extends BaseDao {

	private static final long serialVersionUID = -2644908989655094673L;

	public List
list(Article article,PageBean pageBean) { BaseDao obj = this; return (List
) this.getHibernateTemplate().execute(new HibernateCallback>() { @Override public List
doInHibernate(Session session) throws HibernateException { String hql = "from Article"; Map map = new HashMap<>(); if (StringUtils.isNotBlank(article.getTitle())) { hql += " where title like :title"; map.put("title", "%"+article.getTitle()+"%"); } return obj.executeQuery(session, hql, map, pageBean); } }); } public int save(Article article) { return (int) this.getHibernateTemplate().save(article); } public int update(Article article) { this.getHibernateTemplate().update(article); return article.getId(); } public void del(Article article) { this.getHibernateTemplate().delete(article); } }

TreeNodeDao:

package com.lihao.vue.dao;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;

import com.lihao.base.dao.BaseDao;
import com.lihao.vue.entity.TreeNode;

public class TreeNodeDao extends BaseDao {

	private static final long serialVersionUID = 1297339130752837659L;
	public void add(TreeNode treeNode) {
		this.getHibernateTemplate().save(treeNode);
	}
	
	public List list(){
		return (List) this.getHibernateTemplate().execute(new HibernateCallback>() {
			@Override
			public List doInHibernate(Session session) throws HibernateException {
				List list = (List) session.createQuery("from TreeNode where treeNodeType=1").list();
//				for (TreeNode treeNode : list) {
//					Hibernate.initialize(treeNode.getChildren());
//				}
				return list;
			}
		});
	}

}

UserDao:

package com.lihao.vue.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;

import com.lihao.base.dao.BaseDao;
import com.lihao.vue.entity.User;
import com.lihao.vue.util.PageBean;
import com.lihao.vue.util.StringUtils;

public class UserDao extends BaseDao {

	private static final long serialVersionUID = -2644908989655094673L;

	public List list(User user,PageBean pageBean) {
		BaseDao obj = this;
		return (List) this.getHibernateTemplate().execute(new HibernateCallback>() {
			@Override
			public List doInHibernate(Session session) throws HibernateException {
				String hql = "from User where 1=1 ";
				Map map = new HashMap<>();
				String uname = user.getUname();
				String pwd = user.getPwd();
				if (StringUtils.isNotBlank(uname)) {
					hql += " and uname = :uname";
					map.put("uname", uname);
				}
				if (StringUtils.isNotBlank(pwd)) {
					hql += " and pwd = :pwd";
					map.put("pwd", pwd);
				}
				return obj.executeQuery(session, hql, map, pageBean);
			}
		});
	}
}

entity层

Article:

package com.lihao.vue.entity;

public class Article {
	private Integer id;
	private String title;
	private String body;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getBody() {
		return body;
	}

	public void setBody(String body) {
		this.body = body;
	}


}

TreeNode:

package com.lihao.vue.entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class TreeNode implements Serializable{
	private Integer treeNodeId;
	private String treeNodeName;
	private Integer treeNodeType;
//	private int parentNodeId;
	private String url;
	private Integer position;
	private String icon;
	private List children = new ArrayList<>();

	@Override
	public String toString() {
		return "TreeNode [treeNodeId=" + treeNodeId + ", treeNodeName=" + treeNodeName + ", treeNodeType="
				+ treeNodeType + ", url=" + url + ", position=" + position + ", icon=" + icon + ", children=" + children
				+ "]";
	}

	public Integer getTreeNodeId() {
		return treeNodeId;
	}

	public void setTreeNodeId(Integer treeNodeId) {
		this.treeNodeId = treeNodeId;
	}

	public String getTreeNodeName() {
		return treeNodeName;
	}

	public void setTreeNodeName(String treeNodeName) {
		this.treeNodeName = treeNodeName;
	}

	public Integer getTreeNodeType() {
		return treeNodeType;
	}

	public void setTreeNodeType(Integer treeNodeType) {
		this.treeNodeType = treeNodeType;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Integer getPosition() {
		return position;
	}

	public void setPosition(Integer position) {
		this.position = position;
	}

	public String getIcon() {
		return icon;
	}

	public void setIcon(String icon) {
		this.icon = icon;
	}

	public List getChildren() {
		return children;
	}

	public void setChildren(List children) {
		this.children = children;
	}


//	public int getParentNodeId() {
//		return parentNodeId;
//	}
//
//	public void setParentNodeId(int parentNodeId) {
//		this.parentNodeId = parentNodeId;
//	}


}

User:

package com.lihao.vue.entity;

public class User {
	private String uname;
	private String pwd;

	public String getUname() {
		return uname;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	@Override
	public String toString() {
		return "User [uname=" + uname + ", pwd=" + pwd + "]";
	}

	public User(String uname, String pwd) {
		super();
		this.uname = uname;
		this.pwd = pwd;
	}

	public User() {
		super();
	}

}

Article.hbm.xml:




	
		
			
		
		
		
		
	

TreeNode.hbm.xml:




	
		
			
		
		
		
		
		

		
		
		
		
			
			
		
	

User.hbm.xml:




	
		
			
		
		
		
	

test层

JwtDemo:

package com.lihao.vue.test;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import com.lihao.vue.util.JwtUtils;

import io.jsonwebtoken.Claims;

public class JwtDemo {

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

	@Test
	public void test1() {// 生成JWT
		Map claims = new HashMap();
		claims.put("username", "zss");
		claims.put("age", 18);

		String jwt = JwtUtils.createJwt(claims, JwtUtils.JWT_WEB_TTL);
		System.out.println(jwt);

		Claims parseJwt = JwtUtils.parseJwt(jwt);
		for (Map.Entry entry : parseJwt.entrySet()) {
			System.out.println(entry.getKey() + "=" + entry.getValue());
		}
		Date d1 = parseJwt.getIssuedAt();
		Date d2 = parseJwt.getExpiration();
		System.out.println("令牌签发时间:" + sdf.format(d1));
		System.out.println("令牌过期时间:" + sdf.format(d2));
	}

	@Test
	public void test2() {// 解析oldJwt
//		String oldJwt = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NjI5MDMzNjAsImlhdCI6MTU2MjkwMTU2MCwiYWdlIjoxOCwianRpIjoiZDVjMzE4Njg0MDcyNDgyZDg1MDE5ODVmMDY3OGQ4NjkiLCJ1c2VybmFtZSI6InpzcyJ9.XDDDRRq5jYq5EdEBHtPm7GcuBz4S0VhDTS1amRCdf48";
		String oldJwt = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NjM1MjU5MjMsImlhdCI6MTU2MzUyNDEyMywiYWdlIjoxOCwianRpIjoiOTAzNmMwY2Q3NGIwNDBjMzgzMDAxYzdiNmZkMzYzZmIiLCJ1c2VybmFtZSI6InpzcyJ9.sgV9fr4fgmmahDFRJnsfazA6R3H-gNMVcg2ucA227n4";
		Claims parseJwt = JwtUtils.parseJwt(oldJwt);
		for (Map.Entry entry : parseJwt.entrySet()) {
			System.out.println(entry.getKey() + "=" + entry.getValue());
		}
		Date d1 = parseJwt.getIssuedAt();
		Date d2 = parseJwt.getExpiration();
		System.out.println("令牌签发时间:" + sdf.format(d1));
		System.out.println("令牌过期时间:" + sdf.format(d2));
	}

	@Test
	public void test3() {// 复制jwt,并延时30秒
		String oldJwt = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NjI5MDMzNjAsImlhdCI6MTU2MjkwMTU2MCwiYWdlIjoxOCwianRpIjoiZDVjMzE4Njg0MDcyNDgyZDg1MDE5ODVmMDY3OGQ4NjkiLCJ1c2VybmFtZSI6InpzcyJ9.XDDDRRq5jYq5EdEBHtPm7GcuBz4S0VhDTS1amRCdf48";
		String jwt = JwtUtils.copyJwt(oldJwt, JwtUtils.JWT_WEB_TTL);
		Claims parseJwt = JwtUtils.parseJwt(jwt);
		for (Map.Entry entry : parseJwt.entrySet()) {
			System.out.println(entry.getKey() + "=" + entry.getValue());
		}
		Date d1 = parseJwt.getIssuedAt();
		Date d2 = parseJwt.getExpiration();
		System.out.println("令牌签发时间:" + sdf.format(d1));
		System.out.println("令牌过期时间:" + sdf.format(d2));
	}

	@Test
	public void test4() {// 测试JWT的有效时间
		Map claims = new HashMap();
		claims.put("username", "zss");
		String jwt = JwtUtils.createJwt(claims, 3 * 1000L);
		System.out.println(jwt);
		Claims parseJwt = JwtUtils.parseJwt(jwt);
		Date d1 = parseJwt.getIssuedAt();
		Date d2 = parseJwt.getExpiration();
		System.out.println("令牌签发时间:" + sdf.format(d1));
		System.out.println("令牌过期时间:" + sdf.format(d2));
	}

	@Test
	public void test5() {// 三秒后再解析上面过期时间只有三秒的令牌,因为过期则会报错io.jsonwebtoken.ExpiredJwtException
		String oldJwt = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NjI4NTMzMzAsImlhdCI6MTU2Mjg1MzMyNywidXNlcm5hbWUiOiJ6c3MifQ.e098Vj9KBlZfC12QSDhI5lUGRLbNwb27lrYYSL6JwrQ";
		Claims parseJwt = JwtUtils.parseJwt(oldJwt);
		// 过期后解析就报错了,下面代码根本不会执行
		Date d1 = parseJwt.getIssuedAt();
		Date d2 = parseJwt.getExpiration();
		System.out.println("令牌签发时间:" + sdf.format(d1));
		System.out.println("令牌过期时间:" + sdf.format(d2));
	}
}

util层:

CorsFilter:

package com.lihao.vue.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 配置tomcat允许跨域访问
 * 
 * @author Administrator
 *
 */
public class CorsFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	// @Override
	// public void doFilter(ServletRequest servletRequest, ServletResponse
	// servletResponse, FilterChain filterChain)
	// throws IOException, ServletException {
	// HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
	//
	// // Access-Control-Allow-Origin就是我们需要设置的域名
	// // Access-Control-Allow-Headers跨域允许包含的头。
	// // Access-Control-Allow-Methods是允许的请求方式
	// httpResponse.addHeader("Access-Control-Allow-Origin", "*");// *,任何域名
	// httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT,
	// DELETE");
	// // httpResponse.setHeader("Access-Control-Allow-Headers", "Origin,
	// // X-Requested-With, Content-Type, Accept");
	//
	// // 允许请求头Token
	// httpResponse.setHeader("Access-Control-Allow-Headers",
	// "Origin,X-Requested-With, Content-Type, Accept, Token");
	// HttpServletRequest req = (HttpServletRequest) servletRequest;
	// System.out.println("Token=" + req.getHeader("Token"));
	// if("OPTIONS".equals(req.getMethod())) {
	// return;
	// }
	//
	//
	// filterChain.doFilter(servletRequest, servletResponse);
	// }

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletResponse resp = (HttpServletResponse) servletResponse;
		HttpServletRequest req = (HttpServletRequest) servletRequest;

		// Access-Control-Allow-Origin就是我们需要设置的域名
		// Access-Control-Allow-Headers跨域允许包含的头。
		// Access-Control-Allow-Methods是允许的请求方式
		resp.setHeader("Access-Control-Allow-Origin", "*");// *,任何域名
		resp.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
		// resp.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,
		// Content-Type, Accept");
		// 允许客户端,发一个新的请求头jwt
		resp.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With, Content-Type, Accept, jwt");

		// 允许客户端,处理一个新的响应头jwt
		resp.setHeader("Access-Control-Expose-Headers", "jwt");
		// String sss = resp.getHeader("Access-Control-Expose-Headers");
		// System.out.println("sss=" + sss);

		// 允许请求头Token
		// httpResponse.setHeader("Access-Control-Allow-Headers","Origin,X-Requested-With,
		// Content-Type, Accept, Token");
		// System.out.println("Token=" + req.getHeader("Token"));

		if ("OPTIONS".equals(req.getMethod())) {// axios的ajax会发两次请求,第一次提交方式为:option,直接返回即可
			return;
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}

	@Override
	public void destroy() {

	}
}

JsonData:

package com.lihao.vue.util;

import java.io.Serializable;
import java.util.HashMap;

/**
 * 服务器返回给客户端的JSON格式的数据
 *
 */
public class JsonData extends HashMap implements Serializable {

	private static final long serialVersionUID = -8855960778711040221L;
	private int code;
	private String msg;
	private Object result;
	
	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Object getResult() {
		return result;
	}

	public void setResult(Object result) {
		this.result = result;
	}

	public JsonData(int code, String msg, Object result) {
		super();
		this.put("code", code);
		this.put("msg", msg);
		this.put("result", result);
	}

	public JsonData() {
		super();
	}

}

JwtFilter:

package com.lihao.vue.util;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.jsonwebtoken.Claims;

/**
 * * JWT验证过滤器,配置顺序 :CorsFilte-->JwtFilter-->struts2中央控制器
 * 
 * @author Administrator
 *
 */
public class JwtFilter implements Filter {

	// 排除的URL,一般为登陆的URL(请改成自己登陆的URL)
	private static String EXCLUDE = "^/vue/userAction_login\\.action?.*$";

	private static Pattern PATTERN = Pattern.compile(EXCLUDE);

	private boolean OFF = true;// true关闭jwt令牌验证功能

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String path = req.getServletPath();
		if (OFF || isExcludeUrl(path)) {// 登陆直接放行
			chain.doFilter(request, response);
			return;
		}

		// 从客户端请求头中获得令牌并验证
		String jwt = req.getHeader(JwtUtils.JWT_HEADER_KEY);
		Claims claims = this.validateJwtToken(jwt);
		if (null == claims) {
			// resp.setCharacterEncoding("UTF-8");
			resp.sendError(403, "JWT令牌已过期或已失效");
			return;
		} else {
			String newJwt = JwtUtils.copyJwt(jwt, JwtUtils.JWT_WEB_TTL);
			resp.setHeader(JwtUtils.JWT_HEADER_KEY, newJwt);
			chain.doFilter(request, response);
		}
	}

	/**
	 * 验证jwt令牌,验证通过返回声明(包括公有和私有),返回null则表示验证失败
	 */
	private Claims validateJwtToken(String jwt) {
		Claims claims = null;
		try {
			if (null != jwt) {
				claims = JwtUtils.parseJwt(jwt);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return claims;
	}

	/**
	 * 是否为排除的URL
	 * 
	 * @param path
	 * @return
	 */
	private boolean isExcludeUrl(String path) {
		Matcher matcher = PATTERN.matcher(path);
		return matcher.matches();
	}

	// public static void main(String[] args) {
	// String path = "/sys/userAction_doLogin.action?username=zs&password=123";
	// Matcher matcher = PATTERN.matcher(path);
	// boolean b = matcher.matches();
	// System.out.println(b);
	// }

}

JwtUtils :

package com.lihao.vue.util;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * JWT验证过滤器:配置顺序 CorsFilte->JwtUtilsr-->StrutsPrepareAndExecuteFilter
 *
 */
public class JwtUtils {
	/**
	 * JWT_WEB_TTL:WEBAPP应用中token的有效时间,默认30分钟
	 */
	public static final long JWT_WEB_TTL = 30 * 60 * 1000;

	/**
	 * 将jwt令牌保存到header中的key
	 */
	public static final String JWT_HEADER_KEY = "jwt";

	// 指定签名的时候使用的签名算法,也就是header那部分,jjwt已经将这部分内容封装好了。
	private static final SignatureAlgorithm SIGNATURE_ALGORITHM = SignatureAlgorithm.HS256;
	private static final String JWT_SECRET = "f356cdce935c42328ad2001d7e9552a3";// JWT密匙
	private static final SecretKey JWT_KEY;// 使用JWT密匙生成的加密key

	static {
		byte[] encodedKey = Base64.decodeBase64(JWT_SECRET);
		JWT_KEY = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
	}

	private JwtUtils() {
	}

	/**
	 * 解密jwt,获得所有声明(包括标准和私有声明)
	 * 
	 * @param jwt
	 * @return
	 * @throws Exception
	 */
	public static Claims parseJwt(String jwt) {
		Claims claims = Jwts.parser().setSigningKey(JWT_KEY).parseClaimsJws(jwt).getBody();
		return claims;
	}

	/**
	 * 创建JWT令牌,签发时间为当前时间
	 * 
	 * @param claims
	 *            创建payload的私有声明(根据特定的业务需要添加,如果要拿这个做验证,一般是需要和jwt的接收方提前沟通好验证方式的)
	 * @param ttlMillis
	 *            JWT的有效时间(单位毫秒),当前时间+有效时间=过期时间
	 * @return jwt令牌
	 */
	public static String createJwt(Map claims, long ttlMillis) {
		// 生成JWT的时间,即签发时间
		long nowMillis = System.currentTimeMillis();

		// 下面就是在为payload添加各种标准声明和私有声明了
		// 这里其实就是new一个JwtBuilder,设置jwt的body
		JwtBuilder builder = Jwts.builder()
				// 如果有私有声明,一定要先设置这个自己创建的私有的声明,这个是给builder的claim赋值,一旦写在标准的声明赋值之后,就是覆盖了那些标准的声明的
				.setClaims(claims)
				// 设置jti(JWT ID):是JWT的唯一标识,根据业务需要,这个可以设置为一个不重复的值,主要用来作为一次性token,从而回避重放攻击。
				// 可以在未登陆前作为身份标识使用
				.setId(UUID.randomUUID().toString().replace("-", ""))
				// iss(Issuser)签发者,写死
				// .setIssuer("zking")
				// iat: jwt的签发时间
				.setIssuedAt(new Date(nowMillis))
				// 代表这个JWT的主体,即它的所有人,这个是一个json格式的字符串,可放数据{"uid":"zs"}。此处没放
				// .setSubject("{}")
				// 设置签名使用的签名算法和签名使用的秘钥
				.signWith(SIGNATURE_ALGORITHM, JWT_KEY)
				// 设置JWT的过期时间
				.setExpiration(new Date(nowMillis + ttlMillis));

		return builder.compact();
	}

	/**
	 * 复制jwt,并重新设置签发时间(为当前时间)和失效时间
	 * 
	 * @param jwt
	 *            被复制的jwt令牌
	 * @param ttlMillis
	 *            jwt的有效时间(单位毫秒),当前时间+有效时间=过期时间
	 * @return
	 */
	public static String copyJwt(String jwt, Long ttlMillis) {
		Claims claims = parseJwt(jwt);

		// 生成JWT的时间,即签发时间
		long nowMillis = System.currentTimeMillis();

		// 下面就是在为payload添加各种标准声明和私有声明了
		// 这里其实就是new一个JwtBuilder,设置jwt的body
		JwtBuilder builder = Jwts.builder()
				// 如果有私有声明,一定要先设置这个自己创建的私有的声明,这个是给builder的claim赋值,一旦写在标准的声明赋值之后,就是覆盖了那些标准的声明的
				.setClaims(claims)
				// 设置jti(JWT ID):是JWT的唯一标识,根据业务需要,这个可以设置为一个不重复的值,主要用来作为一次性token,从而回避重放攻击。
				// 可以在未登陆前作为身份标识使用
				//.setId(UUID.randomUUID().toString().replace("-", ""))
				// iss(Issuser)签发者,写死
				// .setIssuer("zking")
				// iat: jwt的签发时间
				.setIssuedAt(new Date(nowMillis))
				// 代表这个JWT的主体,即它的所有人,这个是一个json格式的字符串,可放数据{"uid":"zs"}。此处没放
				// .setSubject("{}")
				// 设置签名使用的签名算法和签名使用的秘钥
				.signWith(SIGNATURE_ALGORITHM, JWT_KEY)
				// 设置JWT的过期时间
				.setExpiration(new Date(nowMillis + ttlMillis));
		return builder.compact();
	}
}

PageBean:

package com.lihao.vue.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 分页工具类
 *
 */
public class PageBean {

	private int page = 1;// 页码

	private int rows = 10;// 页大小

	private int total = 0;// 总记录数

	private boolean pagination = true;// 是否分页
	// 获取前台向后台提交的所有参数
	private Map parameterMap;
	// 获取上一次访问后台的url
	private String url;

	/**
	 * 初始化pagebean
	 * 
	 * @param req
	 */
	public void setRequest(HttpServletRequest req) {
		this.setPage(req.getParameter("page"));
		this.setRows(req.getParameter("rows"));
		// 只有jsp页面上填写pagination=false才是不分页
		this.setPagination(!"fasle".equals(req.getParameter("pagination")));
		this.setParameterMap(req.getParameterMap());
		this.setUrl(req.getRequestURL().toString());
	}

	public int getMaxPage() {
		return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
	}

	public int nextPage() {
		return this.page < this.getMaxPage() ? this.page + 1 : this.getMaxPage();
	}

	public int previousPage() {
		return this.page > 1 ? this.page - 1 : 1;
	}

	public PageBean() {
		super();
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public void setPage(String page) {
		this.page = StringUtils.isBlank(page) ? this.page : Integer.valueOf(page);
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public void setRows(String rows) {
		this.rows = StringUtils.isBlank(rows) ? this.rows : Integer.valueOf(rows);
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() {
		return pagination;
	}

	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}

	public Map getParameterMap() {
		return parameterMap;
	}

	public void setParameterMap(Map parameterMap) {
		this.parameterMap = parameterMap;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	/**
	 * 获得起始记录的下标
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
				+ ", parameterMap=" + parameterMap + ", url=" + url + "]";
	}

}

ResponseUtil :

package com.lihao.vue.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

public class ResponseUtil {

	public static void write(HttpServletResponse response,Object o)throws Exception{
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		out.println(o.toString());
		out.flush();
		out.close();
	}
}

StringUtils :

package com.lihao.vue.util;

public class StringUtils {
	// 私有的构造方法,保护此类不能在外部实例化
	private StringUtils() {
	}

	/**
	 * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isBlank(String s) {
		boolean b = false;
		if (null == s || s.trim().equals("")) {
			b = true;
		}
		return b;
	}
	
	/**
	 * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}

}

Web层

ArticleAction:

package com.lihao.vue.web;

import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.opensymphony.xwork2.ModelDriven;
import com.lihao.base.web.BaseAction;
import com.lihao.vue.biz.ArticleBiz;
import com.lihao.vue.entity.Article;
import com.lihao.vue.util.JsonData;
import com.lihao.vue.util.PageBean;
import com.lihao.vue.util.ResponseUtil;

public class ArticleAction extends BaseAction implements ModelDriven
{ private ArticleBiz articleBiz; private Article article = new Article(); public ArticleBiz getArticleBiz() { return articleBiz; } public void setArticleBiz(ArticleBiz articleBiz) { this.articleBiz = articleBiz; } public String list() { PageBean pageBean = new PageBean(); pageBean.setRequest(request); ObjectMapper om = new ObjectMapper(); try { List
list = this.articleBiz.list(article, pageBean); JsonData jsonData = new JsonData(1, "操作成功", list); jsonData.put("pageBean", pageBean); ResponseUtil.write(response, om.writeValueAsString(jsonData)); } catch (Exception e) { e.printStackTrace(); } return null; } public String add() { ObjectMapper om = new ObjectMapper(); try { code = this.articleBiz.save(article); } catch (Exception e) { e.printStackTrace(); code = 0; }finally { JsonData jsonData = new JsonData(code, code == 0 ? "新增失败" : "新增成功", code); try { ResponseUtil.write(response, om.writeValueAsString(jsonData)); } catch (Exception e) { e.printStackTrace(); } } return null; } public String edit() { ObjectMapper om = new ObjectMapper(); try { code = this.articleBiz.edit(article); } catch (Exception e) { e.printStackTrace(); code = 0; }finally { JsonData jsonData = new JsonData(code, code == 0 ? "修改失败" : "修改成功", code); try { ResponseUtil.write(response, om.writeValueAsString(jsonData)); } catch (Exception e) { e.printStackTrace(); } } return null; } public String del() { ObjectMapper om = new ObjectMapper(); try { this.articleBiz.del(article); code = 1; } catch (Exception e) { e.printStackTrace(); code = 0; }finally { JsonData jsonData = new JsonData(code, code == 0 ? "删除失败" : "删除成功", code); try { ResponseUtil.write(response, om.writeValueAsString(jsonData)); } catch (Exception e) { e.printStackTrace(); } } return null; } @Override public Article getModel() { return article; } }

TreeNodeAction:

package com.lihao.vue.web;

import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lihao.base.web.BaseAction;
import com.lihao.vue.biz.TreeNodeBiz;
import com.lihao.vue.entity.TreeNode;
import com.lihao.vue.util.JsonData;
import com.lihao.vue.util.ResponseUtil;

public class TreeNodeAction extends BaseAction{

	private static final long serialVersionUID = 1L;
	private TreeNodeBiz treeNodeBiz;
	
	
	public TreeNodeBiz getTreeNodeBiz() {
		return treeNodeBiz;
	}


	public void setTreeNodeBiz(TreeNodeBiz treeNodeBiz) {
		this.treeNodeBiz = treeNodeBiz;
	}


	public String execute() {
		ObjectMapper om = new ObjectMapper();
		List list = this.treeNodeBiz.list();
		JsonData jsonData = new JsonData(1, "操作成功", list);
		try {
			ResponseUtil.write(response, om.writeValueAsString(jsonData));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}

UserAction:

package com.lihao.vue.web;

import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.opensymphony.xwork2.ModelDriven;
import com.lihao.base.web.BaseAction;
import com.lihao.vue.biz.UserBiz;
import com.lihao.vue.entity.User;
import com.lihao.vue.util.JsonData;
import com.lihao.vue.util.JwtUtils;
import com.lihao.vue.util.PageBean;
import com.lihao.vue.util.ResponseUtil;
import com.lihao.vue.util.StringUtils;

public class UserAction extends BaseAction implements ModelDriven{

	private UserBiz userBiz;
	private User user = new User();

	public UserBiz getUserBiz() {
		return userBiz;
	}

	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}
	 
	public String login() {
		ObjectMapper om = new ObjectMapper();
		JsonData jsonData = null;
		try {
			if(StringUtils.isBlank(user.getUname()) || StringUtils.isBlank(user.getPwd())) {
				jsonData = new JsonData(0, "用户或者密码为空", user);
			}else {
				User u = this.userBiz.login(user);
//				Map claims = new HashMap();
//				claims.put("uname",user.getUname());
//				claims.put("pwd", user.getPwd());
//				String jwt = JwtUtils.createJwt(claims, JwtUtils.JWT_WEB_TTL);
//				response.setHeader(JwtUtils.JWT_HEADER_KEY, jwt);
				jsonData = new JsonData(1, "登录成功", u);
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsonData = new JsonData(0, "用户或者密码错误", user);
		}finally {
			try {
				ResponseUtil.write(response, om.writeValueAsString(jsonData));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return null;
	}
	
	public String getAsyncData() {
		ObjectMapper om = new ObjectMapper();
		try {
			Thread.sleep(6000);
			ResponseUtil.write(response, om.writeValueAsString("http://www.javaxl.com"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public User getModel() {
		return user;
	}
}

配置文件

spring-vue.xml




	
	
		
	
	
		
	
	

	
	
		
	
	
		
	


	
	
		
	
	
		
	



struts-vue.xml




	
		
		
		
		
		
		
	

pom.xml:


  4.0.0
  com.lihao
  T244_SSH
  war
  0.0.1-SNAPSHOT
  T244_SSH Maven Webapp
  http://maven.apache.org
  
		5.2.12.Final
		5.1.44
		5.0.1.RELEASE
		2.5.13
		1.7.7
		2.9.1
		3.2.0
		4.12
		4.0.0
		1.2
		1.1.2
		8.0.47
		1.7.6
		2.6.0
		2.9.3
	
  
  
    
		
			org.hibernate
			hibernate-core
			${hibernate.version}
		
		
			org.hibernate
			hibernate-c3p0
			${hibernate.version}
		
		
			org.hibernate
			hibernate-ehcache
			${hibernate.version}
		
		
			mysql
			mysql-connector-java
			${mysql.version}
		
		
		
		
			org.springframework
			spring-context
			${spring.version}
		
		
			org.springframework
			spring-orm
			${spring.version}
		
		
			org.springframework
			spring-web
			${spring.version}
		
		
			org.springframework
			spring-aspects
			${spring.version}
		
		
		
		
			org.apache.struts
			struts2-core
			${struts2.version}
		
		
			org.apache.struts
			struts2-spring-plugin
			${struts2.version}
		
		
		
		
		
		
			org.slf4j
			slf4j-api
			${slf4j.version}
		
		
			org.slf4j
			jcl-over-slf4j
			${slf4j.version}
			runtime
		

		
		
			org.apache.logging.log4j
			log4j-slf4j-impl
			${log4j2.version}
		

		
		
			org.apache.logging.log4j
			log4j-api
			${log4j2.version}
		
		
			org.apache.logging.log4j
			log4j-core
			${log4j2.version}
		

		
		
			org.apache.logging.log4j
			log4j-web
			${log4j2.version}
			runtime
		
		
		
			com.lmax
			disruptor
			${disruptor.version}
		
		
		
		
		
			junit
			junit
			${junit.version}
			test
		
		
		
    
		
			javax.servlet
			javax.servlet-api
			${javax.servlet.version}
			provided
		
    
    
		
			jstl
			jstl
			${jstl.version}
		
		
			taglibs
			standard
			${standard.version}
		
    
    
		
			org.apache.tomcat
			tomcat-jsp-api
			${tomcat-jsp-api.version}
		

		
			org.apache.axis2
			axis2
			${axis2.version}
			pom
		
		
			org.apache.axis2
			axis2-transport-http
			${axis2.version}
		
		
			org.apache.axis2
			axis2-transport-local
			${axis2.version}
		
				
		
			org.apache.axis2
			axis2-spring
			${axis2.version}
		
		
			org.apache.axis2
			axis2-adb
			${axis2.version}
		
		
		
			org.apache.xmlbeans
			xmlbeans
			${xmlbeans.version}
		
		

		
			com.fasterxml.jackson.core
			jackson-databind
			${jackson.version}
		
		
			com.fasterxml.jackson.core
			jackson-core
			${jackson.version}
		
		
			com.fasterxml.jackson.core
			jackson-annotations
			${jackson.version}
		
		
		
			io.jsonwebtoken
			jjwt
			0.9.1
		
		
			com.auth0
			java-jwt
			3.4.0
		
    
    
  
  
    T244_SSH
    
			
				org.apache.maven.plugins
				maven-compiler-plugin
				3.7.0
				
					1.8
					1.8
					UTF-8
				
			
		
    
  


web.xml:


  Archetype Created Web Application
	

	
		contextConfigLocation
		classpath:spring-context.xml
	
	
		
			org.springframework.web.context.ContextLoaderListener
		
	
	
	
		corsFilter
		com.lihao.vue.util.CorsFilter
	
	
		corsFilter
		/*
	
	
	
		jwtFilter
		com.lihao.vue.util.JwtFilter
	
	
		jwtFilter
		/*
	
	
	
		struts2
		
			org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
		
	
	
		struts2
		*.action
	

	
	
		encodingFilter
		
			org.springframework.web.filter.CharacterEncodingFilter
		
		true
		
			encoding
			UTF-8
		
	
	
		encodingFilter
		/*
	

你可能感兴趣的:(前篇所需后端代码)