关于session获取j对象

想要if else判断s3是否>=0跳转到postive.jsp或者negative.jsp 下边代码哪里错了
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


My JSP 'sum.jsp' starting page
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->


<%

response.setCharacterEncoding("UTF-8");
//String str1=request.getParameter("shuju1");
//String str2=request.getParameter("shuju2");
String str1=(String)session.getAttribute("shuju1");
String str2=(String)session.getAttribute("shuju2");
//double s1=Double.parseDouble(str1);
//double s2=Double.parseDouble(str2);
//double s3=s1+s2;
double s1=Double.parseDouble(str1);
double s2=Double.parseDouble(str2);
double s3=s1+s2;
session.setAttribute("str1","s1");
session.setAttribute("str2","s2");
session.setAttribute("str3","s3");
//request.setAttribute("st1",s1);
//request.setAttribute("st2",s2);
//request.setAttribute("st3",s3);
    if(s3>0){
            response.sendRedirect("postive.jsp");

    }else{
            response.sendRedirect("negative.jsp");
    }

%>

这是sum.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


My JSP 'input.jsp' starting page
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->



整数1:

整数2:




这是input.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>My JSP 'postive.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->


利用getAttribute方法获取利用setAttribute方法保存的值,并显示!

<%
Double a1=(Double)session.getAttribute("st1");
Double a2=(Double)session.getAttribute("st2");
Double a3=(Double)session.getAttribute("st3");
%>
<%=a1%>+<%=a2%>=<%=a3%>

利用getParameter方法获取获取请求参数,并显示!

<% //String s1=session.getParameter("shuju1");
//String s2=session.getParameter("shuju2");
String s1=(String)session.getAttribute("shuju1");
String s2=(String)session.getAttribute("shuju2");
%>

<%=s1%>+<%=s2%>=<%=a3%>

结果为正!


这是postive.jsp

8个回答

楼主你的这个问题其实很简单,应该是你刚开始学jsp的原因。
input.jsp中有一个form,两个input的name分别为shuju1,shuju1
这个form的action为sum.jsp
sum中应该写

 String str1=request.getParameter("shuju1");
String str2=request.getParameter("shuju2");
double s1=Double.parseDouble(str1);
double s2=Double.parseDouble(str2);
double s3=s1+s2;
session.setAttribute("st1",s1);
session.setAttribute("st2",s2);
session.setAttribute("st3",s3);
if(s3>0){
    response.sendRedirect("postive.jsp");
}else{
    response.sendRedirect("negative.jsp");
}

postive.jsp里面再取session里的值就是了啊

 Double a1=(Double)session.getAttribute("st1");
Double a2=(Double)session.getAttribute("st2");
Double a3=(Double)session.getAttribute("st3");
weixin_38486417
Brandon0824 万分谢谢!问题搞懂了!
2 年多之前 回复

HTTP Status 500 - An exception occurred processing JSP page /sum.jsp at line 30

type Exception report

message An exception occurred processing JSP page /sum.jsp at line 30

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: An exception occurred processing JSP page /sum.jsp at line 30

27: //double s1=Double.parseDouble(str1);
28: //double s2=Double.parseDouble(str2);
29: //double s3=s1+s2;
30: double s1=Double.parseDouble(str1);
31: double s2=Double.parseDouble(str2);
32: double s3=s1+s2;
33: session.setAttribute("str1","s1");

这是错误提示

是不是没有先获取session的原因

zjq_1314520
片刻清夏 回复weixin_38486417: 你把值在js代码中存储进去看看!
2 年多之前 回复
weixin_38486417
Brandon0824 回复片刻清夏: 因为session没有像request那样getParameter的方法...所以不知道怎么在sum.jsp获取到input.jsp输入的两个值...
2 年多之前 回复
zjq_1314520
片刻清夏 session是内置对象,应该不用获取,我感觉是没有往session里面设置值,或者设置错误。
2 年多之前 回复
weixin_38486417
Brandon0824 请问要在哪一步获取呢?不是直接session.getAttributr就可以吗?
2 年多之前 回复

"shuju1","shuju1"有设值吗

weixin_38486417
Brandon0824 shuju1通过键盘在input.jsp输入值
2 年多之前 回复

session里的"shuju1","shuju2",只看到你get了,没看到你啥时候set的,直接parseDouble不就NullPointerException了

baokx
一缕清风007 回复weixin_38486417: 先用request.getParameter()获取到值,然后再session.setAttribute()进去啊
2 年多之前 回复
weixin_38486417
Brandon0824 可是session没有getParameter的方法,请教一下要怎么获值呢?
2 年多之前 回复

input.jsp中,通过Java代码把输入的值存储到session中去(session.setAttribute()),由于session的作用域比较广,所以能在sum.jsp通过getAttribute方法得到。

weixin_38486417
Brandon0824 谢谢 明白了
2 年多之前 回复

你set属性的时候不需要加双引号吧,session.setAttribute("str1",s1);就是后面的这个不需要吧!

weixin_38486417
Brandon0824 是的
2 年多之前 回复

多看看jsp这方面的知识。。。。。。。。。。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
SSH2框架 我想用ognl标签获取另一对象的属性!

Goodsinfo.java ``` package ssh2.jxc.wjr.vo; import java.util.HashSet; import java.util.Set; /** * Goodsinfo entity. @author MyEclipse Persistence Tools */ public class Goodsinfo implements java.io.Serializable { // Fields private Integer gid; private Goodsclassinfo goodsclassinfo; private String gname; private Integer gamount; private String gunit; private Double gpin; private Double gpout; private Set selldetails = new HashSet(0); private Set consumerbackdetails = new HashSet(0); private Set providerbackdetails = new HashSet(0); private Set stockdetails = new HashSet(0); // Constructors /** default constructor */ public Goodsinfo() { } /** minimal constructor */ public Goodsinfo(Goodsclassinfo goodsclassinfo, Integer gamount) { this.goodsclassinfo = goodsclassinfo; this.gamount = gamount; } /** full constructor */ public Goodsinfo(Goodsclassinfo goodsclassinfo, String gname, Integer gamount, String gunit, Double gpin, Double gpout, Set selldetails, Set consumerbackdetails, Set providerbackdetails, Set stockdetails) { this.goodsclassinfo = goodsclassinfo; this.gname = gname; this.gamount = gamount; this.gunit = gunit; this.gpin = gpin; this.gpout = gpout; this.selldetails = selldetails; this.consumerbackdetails = consumerbackdetails; this.providerbackdetails = providerbackdetails; this.stockdetails = stockdetails; } // Property accessors public Integer getGid() { return this.gid; } public void setGid(Integer gid) { this.gid = gid; } public Goodsclassinfo getGoodsclassinfo() { return this.goodsclassinfo; } public void setGoodsclassinfo(Goodsclassinfo goodsclassinfo) { this.goodsclassinfo = goodsclassinfo; } public String getGname() { return this.gname; } public void setGname(String gname) { this.gname = gname; } public Integer getGamount() { return this.gamount; } public void setGamount(Integer gamount) { this.gamount = gamount; } public String getGunit() { return this.gunit; } public void setGunit(String gunit) { this.gunit = gunit; } public Double getGpin() { return this.gpin; } public void setGpin(Double gpin) { this.gpin = gpin; } public Double getGpout() { return this.gpout; } public void setGpout(Double gpout) { this.gpout = gpout; } public Set getSelldetails() { return this.selldetails; } public void setSelldetails(Set selldetails) { this.selldetails = selldetails; } public Set getConsumerbackdetails() { return this.consumerbackdetails; } public void setConsumerbackdetails(Set consumerbackdetails) { this.consumerbackdetails = consumerbackdetails; } public Set getProviderbackdetails() { return this.providerbackdetails; } public void setProviderbackdetails(Set providerbackdetails) { this.providerbackdetails = providerbackdetails; } public Set getStockdetails() { return this.stockdetails; } public void setStockdetails(Set stockdetails) { this.stockdetails = stockdetails; } } ``` Goodsclassinfo.java ``` package ssh2.jxc.wjr.vo; import java.util.HashSet; import java.util.Set; /** * Goodsclassinfo entity. @author MyEclipse Persistence Tools */ public class Goodsclassinfo implements java.io.Serializable { // Fields private Integer gcid; private String gcname; private Set goodsinfos = new HashSet(0); // Constructors /** default constructor */ public Goodsclassinfo() { } /** minimal constructor */ public Goodsclassinfo(String gcname) { this.gcname = gcname; } /** full constructor */ public Goodsclassinfo(String gcname, Set goodsinfos) { this.gcname = gcname; this.goodsinfos = goodsinfos; } // Property accessors public Integer getGcid() { return this.gcid; } public void setGcid(Integer gcid) { this.gcid = gcid; } public String getGcname() { return this.gcname; } public void setGcname(String gcname) { this.gcname = gcname; } public Set getGoodsinfos() { return this.goodsinfos; } public void setGoodsinfos(Set goodsinfos) { this.goodsinfos = goodsinfos; } } ``` GoodsinfoDAO.java ``` package ssh2.jxc.wjr.dao.impl; import java.util.List; import java.util.Set; import javax.annotation.Resource; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import ssh2.jxc.wjr.dao.IGoodsinfoDAO; import ssh2.jxc.wjr.vo.Goodsinfo; /** * A data access object (DAO) providing persistence and search support for * Goodsinfo entities. Transaction control of the save(), update() and delete() * operations can directly support Spring container-managed transactions or they * can be augmented to handle user-managed Spring transactions. Each of these * methods provides additional information for how to configure it for the * desired type of transaction control. * * @see ssh2.jxc.wjr.vo.Goodsinfo * @author MyEclipse Persistence Tools */ @Repository public class GoodsinfoDAO extends HibernateDaoSupport implements IGoodsinfoDAO { private static final Logger log = LoggerFactory .getLogger(GoodsinfoDAO.class); // property constants public static final String GNAME = "gname"; public static final String GAMOUNT = "gamount"; public static final String GUNIT = "gunit"; public static final String GPIN = "gpin"; public static final String GPOUT = "gpout"; @Resource public void setSessionFactoryOverride(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } protected void initDao() { // do nothing } public void save(Goodsinfo transientInstance) { log.debug("saving Goodsinfo instance"); try { getHibernateTemplate().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(Goodsinfo persistentInstance) { log.debug("deleting Goodsinfo instance"); try { getHibernateTemplate().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public Goodsinfo findById(java.lang.Integer id) { log.debug("getting Goodsinfo instance with id: " + id); try { Goodsinfo instance = (Goodsinfo) getHibernateTemplate().get( "ssh2.jxc.wjr.vo.Goodsinfo", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(Goodsinfo instance) { log.debug("finding Goodsinfo instance by example"); try { List results = getHibernateTemplate().findByExample(instance); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding Goodsinfo instance with property: " + propertyName + ", value: " + value); try { String queryString = "from Goodsinfo as model where model." + propertyName + "= ?"; return getHibernateTemplate().find(queryString, value); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByGname(Object gname) { return findByProperty(GNAME, gname); } public List findByGamount(Object gamount) { return findByProperty(GAMOUNT, gamount); } public List findByGunit(Object gunit) { return findByProperty(GUNIT, gunit); } public List findByGpin(Object gpin) { return findByProperty(GPIN, gpin); } public List findByGpout(Object gpout) { return findByProperty(GPOUT, gpout); } public List findAll() { log.debug("finding all Goodsinfo instances"); try { String queryString = "from Goodsinfo"; return getHibernateTemplate().find(queryString); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public Goodsinfo merge(Goodsinfo detachedInstance) { log.debug("merging Goodsinfo instance"); try { Goodsinfo result = (Goodsinfo) getHibernateTemplate().merge( detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(Goodsinfo instance) { log.debug("attaching dirty Goodsinfo instance"); try { getHibernateTemplate().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Goodsinfo instance) { log.debug("attaching clean Goodsinfo instance"); try { getHibernateTemplate().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public static IGoodsinfoDAO getFromApplicationContext(ApplicationContext ctx) { return (IGoodsinfoDAO) ctx.getBean("GoodsinfoDAO"); } //获取全部商品信息 @Override public List getGoodsinfos() { String hql="from Goodsinfo"; Session session=getHibernateTemplate().getSessionFactory().openSession(); Query query=session.createQuery(hql); List<Goodsinfo> goodsinfos=query.list(); //test System.out.println(goodsinfos.iterator().next().getGoodsclassinfo().getGcname()); session.close(); return goodsinfos; } } ``` goodsmanger.jsp ``` <s:iterator value="#request['goodsinfos']" id="goodsinfos" status="iteratorStatus"> <s:if test="!#iteratorStatus.odd"> <tr bgcolor="white" align="center"> <td><s:property value="#goodsinfos.gname" /></td><!-- 显示商品名称 --> <td><s:property value="#goodsinfos.goodsclassinfos" /></td><!-- 显示商品类别 --> <td>¥<s:property value="#goodsinfos.gpin" /></td><!-- 进价 --> <td>¥<s:property value="#goodsinfos.gpout" /></td><!-- 售价 --> <td><s:property value="#goodsinfos.gunit" /></td><!-- 计价单位 --> <td><s:property value="#goodsinfos.gamount" /></td><!-- 商品数量 --> <td width="120"> gid:<s:property value="gid" /> <a href="#" target="mainFrame"> <img border="0" src="img/mod.gif" height="16" width="16"/>查看/修改 </a> </td> <td width="100"> <a href="#"> <img border="0" src="img/del.gif"/>删除 </a> </td> </tr> </s:if> ``` 我的思路是 List goodsinfo 存到 Map request 在页面上就可以获取到 goodsinfo类的属性值, 就是没有办法获取到商品类别(<td><s:property value="#goodsinfos.goodsclassinfos" /></td><!-- 显示商品类别 -->:没有办法显示) 问题所在:可以获取到对象 goodsinfos (List)里面的每一个对象goodsinfo里面的属性。 就是获取不到 goodsclassinfo的属性的gcname。 我使用的这段代码可以获取到 商品的类别 截取 ``` System.out.println(goodsinfos.iterator().next().getGoodsclassinfo().getGcname()); ``` 求解?

c3p0连接池中获取的Connection对象的close()方法是真的把连接给关闭了?

自己做写了一个管理数据源的DBManager,构想中从数据源里面获取的Connection使用完之后执行close()方法,然后把Connection对象闲置回连接池中。 但是测试出来的结果好像每次执行close()之后connection就销毁了。 代码如下: DBManager.java -------------- package ben.DBUtils; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.HashMap; import java.util.HashSet; import java.util.Properties; import java.util.Set; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.apache.log4j.Logger; /** * Created with IntelliJ IDEA. * User: Ben * Date: 13-7-3 * Time: 下午5:06 * To change this template use File | Settings | File Templates. */ public class DBManager { //保存数据库连接池的容器 private static HashMap<String, ComboPooledDataSource> datasourceMap = new HashMap<String, ComboPooledDataSource>(); private final static ThreadLocal<Connection> conns = new ThreadLocal<Connection>(); private static Logger logger = Logger.getLogger(DBManager.class); static { InitDataSource(null); } /** * 初始化连接池 * */ private final static void InitDataSource(Properties dbProperties){ try{ if (dbProperties == null){ dbProperties = new Properties(); dbProperties.load(DBManager.class.getClassLoader().getResourceAsStream("dbInfo.properties")); } //获取数据源名称 Set<String> keys = new HashSet<String>(); for (Object key : dbProperties.keySet()){ String skey = (String)key; Integer point = skey.indexOf("."); keys.add(skey.substring(0, point)); } //实例化DataSource并放入容器中 for (String key : keys) { ComboPooledDataSource ds = new ComboPooledDataSource(); ds.setDriverClass(dbProperties.getProperty(key + "." + "Driver")); ds.setJdbcUrl(dbProperties.getProperty(key + "." + "Url")); ds.setUser(dbProperties.getProperty(key + "." + "User")); ds.setPassword(dbProperties.getProperty(key + "." + "Password")); ds.setMaxPoolSize(Integer.parseInt(dbProperties.getProperty(key + "." + "MaxPoolSize"))); ds.setMinPoolSize(Integer.parseInt(dbProperties.getProperty(key + "." + "MinPoolSize"))); ds.setMaxIdleTime(Integer.parseInt(dbProperties.getProperty(key + "." + "MaxIdleTime"))); ds.setInitialPoolSize(Integer.parseInt(dbProperties.getProperty(key + "." + "InitialPoolSize"))); ds.setAcquireIncrement(Integer.parseInt(dbProperties.getProperty(key + "." + "AcquireIncrement"))); ds.setAcquireRetryAttempts(Integer.parseInt(dbProperties.getProperty(key + "." + "AcquireRetryAttempts"))); ds.setAcquireRetryDelay(Integer.parseInt(dbProperties.getProperty(key + "." + "AcquireRetryDelay"))); ds.setMaxStatements(Integer.parseInt(dbProperties.getProperty(key + "." + "MaxStatements"))); ds.setIdleConnectionTestPeriod(Integer.parseInt(dbProperties.getProperty(key + "." + "IdleConnectionTestPeriod"))); ds.setCheckoutTimeout(Integer.parseInt(dbProperties.getProperty(key + "." + "CheckoutTimeout"))); ds.setTestConnectionOnCheckin(Boolean.parseBoolean(dbProperties.getProperty(key + "." + "TestConnectionOnCheckin"))); ds.setTestConnectionOnCheckout(Boolean.parseBoolean(dbProperties.getProperty(key + "." + "TestConnectionOnCheckout"))); datasourceMap.put(key, ds); Connection conn = getConnection(key); DatabaseMetaData metaData = conn.getMetaData(); logger.info("Using DataSource: " + conn.getClass().getName()); closeConnection(); } } catch (Exception e){ logger.error("DataSource Error:" + e.toString()); } } /** * 断开连接池 * */ public final static void closeDataSource(String dataSourceName){ try{ ComboPooledDataSource dataSource = datasourceMap.get(dataSourceName); dataSource.close(); } catch (Exception e){ logger.error("Unable to destroy DataSource! " + e.toString()); } } /** * 获取连接 * @return Connection * */ public final static Connection getConnection(String dataSourceName) throws SQLException{ Connection conn = conns.get(); if (conn == null || conn.isClosed()){ ComboPooledDataSource dataSource = datasourceMap.get(dataSourceName); conn = dataSource.getConnection(); conns.set(conn); } return conn; } /** * 关闭连接 * */ public final static void closeConnection(){ Connection conn = conns.get(); try{ if (conn != null && !conn.isClosed()){ conn.setAutoCommit(true); conn.close(); } } catch (SQLException ex){ logger.error("Unable to close connection! " + ex.toString()); } finally { conns.remove(); //conns.set(null); } } } ---------- dbInfo.properties ----------------- DemoData.AcquireIncrement = 2 DemoData.AcquireRetryAttempts = 30 DemoData.AcquireRetryDelay = 1000 DemoData.CheckoutTimeout = 3000 DemoData.Driver = com.microsoft.sqlserver.jdbc.SQLServerDriver DemoData.IdleConnectionTestPeriod = 18000 DemoData.InitialPoolSize = 2 DemoData.MaxIdleTime = 300 DemoData.MaxPoolSize = 100 DemoData.MaxStatements = 1000 DemoData.MinPoolSize = 2 DemoData.Password = 123 DemoData.TestConnectionOnCheckin = false DemoData.TestConnectionOnCheckout = false DemoData.Url = jdbc:sqlserver://localhost:1433;DatabaseName=DemoData DemoData.User = sa ---------- 测试代码:TestDBManager.java ----------------------- package ben.DBUtils; import java.sql.Connection; /** * Created with IntelliJ IDEA. * User: Ben * Date: 13-7-6 * Time: 上午12:28 * To change this template use File | Settings | File Templates. */ public class TestDBManager { public static void main(String[] args) { for (Integer i=0; i<10; i++){ try{ System.out.println(DBManager.getConnection("DemoData")); DBManager.closeConnection(); System.out.println("---------------------------"); } catch (Exception ex){ ex.printStackTrace(); } } } } 打印出来的结果每次都不一样 com.mchange.v2.c3p0.impl.NewProxyConnection@ff5c225 --------------------------- com.mchange.v2.c3p0.impl.NewProxyConnection@5bafcc2c --------------------------- com.mchange.v2.c3p0.impl.NewProxyConnection@ded0b93 --------------------------- com.mchange.v2.c3p0.impl.NewProxyConnection@25057fe --------------------------- com.mchange.v2.c3p0.impl.NewProxyConnection@198ad24a --------------------------- com.mchange.v2.c3p0.impl.NewProxyConnection@1228bd68 --------------------------- com.mchange.v2.c3p0.impl.NewProxyConnection@36db09fa --------------------------- com.mchange.v2.c3p0.impl.NewProxyConnection@35886ba1 --------------------------- com.mchange.v2.c3p0.impl.NewProxyConnection@17d8986 --------------------------- com.mchange.v2.c3p0.impl.NewProxyConnection@2bb9e538 ---------------------------

int类型转换成User对象类型报错问题

想询问一下大佬们,出现了Integer转换成User对象报错的问题代码如下 ``` private void UserUpdate(HttpServletRequest req, HttpServletResponse resp) throws IOException { //获取数据 String pwd=req.getParameter("pwd"); //从session中获取用户信息//下面的User的转换出了问题 User u=(User) req.getSession().getAttribute("servlet"); int uid=u.getUid(); //调用service处理 int index=us.Update(pwd,uid); System.out.println("index="+index); if(index>0){ //获取session对象 HttpSession hs=req.getSession(); hs.setAttribute("pwd","true"); //重定向到登录页面 resp.sendRedirect("/Login.jsp"); } —————————————————————————————————————————————————————— : Servlet.service() for servlet [servlet] in context with path [/New] threw exception java.lang.ClassCastException: java.lang.Integer cannot be cast to com.cwj.pojo.User at com.cwj.servlet.UserServlet.UserUpdate(UserServlet.java:88) at com.cwj.servlet.UserServlet.service(UserServlet.java:41) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.logging.log4j.core.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:66) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1137) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:319) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) ```

Java静态代码块中写这个监听方法时的运行原理是什么?

最近再学习过程中遇到了一个问题,看的视频中老师再静态代码块中写了关于hibernate中的SessionFactory关闭的方法,感觉不是很理解,静态代码块中的东西不是在类加载的时候都运行完了嘛。代码如下: ``` package com.gyf.hibernate.uitls; import org.dom4j.rule.Rule; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtils { private static SessionFactory factory; static{ //1.获取核心 配置文件对象 Configuration cfg = new Configuration().configure(); //2.创建会话工厂 factory = cfg.buildSessionFactory(); //监听程序关闭 Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run() { System.out.println("程序关闭..."); //关闭会话工厂 factory.close(); } }); } public static Session openSession(){ return factory.openSession(); } public static Session getCurrentSession(){ return factory.getCurrentSession(); } } ```

Springboot整合Shiro 记住密码(RememberM)之后怎么实现重启浏览器,我的登录信息也不过期?

1. cookie管理对象 ``` @Bean public CookieRememberMeManager cookieRememberMeManager() { CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager(); SimpleCookie simpleCookie = new SimpleCookie("rememberMe"); simpleCookie.setMaxAge(259200000); cookieRememberMeManager.setCookie(simpleCookie); cookieRememberMeManager.setCipherKey(Base64.decode("6Zm+6I2j5Y+R5aS+5ZOlAA==")); return cookieRememberMeManager; } ``` 2. 上面可以实现cookie保存,重启浏览器,无需登录;但是我发现,cookie虽在, 如我重启之后,ajax调用getRequest().getSession().getAttribute("userName") 这个时候发现Session已经不存在。会报java.lang.NullPointerException空指针异常。在网上找了博客,有些有人说关闭浏览器cookie都也释放了,但是我上面确实也能实现关闭重启之后无需登录,只要不获取session。在程序里面不获取session不可能的。 * 哪位大佬能给点解释?怎么才能实现关闭浏览器session也不过期? 记住密码之后,关闭浏览器,重启电脑再次打开也无需登录? ## **解决办法:** ``` /** * cookie对象; * @return */ @Bean public SimpleCookie rememberMeCookie(){ // 这个参数是cookie的名称,对应前端的checkbox的name = rememberMe SimpleCookie simpleCookie = new SimpleCookie("rememberMe"); // cookie生效时间30天,单位秒; simpleCookie.setMaxAge(2592000); // 浏览器中通过document.cookie可以获取cookie属性,设置了HttpOnly=true,在脚本中就不能的到cookie,可以避免cookie被盗用 simpleCookie.setHttpOnly(true); // JSESSIONID的path为/用于多个系统共享JSESSIONID simpleCookie.setPath("/"); return simpleCookie; } /** * cookie管理对象;记住我功能 * @return */ @Bean public CookieRememberMeManager rememberMeManager(){ CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager(); cookieRememberMeManager.setCookie(rememberMeCookie()); // rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位) cookieRememberMeManager.setCipherKey(Base64.decode("2A2V+RFLUs+eTA3Kpr+dag==")); return cookieRememberMeManager; } /** * 自定义过滤器 * @author : fyk * @create : 2019/11/14 16:12 **/ @Bean public CustomUserFilter customUserFilter() { CustomUserFilter customUserFilter = new CustomUserFilter(); return customUserFilter; } ``` ``` package com.cocosum.blog.core.shiro.filter; import com.cocosum.blog.commons.utils.SysConstant; import com.cocosum.blog.system.entity.UserInfo; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.subject.Subject; import org.apache.shiro.web.filter.AccessControlFilter; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.Objects; /** * 自定义过滤器 * @author : fyk * @create : 2019/11/14 17:06 **/ @Slf4j public class CustomUserFilter extends AccessControlFilter { @Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { Subject subject = getSubject(request, response); if (subject == null) { return false; } // 转成HttpSession对象 HttpSession session = ((HttpServletRequest) request).getSession(); // 获取当前登录用户(获取用户) Object userName = session.getAttribute(SysConstant.UserConstant.USER_NAME); // 如果因为session过时或者浏览器关闭,导致保存的登录信息随着session的关闭而清空了 if (Objects.isNull(userName)) { // 获取主体信息, session被清空之后,主体信息不会被清除掉 UserInfo userInfo = (UserInfo) subject.getPrincipal(); if (Objects.nonNull(userInfo)) { session.setAttribute(SysConstant.UserConstant.USER_NAME, userInfo.getUserName()); } else { // 否则session与主体信息都为空,那就说明没有登录。则需要重新登录 } } return true; } @Override protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception { return true; } @Override protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception { return true; } } ```

被Hibernate的Session绊了一跤

<p>写这篇博客的原因是出于昨天我在问答频道的一个问题,该问题如下:</p> <p> </p> <p><span style="font-family: Arial; line-height: 18px;">    当在servlet中调用DAO的save方法并提交事务后,控制台显示已经执行了sql语句,但是却没有向数据库中记录,如果把数据库的隔离级别设置为未提交读,这是可以看见刚插入的记录,但是之前已经调用了提交事务的语句,这是为什么呢? <br>注:主键生成策略为“native”,数据库是MySQL。<br><strong style="font-weight: bold;">问题补充:</strong><br>已经把数据库操作放到了事务中,而当第二条记录提交的时候才会向数据库中插入第一条记录,而新提交的记录不会被插入。<br><strong style="font-weight: bold;">问题补充:</strong></span></p> <p><span style="font-family: Consolas; line-height: 18px;"> <div class="bar"> <div class="tools" style="text-align: left; color: black; font-weight: bold; padding: 3px; margin: 0px;">Java代码 ;</div> </div> <ol class="dp-j" style="font-size: 1em; line-height: 1.4em; background-color: #ffffff; margin-top: 0px; margin-right: 0px; margin-bottom: 1px; margin-left: 0px; padding-top: 2px; padding-right: 0px; padding-bottom: 2px; padding-left: 0px; color: #2b91af; border: 1px solid #d1d7dc;"> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;"><span style="color: black;">UserDAO userDAO = </span><span class="keyword" style="color: #7f0055; font-weight: bold;">new</span><span style="color: black;"> UserDAO();  </span></span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">        User user = <span class="keyword" style="color: #7f0055; font-weight: bold;">new</span><span style="color: black;"> User();  </span></span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">          </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">        SessionFactory sessionFactory = HibernateSessionFactory.getSessionFactory();  </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">        Session session = sessionFactory.openSession();  </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">        Transaction tx = <span class="keyword" style="color: #7f0055; font-weight: bold;">null</span><span style="color: black;">;  </span></span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">          </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">        user.setUsername(registerForm.getUsername());  </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">          </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">        user.setEmail(registerForm.getEmail());  </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">  </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">        <span class="keyword" style="color: #7f0055; font-weight: bold;">try</span><span style="color: black;"> {  </span></span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">            tx = session.beginTransaction();  </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">            userDAO.save(user);  </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">            tx.commit();  </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">        }  </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">        <span class="keyword" style="color: #7f0055; font-weight: bold;">catch</span><span style="color: black;"> (RuntimeException e) {  </span></span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">            <span class="keyword" style="color: #7f0055; font-weight: bold;">if</span><span style="color: black;"> (tx != </span><span class="keyword" style="color: #7f0055; font-weight: bold;">null</span><span style="color: black;">)  </span></span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">                tx.rollback();  </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">            <span class="keyword" style="color: #7f0055; font-weight: bold;">throw</span><span style="color: black;"> e;   </span></span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">        }  </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">        <span class="keyword" style="color: #7f0055; font-weight: bold;">finally</span><span style="color: black;"> {  </span></span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">            session.close();  </span></li> <li style="font-size: 1em; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; border-left-width: 1px; border-left-style: solid; border-left-color: #d1d7dc; background-color: #fafafa; padding-left: 10px; line-height: 18px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 38px;"><span style="color: black;">        }  </span></li> </ol></span></p> <p><span style="font-family: Arial; line-height: 18px;"> <div class="dp-highlighter" style="font-family: Consolas, 'Courier New', Courier, mono; font-size: 12px; background-color: transparent; width: 97%; margin-left: 9px; padding: 1px;"> <div class="bar"> <div class="tools" style="color: black; padding: 3px; margin: 0px;"><span style="font-family: Verdana; line-height: normal;">通过查看Hibernate的代码发现的其中的问题。</span></div> <div class="tools" style="color: black; padding: 3px; margin: 0px;">我在获得Session对象的时候采用的是 sessionFactory.openSession();  Hibernate会新产生一个Session对象,接着执行userDAO.save(user)语句,而UserDAO类的save方法中用到的Session是通过HibernateSessionFactory.getSession()方法获得的,再继续看HibernateSessionFactory,其getSession()方法如下</div> </div> <div class="tools" style="color: black; padding: 3px; margin: 0px;"> <pre name="code" class="java"> public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; }</pre> </div> <div class="tools" style="color: black; padding: 3px; margin: 0px;"> 因此HibernateSessionFactory会为每个线程创建一个Session对象,MyEclipse所生成的DAO类就是用的这个</div> <div class="tools" style="color: black; padding: 3px; margin: 0px;">Session,这与在程序中通过openSession()方法所得到的是两个不同的Session对象,因此我在程序中调用的提交事务方法是在后一个Session中进行的,而对User对象的保存是在第一个Session中,而该Session中并没有执行提交事务操作。</div> <div class="tools" style="color: black; padding: 3px; margin: 0px;">    但是,至于之前的为什么当我执行第二次插入操作时会把前一条记录插入的原因还没有弄清楚,哪位大哥知道,欢迎留言。</div> </div> <div class="tools" style="color: black; padding: 3px; margin: 0px;"><br></div> <div class="tools" style="color: black; padding: 3px; margin: 0px;"><br></div> </span></p>

mina udp 客户端收不到服务端消息

已经关闭防火墙,抓包工具可以监听到服务端已经发送了消息 客户端代码 package cn.encdata.service.signal.realtime.client; import java.net.InetSocketAddress; import java.nio.charset.Charset; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.service.IoConnector; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.transport.socket.nio.NioDatagramConnector; import org.apache.mina.transport.socket.nio.NioSocketConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.encdata.service.Config; //通信客户端 public class SocketClient { private ConnectFuture future = null;//连接对象 private boolean exit = false; private static Charset CS = Charset.forName("GBK"); private IoSession session = null;//会话 private static Logger log = LoggerFactory.getLogger(SocketClient.class); private static SocketClient client= null; private SocketClient() { } public static SocketClient instance() { if(client == null) { client = new SocketClient(); } return client; } public synchronized void start() { new Thread(new Runnable(){ public void run(){connect();} }).start(); } public synchronized void stop() { if(future!=null && future.isConnected()) { future.getSession().close(true); future = null; exit = true; } } public synchronized void send(IoBuffer buffer) { if(buffer == null) return; if(session == null || !session.isConnected()) { log.info("通讯链路尚未创建,无法发送数据."); return; } if(session.getAttribute("login") == null) { log.info("通讯链路尚未通过验证,无法发送数据."); return; } session.write(buffer); buffer.free(); } private void connect() { while(!exit) { if(future == null || !future.isConnected()) { IoConnector connector = null; try { connector = new NioDatagramConnector(); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory())); //connector.setConnectTimeoutMillis(Config.Server.ConnectTimeout); connector.setHandler(new SocketDataHandler()); future = connector.connect(new InetSocketAddress("172.16.13.99",5555),new InetSocketAddress("172.163.133.200",8341)); future.awaitUninterruptibly(); if (!future.isConnected()) { log.info(" 断线连接中{}:{}",Config.Server.IP,Config.Server.Port); Thread.sleep(Config.Server.ReconnectInterval); continue; } session = future.getSession(); future.getSession().getCloseFuture().awaitUninterruptibly(); future = null; } catch (Exception e) { log.error("创建通讯连接异常",e); break; } finally { if(connector != null) { connector.dispose(); } } } try { Thread.sleep(Config.Server.ReconnectInterval); } catch (InterruptedException e) { e.printStackTrace(); } } } } handler类代码为: package cn.encdata.service.signal.realtime.client; import java.nio.ByteOrder; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.encdata.service.Config; import cn.encdata.service.signal.realtime.receive.handler.FaceHandler; public class SocketDataHandler extends IoHandlerAdapter { private final Logger log = LoggerFactory.getLogger(SocketDataHandler.class); @Override public void sessionOpened(IoSession session) { log.info("与服务器连接成功:"+session.getRemoteAddress()); log.info("发送登录消息"); //退出登录 //session.write("退出登录\rsuper\r"); session.write("登录系统\rsuper\r111\r"); } @Override public void sessionClosed(IoSession session) throws Exception { log.info("{}与服务器断线",session.getRemoteAddress()); } @Override public void messageReceived(IoSession session, Object message) { System.out.println("客户端传来消息:"+message.toString()); } @Override public void sessionIdle(IoSession session, IdleStatus status) { if (status == IdleStatus.BOTH_IDLE) { //发送心跳包 IoBuffer heartbeat = IoBuffer.allocate(2+1); heartbeat.order(ByteOrder.BIG_ENDIAN); //heartbeat.putUnsignedShort(1); //heartbeat.putUnsigned(0); //heartbeat.flip(); log.info("发送心跳消息"); session.write("客户端正常\rsuper\r"); } } @Override public void sessionCreated(IoSession session) throws Exception { //当创建一个新的连接时被触发,即开始一个新的session是被触发 log.info("sessionCreated"); session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 20); } @Override public void messageSent(IoSession session, Object message) { } @Override public void exceptionCaught(IoSession session, Throwable cause) { log.error(cause.getMessage(),cause); } }

jquery从后台取得list,怎么遍历出来?

function listNames() { var name =$("#tName").val(); $.get("boardlist.action?typeName="+name, null, callback); } function callback(date) { var resultobj = $("#result"); resultobj.html(date); } 数据已返回

请问一下java 调用shell上传linux的问题

package com.wfj.cms.util; import java.io.IOException; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import org.apache.log4j.Logger; import org.apache.oro.text.regex.MalformedPatternException; import com.jcraft.jsch.ChannelShell; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import com.jcraft.jsch.UserInfo; import expect4j.Closure; import expect4j.Expect4j; import expect4j.ExpectState; import expect4j.matches.EofMatch; import expect4j.matches.Match; import expect4j.matches.RegExpMatch; import expect4j.matches.TimeoutMatch; public class Shell { private static Logger log = Logger.getLogger(Shell.class); private Session session; private ChannelShell channel; private static Expect4j expect = null; private static final long defaultTimeOut = 1000; private StringBuffer buffer=new StringBuffer(); public static final int COMMAND_EXECUTION_SUCCESS_OPCODE = -2; public static final String BACKSLASH_R = "\r"; public static final String BACKSLASH_N = "\n"; public static final String COLON_CHAR = ":"; public static String ENTER_CHARACTER = BACKSLASH_R; public static final int SSH_PORT = 22; //正则匹配,用于处理服务器返回的结果 public static String[] linuxPromptRegEx = new String[] { "~]#", "~#", "#", ":~#", "/$", ">" }; public static String[] errorMsg=new String[]{"could not acquire the config lock "}; //ssh服务器的ip地址 private String ip; //ssh服务器的登入端口 private int port; //ssh服务器的登入用户名 private String user; //ssh服务器的登入密码 private String password; public Shell(String ip,int port,String user,String password) { this.ip=ip; this.port=port; this.user=user; this.password=password; expect = getExpect(); } /** * 关闭SSH远程连接 */ public void disconnect(){ if(channel!=null){ channel.disconnect(); } if(session!=null){ session.disconnect(); } } /** * 获取服务器返回的信息 * @return 服务端的执行结果 */ public String getResponse(){ return buffer.toString(); } //获得Expect4j对象,该对用可以往SSH发送命令请求 private Expect4j getExpect() { try { log.debug(String.format("Start logging to %s@%s:%s",user,ip,port)); JSch jsch = new JSch(); session = jsch.getSession(user, ip, port); session.setPassword(password); Hashtable<String, String> config = new Hashtable<String, String>(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); localUserInfo ui = new localUserInfo(); session.setUserInfo(ui); session.connect(); channel = (ChannelShell) session.openChannel("shell"); Expect4j expect = new Expect4j(channel.getInputStream(), channel .getOutputStream()); channel.connect(); log.debug(String.format("Logging to %s@%s:%s successfully!",user,ip,port)); return expect; } catch (Exception ex) { log.error("Connect to "+ip+":"+port+"failed,please check your username and password!"); ex.printStackTrace(); } return null; } /** * 执行配置命令 * @param commands 要执行的命令,为字符数组 * @return 执行是否成功 */ public boolean executeCommands(String[] commands) { //如果expect返回为0,说明登入没有成功 if(expect==null){ return false; } log.debug("----------Running commands are listed as follows:----------"); for(String command:commands){ log.debug(command); } log.debug("----------End----------"); Closure closure = new Closure() { public void run(ExpectState expectState) throws Exception { buffer.append(expectState.getBuffer());// buffer is string // buffer for appending // output of executed // command expectState.exp_continue(); } }; List<Match> lstPattern = new ArrayList<Match>(); String[] regEx = linuxPromptRegEx; if (regEx != null && regEx.length > 0) { synchronized (regEx) { for (String regexElement : regEx) { try { RegExpMatch mat = new RegExpMatch(regexElement, closure); lstPattern.add(mat); } catch (MalformedPatternException e) { return false; } catch (Exception e) { return false; } } lstPattern.add(new EofMatch(new Closure() { // should cause // entire page to be // collected public void run(ExpectState state) { } })); lstPattern.add(new TimeoutMatch(defaultTimeOut, new Closure() { public void run(ExpectState state) { } })); } } try { boolean isSuccess = true; for (String strCmd : commands){ isSuccess = isSuccess(lstPattern, strCmd); } //防止最后一个命令执行不了 isSuccess = !checkResult(expect.expect(lstPattern)); //找不到错误信息标示成功 String response=buffer.toString().toLowerCase(); for(String msg:errorMsg){ if(response.indexOf(msg)>-1){ return false; } } return isSuccess; } catch (Exception ex) { ex.printStackTrace(); return false; } } //检查执行是否成功 private boolean isSuccess(List<Match> objPattern, String strCommandPattern) { try { int result = expect.expect(objPattern); boolean isFailed = checkResult(result); if (!isFailed) { expect.send(strCommandPattern); expect.send("\r"); return true; } return false; } catch (MalformedPatternException ex) { return false; } catch (Exception ex) { return false; } } //检查执行返回的状态 private boolean checkResult(int intRetVal) { if (intRetVal == COMMAND_EXECUTION_SUCCESS_OPCODE) { return true; } return false; } //登入SSH时的控制信息 //设置不提示输入密码、不显示登入信息等 public static class localUserInfo implements UserInfo { String passwd; public String getPassword() { return passwd; } public boolean promptYesNo(String str) { return true; } public String getPassphrase() { return null; } public boolean promptPassphrase(String message) { return true; } public boolean promptPassword(String message) { return true; } public void showMessage(String message) { } } public static void main(String[] orgs) throws IOException, InterruptedException{ String ip = "10.6.1.64"; int port = 22; String user ="tomcat"; String password = "123456"; String cmd[] = {" cd /usr","ls -ls"}; String command = "/home/tomcat"; Shell ssh = new Shell(ip,port,user,password); ssh.executeCommands(cmd); System.out.println(ssh.getResponse()); ssh.disconnect(); } } 最近要做一个sell上传jar包到linux上的程序, 大致的需求是.. 将本地(部署在linux服务器上的系统)的文件上传到一组linux服务器上,(多台服务器) 服务器文件路径都是一样的。 但是要用java写, 以前没弄过关于java 调用shell的。 就从网上找到以上代码,但是新的问题又来了, 不熟悉sell命令。 只会一点简单的。从一台服务器上发布到多台服务器(一台一台的上传) 求大神指点迷津。 小弟谦虚好学。 QQ599159992

int类型转换成User对象类型报错问题 User u=(User) req.getSession().getAttribute("servlet");

``` private void UserUpdate(HttpServletRequest req, HttpServletResponse resp) throws IOException { String pwd=req.getParameter("pwd"); //下面的User的转换报错 User u=(User) req.getSession().getAttribute("servlet"); int uid=u.getUid(); int index=us.Update(pwd,uid); System.out.println("index="+index); if(index>0){ HttpSession hs=req.getSession(); hs.setAttribute("pwd","true"); resp.sendRedirect("/Login.jsp"); } ``` ``` Servlet.service() for servlet [servlet] in context with path [/New] threw exception java.lang.ClassCastException: java.lang.Integer cannot be cast to com.cwj.pojo.User at com.cwj.servlet.UserServlet.UserUpdate(UserServlet.java:88) at com.cwj.servlet.UserServlet.service(UserServlet.java:41) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.logging.log4j.core.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:66) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1137) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:319) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) ```

播种数据库 - [ErrorException]试图获取非对象的属性

<div class="post-text" itemprop="text"> <p>I am using <a href="https://github.com/Zizaco/confide" rel="nofollow">"zizaco/confide": "~4.0@dev"</a> and <a href="https://github.com/Zizaco/entrust" rel="nofollow">"zizaco/entrust": "1.2.*@dev"</a>.</p> <p>I have set everything up as described in the two tutorials(confide migrations). Furthermore, I have created the following models:</p> <p><strong>User:</strong></p> <pre><code> &lt;?php use Zizaco\Confide\ConfideUser; use Zizaco\Confide\Confide; use Zizaco\Confide\ConfideEloquentRepository; use Zizaco\Entrust\HasRole; use Carbon\Carbon; use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableInterface; class User extends Eloquent implements UserInterface, RemindableInterface{ use ConfideUser; use HasRole; /** * Get user by username * @param $username * @return mixed */ public function getUserByUsername( $username ) { return $this-&gt;where('username', '=', $username)-&gt;first(); } public function joined() { return String::date(Carbon::createFromFormat('Y-n-j G:i:s', $this-&gt;created_at)); } public function saveRoles($inputRoles) { if(! empty($inputRoles)) { $this-&gt;roles()-&gt;sync($inputRoles); } else { $this-&gt;roles()-&gt;detach(); } } public function currentRoleIds() { $roles = $this-&gt;roles; $roleIds = false; if( !empty( $roles ) ) { $roleIds = array(); foreach( $roles as &amp;$role ) { $roleIds[] = $role-&gt;id; } } return $roleIds; } public static function checkAuthAndRedirect($redirect, $ifValid=false) { // Get the user information $user = Auth::user(); $redirectTo = false; if(empty($user-&gt;id) &amp;&amp; ! $ifValid) // Not logged in redirect, set session. { Session::put('loginRedirect', $redirect); $redirectTo = Redirect::to('user/login') -&gt;with( 'notice', Lang::get('user/user.login_first') ); } elseif(!empty($user-&gt;id) &amp;&amp; $ifValid) // Valid user, we want to redirect. { $redirectTo = Redirect::to($redirect); } return array($user, $redirectTo); } public function currentUser() { return (new Confide(new ConfideEloquentRepository()))-&gt;user(); } public function getReminderEmail() { return $this-&gt;email; } } </code></pre> <p><strong>Role:</strong></p> <pre><code>&lt;?php use Zizaco\Entrust\EntrustRole; class Role extends EntrustRole { public function validateRoles( array $roles ) { $user = Confide::user(); $roleValidation = new stdClass(); foreach( $roles as $role ) { // Make sure theres a valid user, then check role. $roleValidation-&gt;$role = ( empty($user) ? false : $user-&gt;hasRole($role) ); } return $roleValidation; } } </code></pre> <p><strong>Permission:</strong></p> <pre><code>&lt;?php use Zizaco\Entrust\EntrustPermission; class Permission extends EntrustPermission { public function preparePermissionsForDisplay($permissions) { // Get all the available permissions $availablePermissions = $this-&gt;all()-&gt;toArray(); foreach($permissions as &amp;$permission) { array_walk($availablePermissions, function(&amp;$value) use(&amp;$permission){ if($permission-&gt;name == $value['name']) { $value['checked'] = true; } }); } return $availablePermissions; } /** * Convert from input array to savable array. * @param $permissions * @return array */ public function preparePermissionsForSave( $permissions ) { $availablePermissions = $this-&gt;all()-&gt;toArray(); $preparedPermissions = array(); foreach( $permissions as $permission =&gt; $value ) { // If checkbox is selected if( $value == '1' ) { // If permission exists array_walk($availablePermissions, function(&amp;$value) use($permission, &amp;$preparedPermissions){ if($permission == (int)$value['id']) { $preparedPermissions[] = $permission; } }); } } return $preparedPermissions; } } </code></pre> <p>Furthermore, I would like to seed my database in the beginning with values, therefore I created several seeders for user, role and permission. However, I get an error in my permission seeder:</p> <p><strong>UserTableSeeder:</strong></p> <pre><code>&lt;?php class UsersTableSeeder extends Seeder { public function run() { DB::table('users')-&gt;delete(); $users = array( array( 'username' =&gt; 'admin', 'email' =&gt; 'admin@example.org', 'password' =&gt; Hash::make('admin'), 'confirmed' =&gt; 1, 'confirmation_code' =&gt; md5(microtime().Config::get('app.key')), 'created_at' =&gt; new DateTime, 'updated_at' =&gt; new DateTime, ), array( 'username' =&gt; 'moderator', 'email' =&gt; 'moderator@example.org', 'password' =&gt; Hash::make('moderator'), 'confirmed' =&gt; 1, 'confirmation_code' =&gt; md5(microtime().Config::get('app.key')), 'created_at' =&gt; new DateTime, 'updated_at' =&gt; new DateTime, ), array( 'username' =&gt; 'user', 'email' =&gt; 'user@example.org', 'password' =&gt; Hash::make('user'), 'confirmed' =&gt; 1, 'confirmation_code' =&gt; md5(microtime().Config::get('app.key')), 'created_at' =&gt; new DateTime, 'updated_at' =&gt; new DateTime, ) ); DB::table('users')-&gt;insert( $users ); } } </code></pre> <p><strong>RolesTableSeeder:</strong></p> <pre><code>&lt;?php class RolesTableSeeder extends Seeder { public function run() { DB::table('roles')-&gt;delete(); $adminRole = new Role; $adminRole-&gt;name = 'adminRole'; $adminRole-&gt;save(); $standRole = new Role; $standRole-&gt;name = 'userRole'; $standRole-&gt;save(); $modRole = new Role; $modRole-&gt;name = 'modRole'; $modRole-&gt;save(); $user = User::where('username','=','admin')-&gt;first(); $user-&gt;attachRole( $adminRole ); $user = User::where('username','=','user')-&gt;first(); $user-&gt;attachRole( $standRole ); $user = User::where('username','=','moderator')-&gt;first(); $user-&gt;attachRole( $modRole ); } } </code></pre> <p><strong>PermissionsTableSeeder:</strong></p> <pre><code>&lt;?php class PermissionsTableSeeder extends Seeder { public function run() { DB::table('permissions')-&gt;delete(); $permissions = array( array( // 1 'name' =&gt; 'manage_users', 'display_name' =&gt; 'manage users' ), array( // 2 'name' =&gt; 'manage_roles', 'display_name' =&gt; 'manage roles' ), array( // 3 'name' =&gt; 'standart_user_role', 'display_name' =&gt; 'standart_user_role' ), ); DB::table('permissions')-&gt;insert( $permissions ); DB::table('permission_role')-&gt;delete(); $role_id_admin = Role::where('name', '=', 'admin')-&gt;first()-&gt;id; $role_id_mod = Role::where('name', '=', 'moderator')-&gt;first()-&gt;id; $role_id_stand = Role::where('name', '=', 'user')-&gt;first()-&gt;id; $permission_base = (int)DB::table('permissions')-&gt;first()-&gt;id - 1; $permissions = array( array( 'role_id' =&gt; $role_id_admin, 'permission_id' =&gt; $permission_base + 1 ), array( 'role_id' =&gt; $role_id_admin, 'permission_id' =&gt; $permission_base + 2 ), array( 'role_id' =&gt; $role_id_mod, 'permission_id' =&gt; $permission_base + 1 ), array( 'role_id' =&gt; $role_id_mod, 'permission_id' =&gt; $permission_base + 3 ), array( 'role_id' =&gt; $role_id_stand, 'permission_id' =&gt; $permission_base + 3 ), ); DB::table('permission_role')-&gt;insert( $permissions ); } } </code></pre> <p>This is the error I get when running <code>db:seed</code>:</p> <pre><code>$ php artisan db:seed ************************************** * Application In Production! * ************************************** Do you really wish to run this command? Y Seeded: UsersTableSeeder Seeded: RolesTableSeeder [ErrorException] Trying to get property of non-object db:seed [--class[="..."]] [--database[="..."]] [--force] </code></pre> <p>Any recommendations what I am doing wrong in my seeding?</p> <p>I appreciate your answers!</p> </div>

hibernate多对一提示空指针的问题

创建了product和factory两个实体类,字段什么的和数据库的都是一样的,配置文件如下:product.hbm.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name = "com.pansoft.entity.Product" table = "product"> <id name="id" type = "int" column="id" > <generator class="native"></generator> </id> <property name="name" type = "string" length="255"> <column name="name"></column> </property> <property name="price" type = "double"> <column name="price"></column> </property> <many-to-one name="factory" class="com.pansoft.entity.Factory"> <column name="factoryid"></column> </many-to-one> </class> </hibernate-mapping> factory.hbm.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name = "com.pansoft.entity.Factory" table="factory"> <id name = "factoryid" type = "int" column="factoryid"> <generator class="native"> </generator> </id> <property name="name" type = "string"> <column name="name"></column> </property> </class> </hibernate-mapping> 操作查询: try { Session session = Hibernateutils.getSession(); session.beginTransaction(); Product product = (Product)session.get(Product.class, new Integer(1)); if(product == null) { System.out.println("111"); } else { System.out.println(product.getName()); session.getTransaction().commit(); } } catch (Exception e) { // TODO 自动生成的 catch 块 System.out.println("错误"); e.printStackTrace(); } 之后控制台就输出: log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. Hibernate: select product0_.id as id0_0_, product0_.name as name0_0_, product0_.price as price0_0_, product0_.factoryid as factoryid0_0_ from product product0_ where product0_.id=? 111

spring+myBatis数据不入库问题,求大神解答。

昨天做项目的时候遇到的问题,查询删除都是好的,保存死活不入库,以下是代码部分: ``` /** * 试题模版导入 * * @param session * @param response * @param request * @throws Exception */ @RequestMapping(value = "/templateImport", method = RequestMethod.POST) @ResponseBody public String templateImport(@RequestParam(value = "file", required = false) MultipartFile file, HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap) { List<Map<Question, List<String>>> questionAndOptionsList = new ArrayList<Map<Question, List<String>>>();// 定义试题和答案的map集合对象集 List<Row> rowList = new ArrayList<Row>();// 定义行对象 String libraryId = request.getParameter("libraryId"); if (StringUtils.isEmpty(libraryId)) { modelMap.put("message", "未选择题库"); RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE); return null; } try { rowList = ExcelUtil.getRows(file, 1); } catch (Exception e) { modelMap.put("message", "解析模版出错"); RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE); return null; } int dateNum = rowList.size();// 定义数据总条数 int addNum = 0;// 定义新增数据条数 int updateNum = 0;// 定义修改数据条数 for (int i = 0; i < rowList.size(); i++) { Row row = rowList.get(i); Question question = new Question();// 定义试题对象 List<String> questionOptionList = new ArrayList<String>();// 定义接收所有解析到的试题选项 int cellNum = row.getLastCellNum();// 获取总列数 String questionTypeId = null; // 定义转换之后的试题类型 // 获取所有试题列的值 String content = ExcelUtil.getStringCellValue(row.getCell(0));// 获取试题内容 String questionTypeName = ExcelUtil.getStringCellValue(row.getCell(1));// 获取试题类型(拿到的是中文,需要自己转换) String answer = ExcelUtil.getStringCellValue(row.getCell(2));// 获取答案 String analysis = ExcelUtil.getStringCellValue(row.getCell(3));// 获取试题解析 /* * 试题信息非空校验 */ if (StringUtils.isEmpty(content)) { modelMap.put("message", "导入文件中第" + (i + 2) + "行的试题内容为空"); RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE); return null; } if (StringUtils.isEmpty(questionTypeName)) { modelMap.put("message", "导入文件中第" + (i + 2) + "行的试题类型为空"); RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE); return null; } else { // 解析试题类型为编码 switch (questionTypeName) { case "单选题": questionTypeId = Const.QUESTION_TYPE_ID_SINGLE; break; case "多选题": questionTypeId = Const.QUESTION_TYPE_ID_MULTIPLE; break; case "判断题": questionTypeId = Const.QUESTION_TYPE_ID_JUDGE; break; default: break; } } if (StringUtils.isEmpty(answer)) { modelMap.put("message", "导入文件中第" + (i + 2) + "行的答案为空"); RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE); return null; } /* * 试题信息长度校验 */ if (content.length() > 1000) { modelMap.put("message", "导入文件中第" + (i + 2) + "行的试题内容长度超出范围"); RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE); return null; } if (answer.length() > 200) { modelMap.put("message", "导入文件中第" + (i + 2) + "行的答案长度超出范围"); RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE); return null; } if (analysis.length() > 500) { modelMap.put("message", "导入文件中第" + (i + 2) + "行的试题解析长度超出范围"); RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE); return null; } /* * 校验通过之后设置question对象 */ question.setContent(content);// 设置内容 question.setQuestionTypeId(questionTypeId);// 设置类型 question.setAnswer(answer);// 设置答案 question.setLibraryId(libraryId);// 设置题库 question.setAnalysis(analysis);// 设置解析 question.setDelFlag("0");// 设置删除标识(1、为删除0、为未删除) /* * 开始解析试题答案信息 */ for (int j = 4; j < cellNum; j++) {// 定义从第5列开始解析答案信息,第5列之前都时试题信息 String questionOption = ExcelUtil.getStringCellValue(row.getCell(j));// 获取试题答案选项 if (!StringUtils.isEmpty(questionOption)) {// 判断试题选项是否为空,如果为空则不存储该选项,也不中断解析之后的选项列 questionOptionList.add(questionOption); } } Map<Question, List<String>> map = new HashMap<Question, List<String>>(); map.put(question, questionOptionList); questionAndOptionsList.add(map); } for (Map<Question, List<String>> questionAndOptions : questionAndOptionsList) { Set set = questionAndOptions.keySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Question keyQuestion = (Question) iterator.next(); **questionService.save(keyQuestion);// 保存试题信息** List<String> questionOptionsList = questionAndOptions.get(keyQuestion);// 获取该试题所有的选项 for (int j = 0; j < questionOptionsList.size() && j < 26; j++) { String content = questionOptionsList.get(j); char letterCapital = (char) (j + 65);// 将数字转换成对应的字母 QuestionOption questionOption = new QuestionOption();// 定义试题对象 questionOption.setContent(content);// 设置选项内容 questionOption.setQuestionId(keyQuestion.getId());// 设置试题ID questionOption.setName(String.valueOf(letterCapital));// 设置选项编号(A、B、C...) questionOption.setSortNum(String.valueOf(j));// 设置排序号 questionOption.setDelFlag("0");// 设置删除标识(1、为删除0、为未删除) **optionService.save(questionOption);// 保存试题对象** } } } modelMap.put("message", "新增数据:" + addNum + "条,修改数据:" + updateNum + "条,失败:" + (dateNum - addNum - updateNum) + "条"); RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE); return null; } ``` 跟此方法同类下的保存方法是可以运行的,并且数据也能入库,上述方法没有出现任何错误,并且执行save之后对象ID也会自动生成,但就时不入库。

js的setAttribute设置属性问题

setAttribute("name", "mymps_img_变量") name的名称后面怎么设置变量,效果如mymps_img_0;mymps_img_1;mymps_img_2

异常:Cookie value must not be null

/** * 入口 * @param args */ public static void main(String[] args) { System.out.println("输出什么?"); Login login = new Login(); login.getPersonInfo(); } // 返会一个list对象 public List<String> getPersonInfo() {// 返回一个list对象 List<String> list = new ArrayList<String>(); try { // 得到session ,进行模拟登陆,(如果有验证码,我就不知道了)。--博客园老牛大讲堂 Connection.Response res = Jsoup.connect("http://www.51job.com") .data( "loginname", "15217727459" , "password", "15217727459." )// 进行模拟登陆 .method(Connection.Method.POST).timeout(10000).execute();// 设置请求时间和登陆用的用户名,密码。 // Document doc = res.parse(); // 根据session进行爬虫 // 注释:不是所有网站他们都需要cook,也不是所有的网站cook都是iPlanetDirectoryPro。 // 不同网站网址的cookie不一样。而且每次访问都不一样,所以不要想着把session保存起来。 String guid = res.cookie("guid"); String _ujz = res.cookie("_ujz"); System.out.println("guid === " + guid); System.out.println("_ujz === " + _ujz); Document objectDoc = Jsoup .connect("http://i.51job.com/resume/resume_preview.php?lang=c&resumeid=358968976&3658907287")// 里面的网址(就是你想要爬取的网页) .cookie("guid", guid) .cookie("_ujz", _ujz) // 异常提示行 .timeout(10000).post();// 设置请求的时间(这里设置的请求时间是10秒) System.out.println("objectDoc === " + objectDoc); Element htmlElement = objectDoc.getElementsByClass("name").get(0);// 得到class为name的第一个对象 Elements trElements = htmlElement.getElementsByTag("tr");// 得到tr标签的对象 System.out.println(trElements.size());// 输出多少个tr标签 for (int i = 1; i < trElements.size(); i++) { Elements divElments = trElements.get(i).getElementsByAttributeValue("align", "left");// 根据class进行得到对象。 for (int j = 0; j < trElements.size(); j++) { Element d = divElments.get(j);// 获取每一个对象 list.add(d.text());// 得到这个对象对应的值 } } } catch (IOException e) { e.printStackTrace(); } return list; }

mybatis中mapper配置问题

第一次创建,报一下这些错误,求解决!求解决!不知道usermapper哪里出问题 D:\Java\jdk1.8.0_172\bin\java.exe "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2018.1.5\lib\idea_rt.jar=58476:C:\Program Files\JetBrains\IntelliJ IDEA 2018.1.5\bin" -Dfile.encoding=UTF-8 -classpath D:\Java\jdk1.8.0_172\jre\lib\charsets.jar;D:\Java\jdk1.8.0_172\jre\lib\deploy.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\access-bridge-64.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\cldrdata.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\dnsns.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\jaccess.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\jfxrt.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\localedata.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\nashorn.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\sunec.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\sunjce_provider.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\sunmscapi.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\sunpkcs11.jar;D:\Java\jdk1.8.0_172\jre\lib\ext\zipfs.jar;D:\Java\jdk1.8.0_172\jre\lib\javaws.jar;D:\Java\jdk1.8.0_172\jre\lib\jce.jar;D:\Java\jdk1.8.0_172\jre\lib\jfr.jar;D:\Java\jdk1.8.0_172\jre\lib\jfxswt.jar;D:\Java\jdk1.8.0_172\jre\lib\jsse.jar;D:\Java\jdk1.8.0_172\jre\lib\management-agent.jar;D:\Java\jdk1.8.0_172\jre\lib\plugin.jar;D:\Java\jdk1.8.0_172\jre\lib\resources.jar;D:\Java\jdk1.8.0_172\jre\lib\rt.jar;D:\workplace\webssm\target\classes;D:\mavenRepository\jstl\jstl\1.2\jstl-1.2.jar;D:\mavenRepository\javax\javaee-api\7.0\javaee-api-7.0.jar;D:\mavenRepository\com\sun\mail\javax.mail\1.5.0\javax.mail-1.5.0.jar;D:\mavenRepository\javax\activation\activation\1.1\activation-1.1.jar;D:\mavenRepository\org\mybatis\mybatis\3.3.0\mybatis-3.3.0.jar;D:\mavenRepository\mysql\mysql-connector-java\5.1.29\mysql-connector-java-5.1.29.jar;D:\mavenRepository\commons-dbcp\commons-dbcp\1.2.2\commons-dbcp-1.2.2.jar;D:\mavenRepository\commons-pool\commons-pool\1.3\commons-pool-1.3.jar;D:\mavenRepository\com\alibaba\fastjson\1.1.41\fastjson-1.1.41.jar;D:\mavenRepository\log4j\log4j\1.2.17\log4j-1.2.17.jar;D:\mavenRepository\org\slf4j\slf4j-api\1.7.18\slf4j-api-1.7.18.jar;D:\mavenRepository\org\slf4j\slf4j-log4j12\1.7.18\slf4j-log4j12-1.7.18.jar;D:\mavenRepository\org\codehaus\jackson\jackson-mapper-asl\1.9.13\jackson-mapper-asl-1.9.13.jar;D:\mavenRepository\org\codehaus\jackson\jackson-core-asl\1.9.13\jackson-core-asl-1.9.13.jar;D:\mavenRepository\com\fasterxml\jackson\core\jackson-core\2.8.0\jackson-core-2.8.0.jar;D:\mavenRepository\com\fasterxml\jackson\core\jackson-databind\2.8.0\jackson-databind-2.8.0.jar;D:\mavenRepository\com\fasterxml\jackson\core\jackson-annotations\2.8.0\jackson-annotations-2.8.0.jar;D:\mavenRepository\commons-fileupload\commons-fileupload\1.3.1\commons-fileupload-1.3.1.jar;D:\mavenRepository\commons-io\commons-io\2.4\commons-io-2.4.jar;D:\mavenRepository\commons-codec\commons-codec\1.9\commons-codec-1.9.jar com.controller.test Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException: ### Error building SqlSession. ### The error may exist in com/mapper/UserMapper.java (best guess) ### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 43; 文档根元素 "mapper" 必须匹配 DOCTYPE 根 "null"。 at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:54) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:38) at com.controller.test.main(test.java:25) Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 43; 文档根元素 "mapper" 必须匹配 DOCTYPE 根 "null"。 at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:115) at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:95) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:52) ... 2 more Caused by: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 43; 文档根元素 "mapper" 必须匹配 DOCTYPE 根 "null"。 at org.apache.ibatis.parsing.XPathParser.createDocument(XPathParser.java:259) at org.apache.ibatis.parsing.XPathParser.<init>(XPathParser.java:125) at org.apache.ibatis.builder.xml.XMLMapperBuilder.<init>(XMLMapperBuilder.java:78) at org.apache.ibatis.builder.xml.XMLMapperBuilder.<init>(XMLMapperBuilder.java:73) at org.apache.ibatis.builder.annotation.MapperAnnotationBuilder.loadXmlResource(MapperAnnotationBuilder.java:166) at org.apache.ibatis.builder.annotation.MapperAnnotationBuilder.parse(MapperAnnotationBuilder.java:118) at org.apache.ibatis.binding.MapperRegistry.addMapper(MapperRegistry.java:72) at org.apache.ibatis.session.Configuration.addMapper(Configuration.java:671) at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:348) at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:113) ... 4 more Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 43; 文档根元素 "mapper" 必须匹配 DOCTYPE 根 "null"。 <mapper namespace="com.mapper.UserMapper"> <resultMap type="com.pojo.User" id="userResultMap"> <id property="id" colum="id"/> <result property="username" column="username"/> <result property="sex" column="sex"/> <result property="age" column="age"/> <result property="loginname" column="loginname"/> <result property="password" column="password"/> <result property="phone" column="phone"/> <result property="address" column="address"/> <!-- 一对多关联映射--> <collection property="orders" javaType="ArrayList" column="id" ofType="com.pojo.User" select="com.mapper.OrderMapper.selectOrderByUserId" fetchType="lazy"> <id property="id" colum="id"></id> <result property="code" column="code"></result> <result property="total" column="total"></result> </collection> </resultMap> <select id="selectUserById" parameterType="int" resultMap="userResultMap"> SELECT * FROM user WHERE id = #{id} </select> </mapper> package com.controller; import com.mapper.OrderMapper; import com.mapper.UserMapper; import com.pojo.Order; import com.pojo.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.*; //import org.mybatis.spring.SqlSessionFactoryBean; //import org.springframework.aop.scope.ScopedProxyUtils; import java.io.IOException; //import java.io.InputStream; import java.io.Reader; import java.util.List; public class test { public static void main(String[] args) throws IOException { //读取mybatis-config.xml文件 //InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml"); Reader reader=Resources.getResourceAsReader("mybatis-config.xml"); //初始化mybatis,创建sqlsessionfactory类的实例 SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader); //创建Session实例 SqlSession session=sqlSessionFactory.openSession(); test t=new test(); t.testSelectUserById(session); t.testSelectOrderById(session); session.commit(); session.close(); } //测试一对多关系 public void testSelectUserById(SqlSession session){ //获得usermapper接口的代理对象 UserMapper um=session.getMapper(UserMapper.class); //调用selectUserById方法 User user=um.selectUserById(1); //查询user的对象信息 System.out.println(user.getId()+""+user.getUsername()); List<Order> orders=user.getOrders(); for (Order order:orders ) { System.out.println(order); } } //测试多对多的关系,查询订单Order的时候级联查询订单的商品 public void testSelectOrderById(SqlSession session){ //获得OrderMapper接口的代理对象 OrderMapper om=session.getMapper(OrderMapper.class); //调用selectOrderById方法 Order order=om.selectOrderById(2); //查看查询到的信息 System.out.println(order.getId()+""+order.getCode()+""+order.getTotal()); User user=order.getUser(); System.out.println(user); } }

计算数组中的元素数

<div class="post-text" itemprop="text"> <p>I am creating an application, and it has a function which removes elements from an array inside a document in a MongoDB collection.</p> <p>I need a way to unset the array's field as soon as the array becomes empty right after a remove operation. I need to do this so that I can differentiate between a document that has a non-empty array, and a document that has an empty array.</p> <p>For example, right now my <code>section</code> collection looks like:</p> <pre><code>db.section.find({}) { "_id" : ObjectId("57a0a38ad1c6ef24376477c5"), "sectionid" : "BTE4B", "sectionname" : "BTech 4B", "year" : 4, "session" : 2016, "courseid" : "BTE-CS", "password" : "pm8xTE0-", "students" : 35, "addedon" : "2016-08-02 19:13:38", "teachers" : [ ] } { "_id" : ObjectId("57a0a96bd1c6ef24376477cd"), "sectionid" : "BTE4D", "sectionname" : "BTech 4D", "year" : 4, "session" : 2016, "courseid" : "BTE-CS", "password" : "sHhKr0Ov", "students" : 41, "addedon" : "2016-08-02 19:38:43", "teachers" : [ { "facultyid" : "CS-102", "subjectid" : "CS-ALGO" } ] } </code></pre> <p>I had applied a <em>$pull</em> operation using <em>mgo</em> on the <code>teachers</code> array of the first document, but I need a way to <code>$unset</code> it when it becomes empty.</p> <p>Currently, I have managed to create a workaround in Go, but I would like to get away without any workarounds.</p> <p>I hope I am not missing something very trivial here.</p> <p>Thanks!</p> </div>

ssh注解,获取不到server。

web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>sshTest1</display-name> <!-- 配置Spring的监听器,用于初始化ApplicationContext对象 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext*.xml</param-value> </context-param> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> <!-- 自动扫描action --> <init-param> <param-name>actionPackages</param-name> <param-value>com.lovo</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app> applicationContext.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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!--建立数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <!-- SQL Server数据驱动 --> <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"> </property> <!-- 数据库地址 --> <property name="url" value="jdbc:sqlserver://localhost:1433; DatabaseName=sshTest"> </property> <property name="username" value="sa"></property> <property name="password" value="123"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <!--配置Hibernate的方言--> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <!--格式化输出sql语句--> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.use_sql_comments">false</prop> </props> </property> <!--自动扫描实体 --> <property name="packagesToScan" value="com.lovo.*" /> </bean> <!-- 使用 annotation --> <context:annotation-config /> <!-- 自动扫描与装配bean --> <context:component-scan base-package="com.lovo"></context:component-scan> <!-- 采用注释的方式配置 aop --> <aop:aspectj-autoproxy /> <!-- 用注解来实现事务管理 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="txManager"/> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="select*" read-only="true"/> <tx:method name="get*" read-only="true"/> <tx:method name="load*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="query*" read-only="true"/> <tx:method name="read*" read-only="true"/> <tx:method name="sync*"/> <tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/> </tx:attributes> </tx:advice> </beans> struts.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <!-- 开启使用开发模式,详细错误提示 --> <constant name="struts.devMode" value="true" /> <!-- 将对象交给spring管理 --> <constant name="struts.objectFactory" value="spring" /> <!-- 指定资源编码类型 --> <constant name="struts.i18n.encoding" value="UTF-8" /> <!-- 指定每次请求到达,重新加载资源文件 --> <constant name="struts.i18n.reload" value="false" /> <!-- 指定每次配置文件更改后,自动重新加载 --> <constant name="struts.configuration.xml.reload" value="false" /> <!-- 默认后缀名 --> <constant name="struts.action.extension" value="action," /> </struts> action package com.lovo.action; import javax.annotation.Resource; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.springframework.stereotype.Controller; import com.lovo.bean.Emp; import com.lovo.service.EmpService; import com.opensymphony.xwork2.ActionSupport; @Namespace("/") @ParentPackage("struts-default") @Controller public class EmpAction extends ActionSupport { @Resource() public Emp emp ; private EmpService empService ; @ Action(value = "empAction", results = { @Result(name = "success", location = "/index.jsp"), @Result(name = "index", location = "/login.jsp")}) public String add() { try { empService.add(emp); } catch (Exception e) { e.printStackTrace(); return "index"; } return "success"; } public Emp getEmp() { return emp; } public void setEmp(Emp emp) { this.emp = emp; } public EmpService getEmpService() { return empService; } public void setEmpService(EmpService empService) { this.empService = empService; } } bean package com.lovo.bean; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity(name="t_emp") public class Emp implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "pk_name") private String name; @Column(name = "fk_age") private int age; public Emp(){} public Emp(int id, String name, int age) { super(); this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } dao package com.lovo.dao; import java.util.List; import javax.annotation.Resource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import com.lovo.bean.Emp; @Repository("empDao") public class EmpDao { @Resource(name="sessionFactory") private SessionFactory sessionFactory; public void add(Emp emp){ Session session = sessionFactory.getCurrentSession(); session.save(emp); } public List findAll(){ return null; } public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } } package com.lovo.service; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.lovo.bean.Emp; import com.lovo.dao.EmpDao; @Service("empService") @Transactional public class EmpService { @Resource(name="empDao") private EmpDao empDao; public EmpService(){} public void add(Emp emp) { empDao.add(emp); } public EmpDao getEmpDao() { return empDao; } public void setEmpDao(EmpDao empDao) { this.empDao = empDao; } } action 访问server的时候,没有访问到server获取数据报空指针异常。 高手帮我看看哪里错了。 。。

配置shiro后,启动时出现 is not eligible for getting processed by all BeanPostProcessors

想要学习一下shiro权限管理,在网上一边学习一边实操,但配好之后认证登录没问题,但拦截和授权却不见作用。并在启动时出现如下: >INFO 11364 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'shiroConfig' of type [com.bdg.go.config.ShiroConfig$$EnhancerBySpringCGLIB$$de04983d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) >…… 在启动项目时,shiroConfig下的所有bean都出现了以上提示: ![图片说明](https://img-ask.csdn.net/upload/202004/03/1585894947_634084.png) 在网上查了很多,基本意思就是说Bean的提前注入造成的,但我研究半天依然不知道如何解决。所以跪求大神教学。 项目是spring boot 2.0+ shiroConfig如下: ``` java @Configuration @Slf4j public class ShiroConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.timeout}") private int timeout; @Value("${spring.redis.password}") private String password; @Bean public FilterRegistrationBean delegatingFilterProxy(){ FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); DelegatingFilterProxy proxy = new DelegatingFilterProxy(); proxy.setTargetFilterLifecycle(true); proxy.setTargetBeanName("shiroFilter"); filterRegistrationBean.setFilter(proxy); return filterRegistrationBean; } /* * 创建ShrioFilterFactoryBean */ @Bean("shiroFilter") public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){ ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); log.info("经过过滤器"); // 过滤器 // 过滤链定义,从上向下顺序执行,一般将 /**放在最为下边 Map<String, String> filterMap = new LinkedHashMap<>(); /* * Shiro内置过滤器,可以实现权限相关的拦截器,常用的有: * anon:无需认证(登录)即可访问 * authc:必须认证才可以访问 * user:如果使用rememberme的功能可以直接访问 * perms:该资源必须得到资源权限才能访问 * role:该资源必须得到角色资源才能访问 */ //放过登录请求 filterMap.put("/login", "anon"); filterMap.put("/**", "authc");//其他资源全部拦截 filterMap.put("/logout", "logout"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap); shiroFilterFactoryBean.setLoginUrl("/login"); return shiroFilterFactoryBean; } @Bean("securityManager") public DefaultWebSecurityManager securityManager( @Qualifier("cookieRememberMeManager")CookieRememberMeManager cookieRememberMeManager, @Qualifier("redisCacheManager")RedisCacheManager redisCacheManager, @Qualifier("sessionManager")SessionManager sessionManager, @Qualifier("userRealm")UserRealm userRealm){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); //注入rememberme对象 securityManager.setRememberMeManager(cookieRememberMeManager); //注入session securityManager.setSessionManager(sessionManager); //注入缓存管理对象 securityManager.setCacheManager(redisCacheManager); //将Realm注入SecurityManager securityManager.setRealm(userRealm); return securityManager; } @Bean("userRealm") public UserRealm userRealm(@Qualifier("hashedCredentialsMatcher")HashedCredentialsMatcher hashedCredentialsMatcher){ UserRealm userRealm = new UserRealm(); //设置解密规则 userRealm.setCredentialsMatcher(hashedCredentialsMatcher); userRealm.setCachingEnabled(false); return userRealm; } @Bean("hashedCredentialsMatcher") public HashedCredentialsMatcher hashedCredentialsMatcher(){ HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); hashedCredentialsMatcher.setHashAlgorithmName("md5"); hashedCredentialsMatcher.setHashIterations(1); return hashedCredentialsMatcher; } @Bean("sessionManager") public SessionManager sessionManager(@Qualifier("redisSessionDAO")RedisSessionDAO redisSessionDAO){ MySessionManager mySessionManager = new MySessionManager(); mySessionManager.setSessionIdUrlRewritingEnabled(false); //取消登陆跳转URL后面的jsessionid参数 mySessionManager.setSessionDAO(redisSessionDAO); mySessionManager.setGlobalSessionTimeout(-1);//不过期 return mySessionManager; } @Bean("redisManager") public RedisManager redisManager(){ RedisManager redisManager = new RedisManager(); redisManager.setHost(host+":"+port); redisManager.setTimeout(timeout); redisManager.setPassword(password); return redisManager; } @Bean("redisCacheManager") public RedisCacheManager redisCacheManager(@Qualifier("redisManager")RedisManager redisManager){ RedisCacheManager redisCacheManager = new RedisCacheManager(); redisCacheManager.setRedisManager(redisManager); return redisCacheManager; } @Bean("redisSessionDAO") public RedisSessionDAO redisSessionDAO(){ RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); redisSessionDAO.setRedisManager(redisManager()); return redisSessionDAO; @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){ AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } @Bean("rememberMeCookie") public SimpleCookie rememberMeCookie() { log.info("ShiroConfiguration.rememberMeCookie()============="); SimpleCookie simpleCookie = new SimpleCookie("rememberMe"); simpleCookie.setMaxAge(259200); return simpleCookie; } @Bean("cookieRememberMeManager") public CookieRememberMeManager cookieRememberMeManager(@Qualifier("rememberMeCookie")SimpleCookie rememberMeCookie) { log.info("ShiroConfiguration.rememberMeManager()========"); CookieRememberMeManager manager = new CookieRememberMeManager(); manager.setCookie(rememberMeCookie); return manager; } } ``` UserRealm: ``` @Slf4j public class UserRealm extends AuthorizingRealm { @Autowired private UserService userService; @Autowired private RoleService roleService; @Autowired private PrivilegeService privilegeService; /** * 前置处理非空对象 * shiroFilter在Spring自动装配bean之前实例化 * 相关联的Bean都被初始化完成且没有被代理(包括BeanPostProcessor也会无效)导致事务失效等...... * 使用动态获取代理对象即可解决 */ protected void preHandleNull() { if (userService == null) { userService = SpringContextUtils.getContext().getBean(UserService.class); } if (roleService == null) { roleService = SpringContextUtils.getContext().getBean(RoleService.class); } if (privilegeService == null) { privilegeService = SpringContextUtils.getContext().getBean(PrivilegeService.class); } } /* * 执行授权逻辑:因为设计每个用户只有一个角色,所以roleMapper.getRoleByUserName(user)返回值只有一个实体。 * @author Innocence */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { preHandleNull(); log.info("自定义UserRealm执行授权逻辑开始=================="); User user = (User) principalCollection.getPrimaryPrincipal(); if (null != user) { List<String> roleLists = new ArrayList<>(); List<String> privilegeLists = new ArrayList<>(); Role role = (Role) roleService.findRoleByUserName(user.getUsername()).getData(); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); roleLists.add(role.getName()); info.addRoles(roleLists); List<Privilege> privilegeByRoleId = (List<Privilege>) privilegeService.getPrivilegeByRoleId(role).getData(); for (Privilege privilege : privilegeByRoleId) { privilegeLists.add(privilege.getPrivilegeName()); } info.addStringPermissions(privilegeLists); return info; } return null; } /* * 执行认证逻辑 * @author Innocence */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { preHandleNull(); log.info("自定义UserRealm执行认证逻辑开始=================="); UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; String username = token.getUsername(); User userInfo = (User) userService.findUserInfoByUserName(username).getData(); if (userInfo == null) { return null; } log.info("通过用户名查到的用户信息userInfo:[" + userInfo.toString() + "]"); return new SimpleAuthenticationInfo( userInfo, userInfo.getPassword(), getName() ); } } ```

C/C++学习指南全套教程

C/C++学习的全套教程,从基本语法,基本原理,到界面开发、网络开发、Linux开发、安全算法,应用尽用。由毕业于清华大学的业内人士执课,为C/C++编程爱好者的教程。

定量遥感中文版 梁顺林著 范闻捷译

这是梁顺林的定量遥感的中文版,由范闻捷等翻译的,是电子版PDF,解决了大家看英文费时费事的问题,希望大家下载看看,一定会有帮助的

YOLOv3目标检测实战:训练自己的数据集

YOLOv3是一种基于深度学习的端到端实时目标检测方法,以速度快见长。本课程将手把手地教大家使用labelImg标注和使用YOLOv3训练自己的数据集。课程分为三个小项目:足球目标检测(单目标检测)、梅西目标检测(单目标检测)、足球和梅西同时目标检测(两目标检测)。 本课程的YOLOv3使用Darknet,在Ubuntu系统上做项目演示。包括:安装Darknet、给自己的数据集打标签、整理自己的数据集、修改配置文件、训练自己的数据集、测试训练出的网络模型、性能统计(mAP计算和画出PR曲线)和先验框聚类。 Darknet是使用C语言实现的轻型开源深度学习框架,依赖少,可移植性好,值得深入探究。 除本课程《YOLOv3目标检测实战:训练自己的数据集》外,本人推出了有关YOLOv3目标检测的系列课程,请持续关注该系列的其它课程视频,包括: 《YOLOv3目标检测实战:交通标志识别》 《YOLOv3目标检测:原理与源码解析》 《YOLOv3目标检测:网络模型改进方法》 敬请关注并选择学习!

sql语句 异常 Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your

在我们开发的工程中,有时候会报 [Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ------ 这种异常 不用多想,肯定是我们的sql语句出现问题,下面...

浪潮集团 往年的软件类 笔试题 比较详细的哦

浪潮集团 往年的软件类 笔试题 比较详细的哦

2019 AI开发者大会

2019 AI开发者大会(AI ProCon 2019)是由中国IT社区CSDN主办的AI技术与产业年度盛会。多年经验淬炼,如今蓄势待发:2019年9月6-7日,大会将有近百位中美顶尖AI专家、知名企业代表以及千余名AI开发者齐聚北京,进行技术解读和产业论证。我们不空谈口号,只谈技术,诚挚邀请AI业内人士一起共铸人工智能新篇章!

I2c串口通信实现加速度传感器和FPGA的交流

此代码能实现加速度传感器与FPGA之间的交流,从而测出运动物体的加速度。

Python可以这样学(第一季:Python内功修炼)

董付国系列教材《Python程序设计基础》、《Python程序设计(第2版)》、《Python可以这样学》配套视频,讲解Python 3.5.x和3.6.x语法、内置对象用法、选择与循环以及函数设计与使用、lambda表达式用法、字符串与正则表达式应用、面向对象编程、文本文件与二进制文件操作、目录操作与系统运维、异常处理结构。

微信公众平台开发入门

本套课程的设计完全是为初学者量身打造,课程内容由浅入深,课程讲解通俗易懂,代码实现简洁清晰。通过本课程的学习,学员能够入门微信公众平台开发,能够胜任企业级的订阅号、服务号、企业号的应用开发工作。 通过本课程的学习,学员能够对微信公众平台有一个清晰的、系统性的认识。例如,公众号是什么,它有什么特点,它能做什么,怎么开发公众号。 其次,通过本课程的学习,学员能够掌握微信公众平台开发的方法、技术和应用实现。例如,开发者文档怎么看,开发环境怎么搭建,基本的消息交互如何实现,常用的方法技巧有哪些,真实应用怎么开发。

机器学习初学者必会的案例精讲

通过六个实际的编码项目,带领同学入门人工智能。这些项目涉及机器学习(回归,分类,聚类),深度学习(神经网络),底层数学算法,Weka数据挖掘,利用Git开源项目实战等。

eclipseme 1.7.9

eclipse 出了新的eclipseme插件,官方有下载,但特慢,我都下了大半天(可能自己网速差)。有急需要的朋友可以下哦。。。

Spring Boot -01- 快速入门篇(图文教程)

Spring Boot -01- 快速入门篇 今天开始不断整理 Spring Boot 2.0 版本学习笔记,大家可以在博客看到我的笔记,然后大家想看视频课程也可以到【慕课网】手机 app,去找【Spring Boot 2.0 深度实践】的课程,令人开心的是,课程完全免费! 什么是 Spring Boot? Spring Boot 是由 Pivotal 团队提供的全新框架。Spring Boot...

HoloLens2开发入门教程

本课程为HoloLens2开发入门教程,讲解部署开发环境,安装VS2019,Unity版本,Windows SDK,创建Unity项目,讲解如何使用MRTK,编辑器模拟手势交互,打包VS工程并编译部署应用到HoloLens上等。

最简单的倍频verilog程序(Quartus II)

一个工程文件 几段简单的代码 一个输入一个输出(50Mhz倍频到100Mhz)

计算机组成原理实验教程

西北工业大学计算机组成原理实验课唐都仪器实验帮助,同实验指导书。分为运算器,存储器,控制器,模型计算机,输入输出系统5个章节

4小时玩转微信小程序——基础入门与微信支付实战

这是一个门针对零基础学员学习微信小程序开发的视频教学课程。课程采用腾讯官方文档作为教程的唯一技术资料来源。杜绝网络上质量良莠不齐的资料给学员学习带来的障碍。 视频课程按照开发工具的下载、安装、使用、程序结构、视图层、逻辑层、微信小程序等几个部分组织课程,详细讲解整个小程序的开发过程

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

基于RSA通信密钥分发的加密通信

基于RSA通信密钥分发的加密通信,采用pycrypto中的RSA、AES模块实现

不同变质程度煤尘爆炸残留气体特征研究

为分析不同变质程度煤尘爆炸残留气体成分的特征规律,利用水平管道煤尘爆炸实验装置进行了贫瘦煤、肥煤、气煤、长焰煤4种不同变质程度的煤尘爆炸实验,研究了不同变质程度煤尘爆炸后气体残留物含量的差异,并对气体

设计模式(JAVA语言实现)--20种设计模式附带源码

课程亮点: 课程培训详细的笔记以及实例代码,让学员开始掌握设计模式知识点 课程内容: 工厂模式、桥接模式、组合模式、装饰器模式、外观模式、享元模式、原型模型、代理模式、单例模式、适配器模式 策略模式、模板方法模式、观察者模式、迭代器模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式 课程特色: 笔记设计模式,用笔记串连所有知识点,让学员从一点一滴积累,学习过程无压力 笔记标题采用关键字标识法,帮助学员更加容易记住知识点 笔记以超链接形式让知识点关联起来,形式知识体系 采用先概念后实例再应用方式,知识点深入浅出 提供授课内容笔记作为课后复习以及工作备查工具 部分图表(电脑PC端查看):

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

软件测试2小时入门

本课程内容系统、全面、简洁、通俗易懂,通过2个多小时的介绍,让大家对软件测试有个系统的理解和认识,具备基本的软件测试理论基础。 主要内容分为5个部分: 1 软件测试概述,了解测试是什么、测试的对象、原则、流程、方法、模型;&nbsp; 2.常用的黑盒测试用例设计方法及示例演示;&nbsp; 3 常用白盒测试用例设计方法及示例演示;&nbsp; 4.自动化测试优缺点、使用范围及示例‘;&nbsp; 5.测试经验谈。

几率大的Redis面试题(含答案)

本文的面试题如下: Redis 持久化机制 缓存雪崩、缓存穿透、缓存预热、缓存更新、缓存降级等问题 热点数据和冷数据是什么 Memcache与Redis的区别都有哪些? 单线程的redis为什么这么快 redis的数据类型,以及每种数据类型的使用场景,Redis 内部结构 redis的过期策略以及内存淘汰机制【~】 Redis 为什么是单线程的,优点 如何解决redis的并发竞争key问题 Red...

手把手实现Java图书管理系统(附源码)

【超实用课程内容】 本课程演示的是一套基于Java的SSM框架实现的图书管理系统,主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的java人群。详细介绍了图书管理系统的实现,包括:环境搭建、系统业务、技术实现、项目运行、功能演示、系统扩展等,以通俗易懂的方式,手把手的带你从零开始运行本套图书管理系统,该项目附带全部源码可作为毕设使用。 【课程如何观看?】 PC端:https://edu.csdn.net/course/detail/27513 移动端:CSDN 学院APP(注意不是CSDN APP哦) 本课程为录播课,课程2年有效观看时长,大家可以抓紧时间学习后一起讨论哦~ 【学员专享增值服务】 源码开放 课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化

jsp+servlet入门项目实例

jsp+servlet实现班级信息管理项目

winfrom中嵌套html,跟html的交互

winfrom中嵌套html,跟html的交互,源码就在里面一看就懂,很简单

Java面试题大全(2020版)

发现网上很多Java面试题都没有答案,所以花了很长时间搜集整理出来了这套Java面试题大全,希望对大家有帮助哈~ 本套Java面试题大全,全的不能再全,哈哈~ 一、Java 基础 1. JDK 和 JRE 有什么区别? JDK:Java Development Kit 的简称,java 开发工具包,提供了 java 的开发环境和运行环境。 JRE:Java Runtime Environ...

python实现数字水印添加与提取及鲁棒性测试(GUI,基于DCT,含测试图片)

由python写的GUI,可以实现数字水印的添加与提取,提取是根据添加系数的相关性,实现了盲提取。含有两种攻击测试方法(高斯低通滤波、高斯白噪声)。基于python2.7,watermark.py为主

Xshell6完美破解版,亲测可用

Xshell6破解版,亲测可用,分享给大家。直接解压即可使用

你连存活到JDK8中著名的Bug都不知道,我怎么敢给你加薪

CopyOnWriteArrayList.java和ArrayList.java,这2个类的构造函数,注释中有一句话 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public ArrayList(Collection&lt;? ...

相关热词 c#怎么获得线程名 c# usb 采集器 c# sort() c#面对对象的三大特性 c# 打印 等比缩放 c#弹出右键菜单 c# 系统托盘图标 c# 键值对 键可以重复 c# 鼠标移上去提示 c#结构体定义
立即提问