【毕设】每日项目问题2

2015年5月2日:

还是改之前对大街的爬虫。我的爬虫目前是2部分,一部分宣讲会,一部分校招项目

校招那个因为嵌套的层数比较多,所以我先动手改的是宣讲会部分。

本来宣讲会部分很简单,不需要登陆,直接访问api就行。我写完以后就写项目主体去了,就没管它,也是马上要验收了才拿出来看下发现不能用了。

原因就是必须要登陆才能获取宣讲会信息不然报错。



没办法我只能浏览器模拟登陆,获取一些动态生成的信息。

本来是直接urllib2.urlopen()就行的,唉,大街好好的整什么幺蛾子。

我的解决方案:

webdriver模拟登陆,获取必要信息,设置好请求头,再urllib2.urlopen()





我要获取的就是那个_CSRFToken和cookie

前者直接解析个page_source,在javascript中生成

后者的话包含不少东西,而且每次东西都不一样!我上面的那个截图里面的_utma,_utmc,_utmz这种东西我当时写的时候根本就没有。。。。。

我本来是是想用CookieLib.CookieJar的,但是set_cookie 语法实在不熟,没办法,我是建了个cookiestring字符串,然后用的只有cookie中的一部分。。。。。

再headers={

 “User-Agent”:“ xxxxxx ”,

“Cookie”: cookiestring,

}

然后这样就行了。




2015年5月3日:

python跳出两层循环:这个百度一下有很多文章

    for i in range(1,total):
        URL="http://campus.dajie.com/progress/index/ajaxSearch?ajax=1&major=73&_CSRFToken=&page=%d" %i
        #print URL
        res=urllib2.urlopen(URL, timeout=10).read()   #因为传的是json,所以可以直接读,如果是html的解析,还是用bs
        res_json=json.loads(res)
        project_list_json=res_json["data"]["lists"]
        #print project_list
        for item in project_list_json:  
            if(item["id"]<=max_id):
                break
        else:
            continue
        break 






2015年5月4日:

今天搞校招部分的爬虫,改了不少东西

1.

db.course.find( { "lectures.lectures_count": { $exists: true } } )

2.req=urllib2.Request(detail_url,headers=headers)

这个  【headers=】 一定要有



3.

解决方案:

collection.update({"id":id},{"$set":{"realURL":realURL.decode("unicode_escape"),"pro_detail":pro_detail.decode("unicode_escape")}})

就是这个str.decode(“unicode_escape”)






2015年5月5日:

jsp页面,校招详情,需要显示我从大街爬的校招详情。

我当时爬的时候连着html标签一起爬下来的,但是现在如何显示出了点问题。

1.方案一:

用<% out.printlin()   %>  或者<%= %>

<s:property  value="#request.project.pro_detail">

不行

2.方案二:

<div id="pro_detail"></div>

function onload(){
var div1=document.getElementById("detail");
    div1.innerHTML='<s:property value="#request.project.pro_detail"/>'
}

<body οnlοad="onload()">

不行

3.方案三:

<c:out value="${project.pro_detail}"  escapeXml="false" />

出了点问题-----attribute value does not accept any expressions,百度一下就行了

解决办法:<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

成功



-----------------------------------------------------------------



解析struts.xml报错:

严重: The content of element type "package" must match "(result-types?,interceptors?,default-interceptor-ref?,default-action-ref?,default-class-ref?,global-results?,global-exception-mappings?,action*)". at (null:71:12)

原因:package里元素必须按照一定的顺序排列:

result-types
interceptors
default-interceptor-ref
default-action-ref
default-class-ref
global-results
global-exception-mappings
action*(所有action放到最后)

其实我在配置struts拦截器 【免登陆】的时候出了不少错。主要还是自己不熟悉吧。




----------------------------------------------------------------------------------------



碰到一个问题,就是js写入的cookie在后台java读出来不对!



关键就在这个account!!!@及后面的字符无法显示    http://www.iteye.com/problems/15629

我猜想是编码问题因为感觉其他网站的cookie都不是直接存邮箱。

查了一下,http://www.blogjava.net/stone2083/archive/2010/11/03/336923.html

用了escape和encodeURI,http://huangqiqing123.iteye.com/blog/1769631

解决方案:

js写入的时候  :

document.cookie = "account=" + encodeURIComponent(document.getElementById("account").value)+ "; expires=" + date.toGMTString();

java后台获取:

 for (Cookie cookie : cookies) {  
            	//System.out.println(cookie.getName()+cookie.getMaxAge()+cookie.getValue());
                if (cookie.getName().equals("account")) {
                    account= URLDecoder.decode(cookie.getValue());  
                } 
                if (cookie.getName().equals("pwd")) {  
                    pwd= cookie.getValue();  
                }
} 


成功



2015年5月6日:

昨天我不是配了个免登陆的拦截器吗,今天发现有问题。

LoginInterceptor.java

package com.whu.interceptor;


import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.whu.entity.User;
import com.whu.service.UserService;

public class LoginInterceptor extends AbstractInterceptor{

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
<span style="white-space:pre">	</span>// 取得请求相关的ActionContext实例  
<span style="white-space:pre">	</span>System.out.println("enter LoginInterceptor");
        ActionContext ctx = invocation.getInvocationContext();  
        Map session = ctx.getSession();  
	//Map<String,Object> session = ActionContext.getContext().getSession(); 
        Object uid = session.get("uid");  
        System.out.println(uid);
        if (uid!=null) {  
            //System.out.println("test");  
        	//System.out.println();
            return invocation.invoke();  
        }  
        System.out.println("enter cookie");
        HttpServletRequest request = ServletActionContext.getRequest();
        System.out.println(request.getCookies());
        Cookie[] cookies = request.getCookies();  
        //JSESSIONID=2FB2D09102E523CD8B825E0876A95198; account=2453929471@qq.com; pwd=96e79218965eb72c92a549dd5a330112
        if (cookies != null) {
        	String account=null;
            String pwd=null;
            for (Cookie cookie : cookies) {  
            	//System.out.println(cookie.getName()+cookie.getMaxAge()+cookie.getValue());
                if (cookie.getName().equals("account")) {
                    account= URLDecoder.decode(cookie.getValue());  
                } 
                if (cookie.getName().equals("pwd")) {  
                    pwd= cookie.getValue();  
                }
            }  
            System.out.println(account);
            System.out.println(pwd);
            if(account!=null && pwd!=null){
            	UserService us=new UserService();
            	User user =new User();
            	user.setAccount(account);
            	user.setPwd(pwd);
            	//System.out.println(user.toString());
            	int result=us.getUser(user);
            	//System.out.println(result);
            	if(result!=-1){
            		session.put("uid", result);
            		//System.out.println(session.get("uid"));
            		return invocation.invoke(); 
            	}
            }
        }
  
        //ctx.put("tip", "你还没有登录");  
        return Action.LOGIN;  
	}

}

struts.xml

  <package name="user" namespace="/" extends="struts-default">
    <!-- 定义一个拦截器 -->  
        <interceptors>  
            <interceptor name="authority"  class="com.whu.interceptor.LoginInterceptor"></interceptor>          
	        <interceptor-stack name="myStack">
	        	<interceptor-ref name="defaultStack"></interceptor-ref>
	            <interceptor-ref name="authority" ></interceptor-ref> 
	        </interceptor-stack>       
        </interceptors> 
        <action name="home" class="com.whu.action.QueryAction" method="queryAll">
            <interceptor-ref name="myStack"></interceptor-ref>
            <result name="success">index.jsp</result>             
        </action>
</package>

QueryAction.java

package com.whu.action;

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

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.whu.dao.impl.CorpDaoImpl;
import com.whu.dao.impl.JobDaoImpl;
import com.whu.dao.impl.ProjectDaoImpl;
import com.whu.dao.impl.XjhDaoImpl;
import com.whu.entity.Comment;
import com.whu.entity.JobBasic;
import com.whu.entity.Project;
import com.whu.entity.User;
import com.whu.entity.Xjh;
import com.whu.service.CommonService;

public class QueryAction extends ActionSupport{
	
	private static Logger logger = LogManager.getLogger(QueryAction.class);	
	private Map<String, Object> req;	
	
	private int project_id;
	public int getProject_id() {
		return project_id;
	}
	public void setProject_id(int project_id) {
		this.project_id = project_id;
	}
	
	Map<String,Object> session = ActionContext.getContext().getSession(); 
	
	
	
	
	//首页返回5条数据
	public String queryAll(){
		//XjhDaoImpl xdi=new XjhDaoImpl();
		//List<Xjh> xjhList=xdi.findAll();
		
		//设定是每页20条数据,首页的话返回5条,宣讲会按时间升序排序	
		//校招部分也是每页20条数据,首页返回5条,校招按网申时间降序排序
		//职位部分也是每页20条数据,首页返回5条,按jobid排序
		//同时返回个人头像
		logger.entry("queryAll");
		try {
			CommonService cs=new CommonService();
			List<Xjh> xjhList= cs.getXjhInfo(1, 5);
			//System.out.println(xjhList.toString());
			req = (Map<String, Object>) ActionContext.getContext().get("request");
			req.put("xjhList", xjhList);
			List<Project> projectList=cs.getProjectInfo(1,5);
			//System.out.println(projectList.toString());
			req.put("projectList", projectList);
			List<JobBasic> jobList=cs.getJobInfo(1, 5);
			//System.out.println(jobList.toString());
			req.put("jobList", jobList);
			String icon;
			System.out.println("action session:"+session.get("uid"));
			if(session.get("uid")!=null){
				icon=cs.getIcon((Integer) session.get("uid"));
				logger.debug("enter getXjhCollects");
				User user=cs.getUser((Integer) session.get("uid"));
				//System.out.println("action:"+user.getXjhList());
				req.put("user", user);
			}else{
				icon="imgs/icon/0.jpg";
			}
			req.put("icon", icon);
			logger.debug("queryAll success");
		} catch (Exception e) {
			logger.error("");
			return ERROR;
		}
		
		
        logger.exit("queryAll");
		return SUCCESS;
	}

问题在于,我start Tomcat后,直接访问home

System.out.println("action session:"+session.get("uid"));
这个session.get("uid")取不到值,而且

有两个JSESSIONID,再次刷新home,uid就能取到了。

http://bbs.youkuaiyun.com/topics/350032270

http://www.iteye.com/problems/102134

翻到一篇文章:http://www.reader8.cn/jiaocheng/20120913/2006969.html

说是:因为这个action将会以单独的线程执行,所以你不能用ActionContext,因为它是ThreadLocal.这也就是说如果你要访问 session数据,你必须实现 SessionAware接口而不是调用ActionContext.getSesion() 。同理,要去到request要实现RequestAware接口。

public class SomeAction extends ActionSupport implements SessionAware, RequestAware{
	 protected Map<String, Object> session;
	protected Map<String, Object> request;
	@Override
	 public void setSession(Map<String, Object> session) {
		 this.session = session;
	 }

	 @Override
	 public void setRequest(Map<String, Object> request) {
		 this.request = request;
	}
}

我试过:

0.拦截器中:ActionContext ctx = invocation.getInvocationContext();  
                    Map session = ctx.getSession();  

   action中:Map<String,Object> session = ActionContext.getContext().getSession(); 

1. 拦截器中:Map<String,Object> session = ActionContext.getContext().getSession(); 

    action中:Map<String,Object> session = ActionContext.getContext().getSession(); 

还是第一次访问取不到

2.拦截器中:HttpSession session = ServletActionContext.getRequest().getSession();

  action中:HttpSession session = ServletActionContext.getRequest().getSession();

还是第一次访问取不到

试了两种我就不打算再试了,包括那个什么SessionAware什么的。

我忽然想到是否跟JSESSIONID有关。 

我的session虽然put进去了,但是是put到新的session中,而我在action中取的session任然是传过来的旧的session??

解决方案我目前猜测是:

关闭服务器后删除全部session,主要是浏览器的JSESSIONID

不过我暂时不打算管这个问题,只要服务器不轻易重启就没有问题。




------------------------------------------------------------------------------



<s:iterator>下的 收藏问题 以及  checkbox根据后台返回值自动勾选的问题


本来想着是个挺简单的问题,但是没想到弄起来还真不知道怎么弄。

这个问题我昨天就在搞,但是一天过去了也没有找到合适的方法。

本来我是在iterator中套了一个form:

                               <form action="collectXjh" method="post"  name="xxx">
				<td><input type="hidden" name="uid" id="uid" value="${sessionScope.uid}">
				    <input type="hidden" name="xjh_id" value='<s:property value="#xjh.xjh_id" />'>
				    <input type="hidden" name="a" >
				    <input type="checkbox" name="isCollect" οnchange="updCollect()">	
				</form>

function updCollect(){
	var uid=document.getElementById("uid").value;
	if(uid==""){
		alert("需要您先登录!");
		document.getElementById("isCollect").checked=false;
	}else{
		document.getElementById("a").value= document.getElementById("isCollect").checked;
		//alert(document.getElementById("a").value);
		document.getElementById("isCollectForm").submit();
	}
	//var isChecked = document.getElementById("isCollect").checked;
	//alert(isChecked);   //选中为true 
		
	//alert("ok");
}


但是这个我犯了一个致命错误,document.getElementById() 是取不到我想要的那个值的!!!

也就是说,只要有这种iterator的情况下,document.getElementById() 就不能用!


没办法,还是改用button来提交form。

我本来的想法是,req.put("xjhList",xjhList )

                                req.put("xjhs",xjhs)   //但是这里可能是mongodb的编码问题,这个xjhs作为一个int[]  在控制台的输出形式非常奇怪,浏览器更是无法显示

我后来还是返回了一个完整的user对象,req.put("user",user) ,   显示到浏览器中总算是正常了  <input type="text" value='<s:property value="#request.user.xjhList" />'>

获得这个收藏的列表以后,我是打算用网上那种  <s:if test="  xxx.contains(   )  "></s:if>的方法做的,但是我对这个实在不熟,一直调不出来正确的显示。

-------------可行的方案--------------

还是我一个老师给的提醒,就是直接在action中做好匹配,就是哪些宣讲会被收藏了,给个tag,再传到前台来。

action

req = (Map<String, Object>) ActionContext.getContext().get("request");
			List<Xjh> xjhList;
			if(session.get("uid")==null){
				xjhList= cs.getXjhInfo(1, 5);
				//System.out.println(xjhList.toString());								
			}else{
				System.out.println("enter setIsCollect");
				int uid = (Integer) session.get("uid");
				xjhList= cs.getXjhInfo(1, 5, uid);
			}
			req.put("xjhList", xjhList);

CommonService

	//访问主页,从数据库中读取?条宣讲会数据--后台已排序
	public List<Xjh> getXjhInfo(int pageNum,int amount,int uid) throws Exception{
		XjhDaoImpl xdi=new XjhDaoImpl();
		//List xl=xdi.getXjh_id(pageNum,amount);
		List<Xjh> xjhList=xdi.getXjhInfo(pageNum,amount);
		
		UserDaoImpl udi=new UserDaoImpl();
		int[] xc=udi.getXjhCollects(uid);
		int len= xc.length;
		
		Iterator iter=xjhList.iterator();
		while(iter.hasNext()){
			Xjh xjh=(Xjh) iter.next();
			int xjh_id=xjh.getXjh_id();
			for(int i=0;i<len;i++){
				if(xc[i]!=xjh_id){
					//System.out.println(xjh_id);
					//xjh.setIsCollect(1);    //1表示被收藏,默认是0??
					continue;
				}else{
					xjh.setIsCollect(1);
					System.out.println("getCollect"+xjh_id);
					break;
				}
			}
		}		
		return xjhList;
	}
	
	//访问主页,从数据库中读取?条校招数据--后台已排序
		public List<Xjh> getXjhInfo(int pageNum,int amount) throws Exception {
			XjhDaoImpl xdi=new XjhDaoImpl();
			List<Xjh> xjhList=xdi.getXjhInfo(pageNum, amount);
			return xjhList;
		}





--------------------------------------------------------------------------------------------



富文本编辑器。

用的ueditor    下载地址:http://ueditor.baidu.com/website/download.html#ueditor

这里不知道除了一个什么问题,当时一直显示不对。

我当时的做法是,解压以后,修改文件夹的名字为ueditor, 然后把这个文件夹考到webroot下,但是考进去以后发现一直报错,中文字符也不能正常显示。

我也是蠢,用notepad++正常打开后再把文件内容复制过去。

然后问题来了,调了几个小时,百度了无数博客,照着走一直不行。



没办法,我重下了一遍,解压以后把里面的文件全考到webroot下的ueditor文件夹下,然后-------它就ok了。。。。。。。==!




-------------------------------------------------------------------------------------------



form写的时候忘记method=“post”了,结果中文乱码,亏我还百度半天中文乱码解决。。。。。





2015年5月8日,项目结束。

很遗憾有个部分没有做完。

整个项目我感受最深的一点就是-----partner一定要好好选,我的前端是个巨坑我会说?!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值