Sql注入、文件上传与手机品牌信息抓取解决方案

Sql注入问题解决方案

 

/**

* 根据传入的用户名与密码查找用户

* @author wei.luo

* @createTime 2011-12-28

* @param String name 用户名

* @param String password 密码

* @return User 返回查找到的用户

*/

public User getByNameAndPassword(final String name,final String password) throws DaoExceptions {

final User user=new User();

final String sql="select * from users where user_name=? and user_pass=?";

PreparedStatementCreator psc = new PreparedStatementCreator (){

public PreparedStatement createPreparedStatement(Connection con)

throws SQLException {

PreparedStatement ps=null;

ps = con.prepareStatement(sql);

ps.setString(1, name);

ps.setString(2, password);

 

return ps;

}

};

 

this.getJdbcTemplate().query(psc, new RowCallbackHandler(){

public void processRow(ResultSet rs) throws SQLException {

user.setUserId(rs.getString("user_id"));

user.setUserInfo(rs.getString("user_info"));

user.setUserAddDate(rs.getDate("user_add_date"));

user.setUserLevel(rs.getInt("user_level"));

user.setUserName(rs.getString("user_name"));

user.setUserPassword(rs.getString("user_pass"));

}

});

return user;

}

 

文件上传解决方案

方法一

1.spring-mvc项目中引入commons-fileupload.jar包和commons-io.jar包还有jspSmartUpload.jar包,并在webmvc-config.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:mvc="http://www.springframework.org/schema/mvc"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

">

…………

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"/>

…………

 

2.jsp页面form表单,设置如下:
				

<form name="form1" id="form1" enctype="multipart/form-data" method="post" action="${ctx }/manage/manageInfo/phone/new.do">

 

</form>

 

3.编写上传文件代码:

    /**

     * 新增机型

     * @author luowei

     * @createTime 2012-1-12

     * @param phone

     * @param request

     * @param result

     * @return

     */

    @RequestMapping(value = "/new")

    public String newPhone(Phone phone,DefaultMultipartHttpServletRequest request,

            HttpServletResponse response) {

        MultipartFile file=request.getFile("phoneimage1");

        String fileName = file.getOriginalFilename();

        String path = request.getRealPath("images/phone");

        File targetFile = new File(path, fileName);

if(!targetFile.exists()){

targetFile.mkdirs();

}

try {

file.transferTo(targetFile);    //上传目标文件

} catch (Exception e) {

e.printStackTrace();

}

phone.setPhoneImage("/ttpod/images/phone/"+fileName);

        phone.setPhonebrand(new Phonebrand(Integer.parseInt((String)request.getParameter("brandName"))));

        phone.setPlatform(new Platform(Integer.parseInt((String)request.getParameter("platformName"))));

    phone.setPhoneAddDate(DateUtil.datetimeToDate());

        this.phoneManageService.save(phone);

        

        //处理其它异外情况,。。。。。。。

        

        String currentPage = (String) this.getSessionAttribute(request,"currentPage");

        this.sendRedirect(response, currentPage);

 

        return null;

    }

 

方法二

直接解析HttpServletRequest,示例代码如下,(表单格式仍然为:enctype="multipart/form-data")

/**

* 新增机型

* @author luowei

* @createTime 2012-1-12

* @param phone

* @param request

* @param result

* @return

*/

@RequestMapping(value = "/new")

public String newPhone(Phone phone,HttpServletRequest request,HttpServletResponse response) {

Phone phone=new Phone();

FileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(factory);

try

{

request.setCharacterEncoding("utf-8");

List items = upload.parseRequest(request); //解析HttpServletRequest

Iterator iter = items.iterator();

while (iter.hasNext())

{

FileItem item = (FileItem) iter.next();

if (item.isFormField()) //如果是普通表单字段

{

String name = item.getFieldName(); //取得表单中字段的名

String value = item.getString("utf-8"); //取得表单中字段的值

if(name.equals("phoneName")){phone.setPhoneName(value);}

if(name.equalsIgnoreCase("brandName")){

phone.setPhonebrand(new Phonebrand(Integer.parseInt(value))); //将指定的手机品牌关联到机型

}

if(name.equals("platformName")){

phone.setPlatform(new Platform(Integer.parseInt(value))); //将指定的手机平台关联到机型

}

if(name.equals("phoneHeadName")){phone.setPhoneName(value);}

if(name.equals("phoneResolution")){phone.setPhoneName(value);}

if(name.equals("phoneStatus")){phone.setPhoneStatus(Integer.parseInt(value));}

if(name.equals("phoneDesc")){phone.setPhoneDesc(Integer.parseInt(value));}

}

else if (!item.isFormField()) //如果不是普通表单字段,即文件字段

{

String fieldName = item.getFieldName();

String fileName = item.getName();

String contentType = item.getContentType();

boolean isInMemory = item.isInMemory();

long sizeInBytes = item.getSize();

//System.out.println(fieldName+":"+fileName+":"+contentType+":"+sizeInBytes);

String path=request.getRealPath("images/phone");

File uploadedFile = new File(path,GetId.getNewId()+fileName); //创建一个上传文件对象

try

{

item.write(uploadedFile); //将要上传的文件对象写到item

phone.setPhoneImage("/ttpod/images/phone/"+uploadedFile.getName());

 

} catch (Exception e)

{

e.printStackTrace();

phone.setPhoneImage("");

}

 

System.out.println(path);

}

}

} catch (FileUploadException e)

{

e.printStackTrace();

}

catch(UnsupportedEncodingException e1)

{

e1.printStackTrace();

}

phone.setPhoneAddDate(DateUtil.datetimeToDate()); //phone对象的添加日期字段设置值

this.phoneManageService.save(phone); //执行保存

String currentPage = (String) this.getSessionAttribute(request,"currentPage");

this.sendRedirect(response, currentPage);

 

return null;

}

 

手机品牌信息抓取解决方案

spring-mvc项目中引入htmlparser.jar包,抓取中关村的手机品牌信息,示例代码如下:

package com.luowei.common.service.imp;

 

import java.util.ArrayList;

import java.util.List;

 

import javax.annotation.Resource;

 

import org.htmlparser.*;

import org.htmlparser.filters.StringFilter;

import org.htmlparser.nodes.*;

import org.htmlparser.util.*;

import org.htmlparser.tags.*;

import org.springframework.stereotype.Service;

 

import com.luowei.common.dao.TPhonebrandDAO;

import com.luowei.common.model.Action;

import com.luowei.common.model.TPhonebrand;

import com.luowei.common.service.BaseService;

import com.luowei.common.service.ITPhonebrandService;

/**

* @className:TPhonebrandManageService.java

* @classDescription:手机品牌Service

* @author:luowei

* @createTime:2012-1-12

*/

@Service

public class TPhonebrandManageService extends BaseService<TPhonebrand> implements ITPhonebrandService

{

@Resource(name="TPhonebrandDAO")

private TPhonebrandDAO tPhonebrandDAO;

 

 

public TPhonebrandDAO gettPhonebrandDAO() {

return tPhonebrandDAO;

}

 

public void settPhonebrandDAO(TPhonebrandDAO tPhonebrandDAO) {

this.tPhonebrandDAO = tPhonebrandDAO;

}

 

/**

* 品牌类别过滤器

* @author luowei

* @createTime 2012-1-13

* @param

* @return

*/

class BrandFilter extends StringFilter

{

public BrandFilter(String pattern)

{

super(pattern);

}

public boolean accept(Node node) {

if(node!=null)

{

if(node instanceof TagNode)

{

TagNode tn=(TagNode)node;

String vl=tn.getAttribute("class");

if(vl!=null&&vl.equals(this.getPattern()))

{

return true;

}

}

}

return false;

}

}

 

/**

* 从中关村抓取品牌信息

* @author luowei

* @createTime 2012-1-13

* @param

* @return

*/

public List<TPhonebrand> getInforFromZOL()

{

try

{

//初始两个页面解析器

Parser parser1=new Parser("http://detail.zol.com.cn/category/57.html");

Parser parser2=new Parser("http://detail.zol.com.cn/category/57.html");

List<TPhonebrand> tPhonebrandList = new ArrayList<TPhonebrand>();

String[] manu={"manu normal","manu txt"};

//获取普通品牌

tPhonebrandList.addAll(findNormalBrand(parser1.parse(new BrandFilter((manu[0])))));

//获取其它品牌

tPhonebrandList.addAll(findOtherBrand(parser2.parse(new BrandFilter(manu[1]))));

return tPhonebrandList;

}

catch(Exception e)

{

e.printStackTrace();

}

return null;

}

 

/**

* 获取普通品牌(class=manu nomal)的品牌

* manu nomal 下的li子标签如下结构:

* <li>

* <a href="/cell_phone_index/subcate57_98_list_1.html">

* <img alt="Samsung(三星) 手机" src="http://2c.zol-img.com.cn/manu_photo/98_.jpg">

* </a>

* <br>

* <a title="Samsung(三星) 手机" href="/cell_phone_index/subcate57_98_list_1.html">Samsung(三星)</a>

* </li>

* @author luowei

* @createTime 2012-1-13

* @param

* @return

*/

 

public List<TPhonebrand> findNormalBrand(NodeList nl1)

{

List<TPhonebrand> list=new ArrayList<TPhonebrand>();

for(int i=0;i<nl1.size();i++)

{

Node n1=nl1.elementAt(i); //获取第iclass=manu normal的结点

NodeList nl2=n1.getChildren();

for(int j=0;j<nl2.size();j++)

{

Node n2=nl2.elementAt(j); //获取li的结点

LinkTag _a=(LinkTag)n2.getFirstChild(); //获取嵌套了图片标签的a标签结点

// if(n2.getFirstChild().getFirstChild() instanceof org.htmlparser.nodes.TextNode )

// {

// System.out.println("-----------"+(n2.getFirstChild()).getClass().toString());

// String textNode=n2.getFirstChild().getFirstChild().getText();

// System.out.println("-----------"+textNode);

// }

ImageTag _img=(ImageTag)n2.getFirstChild().getFirstChild(); //获取图片标签结点

LinkTag _an=(LinkTag)n2.getLastChild(); //获取品牌链接

//LinkTag _an=(LinkTag)_a.getNextSibling();

 

String name=_an.getLinkText(); //得到品牌名称

String imgpath=_img.getImageURL(); //得到图片地址

String url=_a.getLink(); //得到图链接地址

 

TPhonebrand tphonebrand=new TPhonebrand();

tphonebrand.setPhonebrandName(name); //保存品牌名称到tphonebrand对象

tphonebrand.setPhonebrandImage(imgpath);

tphonebrand.setRelateURL(url);

 

list.add(tphonebrand);

}

}

return list;

}

 

/**

* 获取其它品牌(class=manu txt)的品牌

* manu txt 下的li子标签如下结构:

* <li>

* <a title="BlackBerry(黑莓) 手机" href="/cell_phone_index/subcate57_12772_list_1.html">BlackBerry(黑莓)手机</a>

* </li>

* @author luowei

* @createTime 2012-1-12

* @param

* @return

*/

public List<TPhonebrand> findOtherBrand(NodeList nl1) //

{

List<TPhonebrand> list=new ArrayList<TPhonebrand>();

for(int i=0;i<nl1.size();i++)

{

Node n1=nl1.elementAt(i); //定位到第iclass=manu txt的结点

NodeList nl2=n1.getChildren();

for(int j=0;j<nl2.size();j++) //遍历manu txt结点下的li结点

{

Node n2=nl2.elementAt(j); //定位到第jli的结点

 

TPhonebrand tphonebrand=new TPhonebrand();

LinkTag _an=(LinkTag)n2.getFirstChild();//获取品牌链接

 

String name=_an.getLinkText().replace("手机", "");

String url=_an.getLink();

tphonebrand.setPhonebrandName(name);

tphonebrand.setRelateURL(url);

 

list.add(tphonebrand);

}

}

return list;

}

 

public boolean alter(Action obj) {

return false;

}

 

public boolean delete(Action obj) {

return false;

}

 

public boolean save(Action obj) {

return false;

}

 

public static void main(String[] args) {

TPhonebrandManageService tPhonebrandManageService=new TPhonebrandManageService();

List<TPhonebrand> tPhjonebrandList=tPhonebrandManageService.getInforFromZOL();

for(TPhonebrand tPhonebrand:tPhjonebrandList)

{

System.out.println(tPhonebrand.getPhonebrandName()

+"\n"+tPhonebrand.getRelateURL()+"\n----------");

}

}

}

 

 

 

 

 

posted @ 2012-01-13 22:10  维唯为为  阅读(461)  评论(0编辑  收藏  举报