SPA后台数据准备-ssh整合增删改查

文章目录

  • 1.准备ssh整合(spring+hibernate+struts)
  • 2.目标
  • 3.案例treeNode和user
    • 思路
      • pom.xml
      • User
      • user.hbm.xml
      • baseDao
      • UserDao
      • UserBiz
      • UserBizImpl
      • UserAction
      • spring-user.xml
      • struts-sy.xml
      • spring-hibernate.xml
      • spring-context.xml
  • 4.ssh所遇到的异常解决

1.准备ssh整合(spring+hibernate+struts)

点击查看ssh整合的博客

2.目标

http://localhost:8080/T216_SSH/vue/userAction_login.action
{"msg":"登录成功","result":{"uname":"zs","pwd":"123"},"code":1}

http://localhost:8080/T216_SSH/vue/treeNodeAction.action
{"msg":"操作成功","result":[{"treeNodeId":1,"treeNodeName":"系统管理","treeNodeType":1,"url":null,"position":1,"icon":"el-icon-setting","children":[{"treeNodeId":2,"treeNodeName":"用户管理","treeNodeType":2,"url":"/sys/VuexPage1","position":2,"icon":"el-icon-user","children":[]},{"treeNodeId":3,"treeNodeName":"角色管理","treeNodeType":2,"url":"/sys/VuexPage2","position":3,"icon":"","children":[]},{"treeNodeId":4,"treeNodeName":"密码修改","treeNodeType":2,"url":null,"position":4,"icon":null,"children":[]}]},{"treeNodeId":5,"treeNodeName":"论坛管理","treeNodeType":1,"url":null,"position":5,"icon":"el-icon-reading","children":[{"treeNodeId":6,"treeNodeName":"文章管理","treeNodeType":2,"url":"/sys/Articles","position":6,"icon":null,"children":[]}]}],"code":1}


http://localhost:8080/T216_SSH/vue/articleAction_list.action
{"msg":"操作成功","result":[{"id":1,"title":"MySQL Tutorial","body":"DBMS stands for DataBase ..."},{"id":2,"title":"How To Use MySQL Efficiently","body":"After you went through a ..."},{"id":3,"title":"Optimising MySQL","body":"In this tutorial we will show ..."},{"id":4,"title":"1001 MySQL Tricks","body":"1. Never run mysqld as root. 2. ..."},{"id":5,"title":"MySQL vs. YourSQL","body":"In the following database comparison ..."},{"id":6,"title":"MySQL Security","body":"When configured properly, MySQL ..."},{"id":8,"title":"阿里与拼多多的增量之战","body":"近日,多家媒体报道阿里内部正考虑将聚划算彻底从淘宝天猫独立出来,成立大聚划算事业群。据传独立后的聚划算将肩负起阿里进攻下沉市场、迎战拼多多的重任"},{"id":9,"title":"lucene工具类","body":"package com.javaxl.p1.utils;\n\nimport java.io.IOException;\nimport java.nio.file.Paths;\n\nimport org.apache.lucene.analysis.Analyzer;\nimport org.apache.lucene"},{"id":10,"title":"lucene案例","body":"对某一表进行索引操作的帮助类package com.javaxl.p1.component;\n\nimport com.javaxl.p1.entity.Blog;\nimport com.javaxl.p1.service.BlogService;\nimport com.javaxl.p1.utils.Date"},{"id":15,"title":"solr简介","body":"solr简单了解下,相较于lucene好处在哪里"}],"code":1,"pageBean":{"page":1,"rows":10,"total":155,"pagination":true,"parameterMap":{},"url":"http://localhost:8080/T216_SSH/vue/articleAction_list.action","startIndex":0,"maxPage":16}}


http://localhost:8080/T216_SSH/vue/articleAction_add.action
{"msg":"新增成功","result":169,"code":169}


http://localhost:8080/T216_SSH/vue/articleAction_edit.action
{"msg":"修改成功","result":4,"code":4}


http://localhost:8080/T216_SSH/vue/articleAction_del.action
{"msg":"删除失败","result":0,"code":0}

3.案例treeNode和user

SPA后台数据准备-ssh整合增删改查_第1张图片
SPA后台数据准备-ssh整合增删改查_第2张图片

思路

pom.xml
entity
实体类的映射类文件
basedao
dao
biz
bizImpl
web层
spring-xxx.xml(spring-bean文件)
spring-hibernate.xml
spring-context.xml

pom.xml

重点要导json的依赖

	
		
			com.fasterxml.jackson.core
			jackson-databind
			2.2.3
		

完整案例


	4.0.0
	com.wxm
	SSH
	war
	0.0.1-SNAPSHOT
	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
	
	
		
		
			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}
		
		
		
			com.fasterxml.jackson.core
			jackson-databind
			2.2.3
		
	
	
		SSH
		
			
				org.apache.maven.plugins
				maven-compiler-plugin
				3.7.0
				
					1.8
					1.8
					UTF-8
				
			
		
	


User

package com.wxm.user.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;
}

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

public User() {
	super();
}

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

user.hbm.xml




	
		 
			
		 
		
		
	

baseDao

package com.wxm.util;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

/**
 * 基于hibernate的baseDao
 *
 */

public class BaseDao extends HibernateDaoSupport implements Serializable{

	private static final long serialVersionUID = 5427369434249665701L;
	
	public void setParam(Query query,Map map) {
		if(map == null || map.size() < 1) {
			return;
		}
		Object value = null;
		for(Map.Entry entry:map.entrySet()) {
			value = entry.getValue();
			if(value instanceof Collection) {
				query.setParameterList(entry.getKey(), (Collection) value);
			}else if(value instanceof Object[]) {
				query.setParameterList(entry.getKey(), (Object[]) value);
			}else {
				query.setParameter(entry.getKey(), value);
			}
		}
	}
	
	public String getCountHql(String hql) {
		int index = hql.toUpperCase().indexOf("FROM");
		return "select count(*) "+hql.substring(index);
	}
	
	/**
	 * 
	 * @param hql	已经拼装好的
	 * @param map
	 * @param pageBean
	 * @return
	 */
	public List executeQuery(Session session, String hql,Map map,PageBean pageBean) {
		if(pageBean !=null && pageBean.isPagination()) {
			String countHql = getCountHql(hql);
			Query countQuery = session.createQuery(countHql);
			this.setParam(countQuery, map);
			pageBean.setTotal(countQuery.getSingleResult().toString());
			
			Query query = session.createQuery(hql);
			this.setParam(query, map);
			query.setFirstResult(pageBean.getStartIndex());
			query.setMaxResults(pageBean.getRows());
			List list = query.list();
			
			return list;
		}else {
			Query query = session.createQuery(hql);
			this.setParam(query, map);
			List list = query.list();
			
			return list;
		}
		
	}

}


UserDao

package com.wxm.user.dao;

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

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

import com.wxm.user.entity.User;
import com.wxm.util.BaseDao;
import com.wxm.util.PageBean;
import com.wxm.util.StringUtils;

import freemarker.template.utility.StringUtil;

public class UserDao extends BaseDao {

	private static final long serialVersionUID = 1L;

	public List login(User user) {
		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,null);
			}

		});

	}

}

UserBiz

package com.wxm.user.biz;



import java.util.List;

import com.wxm.user.entity.User;
import com.wxm.util.PageBean;


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



UserBizImpl

package com.wxm.user.impl;

import java.util.List;

import com.wxm.user.biz.UserBiz;
import com.wxm.user.dao.UserDao;
import com.wxm.user.entity.User;
import com.wxm.util.PageBean;


public class UserBizImpl implements UserBiz{
    private UserDao userDao;
    
	public UserDao getUserDao() {
		return userDao;
	}

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

	@Override
	public List login(User user) {
		// TODO Auto-generated method stub
		return this.userDao.login(user);
	}

	




}


UserAction

package com.wxm.user.web;

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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.opensymphony.xwork2.ModelDriven;
import com.wxm.user.biz.UserBiz;
import com.wxm.user.entity.User;
import com.wxm.util.BaseAction;
import com.wxm.util.ResponseUtil;

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;
	}

	@Override
	public User getModel() {
		// TODO Auto-generated method stub
		return user;
	}

	public String login() throws JsonProcessingException, Exception {
		List login = userBiz.login(user);
		if (login.size() == 1) {
			this.code = 1;
			this.msg = "登录成功!!欢迎尊敬的xxx用户";
			this.result = login;
		} else {
			this.code = 0;
			this.msg = "登录失败";
			this.result = login;
		}
		Map map = new HashMap();
		ObjectMapper om = new ObjectMapper();
		map.put("msg", msg);
		map.put("result", result);
		map.put("code", code);
		ResponseUtil.write(response, om.writeValueAsString(map));

		return SUCCESS;
	}
	/*
	 * 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-user.xml




  
  
  
     
  
  
  
  


struts-sy.xml




	
		
		
			/index.jsp
		
		
			/index.jsp
		
	

spring-hibernate.xml

注册实体映射文件


		
			
				com/wxm/user/entity/User.hbm.xml
			
		

完整案例




	
	
	
	
	

	
	
		
		
		
		

		
		
		
		
		
		
		
		

		
		

		
		

		
		

		
		

		
		

		
		
	

	
	
		
		
			
		
		
		
			
				org.hibernate.dialect.MySQLDialect
				
				true
				true
			
		
		
		
			
				com/wxm/entity/Book.hbm.xml
				com/wxm/user/entity/User.hbm.xml
				com/wxm/TreeNode/entity/TreeNode.hbm.xml

			
		
	

	
	
	

	
	

	
	
		
	

	
	
		
			
			
			

			
			

			
			

			
			
			
			

			
		
	

	
	
		
		
		
		
		
		
	
	

	
	
		
	
	
	
	
		
	
	
	


spring-context.xml

引入实体类的映射文件

	

完整案例




	
	
	
  

效果
访问地址

http://localhost:8080/SSH/sy/user_login.action

效果在这里插入图片描述

http://localhost:8080/SSH/sy/treeNode_list.action

在这里插入图片描述
这里TreeNode一样的按思路来写就可以,无太大变动,需注意该对应的类路径,和类名下面写了很多异常的解决方法可以参考

4.ssh所遇到的异常解决

异常 解决
1.java.lang.IllegalStateException: BeanFactory not initialized or already closed - call ‘refresh’ before accessing beans via the ApplicationContext 解决:显而易见 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml"); ("/spring-context.xml")没填
2.org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘bookProxy’: FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘myMethodInterceptor’ at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:175) 解决:spring-context.xml里的bean配置核对后发现MyMethodInterceptor里返回为null(就是说忘记填写了)
3.连接池Exception in thread "C3P0PooledConnectionPoolManager[identityToken->1hge9k5a5g18ogr12lnisg 2622e23c]-AdminTaskTimer" java.lang.NoClassDefFoundError: com/mchange/v2/resourcepool/BasicResourcePool$AsyncTestIdleResourceTask
4.org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class path resource [spring-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.PropertyNotFoundException: Could not locate getter method for property [com.wxm.user.entity.User#bame](X2) 解决:实体类的映射类(比如book.hbm.xml文件对应的属性不一致)
5.org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘treeNodeBiz’ defined in class path resource [spring-tree.xml]: Cannot resolve reference to bean ‘treeNodeDao’ while setting bean property ‘treeNodeDao’; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘treeNodeDao’ available 解决:[spring-tree.xml的id对应要正确不知道可以问度娘spring的ioc的相关内容
6. org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in class path resource [spring-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: entity class not found: com.wxm.entity.Book 解决:强调!!!在路径正确的情况下,刷新项目,然后projecet-> clean ,project-> bulid project,重新部署项目
7.org.springframework.orm.hibernate5.HibernateSystemException: Null value was assigned to a property of primitive type setter of com.wxm.TreeNode.entity.TreeNode.parent_node_id; nested exception is org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of com.wxm.TreeNode.entity.TreeNode.parent_node_id 原因:持久化类中使用int定义某个字段,字段又被默认为null。 解决方法:你的持久类里别用int类型,用Integer类型。因为Integer是可以被赋给null的,但int不行。
8.java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: form near line 1, column 1 [form TreeNode] 解决:仔细检查:是hql语句写错了 关键词from
9.HQL java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: form near line 1, column 1 [form TreeNode] 解决:仔细检查:是hql语句写错了 关键词from
10.org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet 解决:实体类的映射类对应属性的主键策略id对应错误

你可能感兴趣的:(#,spring,框架报错总结,#,SSH)