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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
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
2.jsp页面form表单,设置如下:
<form name="form1" id="form1" enctype="multipart/form-data" method="post" action="${ctx }/manage/manageInfo/phone/new.do">
@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);
file.transferTo(targetFile); //上传目标文件
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);
直接解析HttpServletRequest,示例代码如下,(表单格式仍然为:enctype="multipart/form-data"):
@RequestMapping(value = "/new")
public String newPhone(Phone phone,HttpServletRequest request,HttpServletResponse response) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
request.setCharacterEncoding("utf-8");
List items = upload.parseRequest(request); //解析HttpServletRequest
Iterator iter = items.iterator();
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); //创建一个上传文件对象
item.write(uploadedFile); //将要上传的文件对象写到item
phone.setPhoneImage("/ttpod/images/phone/"+uploadedFile.getName());
} catch (FileUploadException e)
catch(UnsupportedEncodingException e1)
phone.setPhoneAddDate(DateUtil.datetimeToDate()); //给phone对象的添加日期字段设置值
this.phoneManageService.save(phone); //执行保存
String currentPage = (String) this.getSessionAttribute(request,"currentPage");
this.sendRedirect(response, currentPage);
在spring-mvc项目中引入htmlparser.jar包,抓取中关村的手机品牌信息,示例代码如下:
package com.luowei.common.service.imp;
import javax.annotation.Resource;
import org.htmlparser.filters.StringFilter;
import org.htmlparser.nodes.*;
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
@Resource(name="TPhonebrandDAO")
private TPhonebrandDAO tPhonebrandDAO;
public TPhonebrandDAO gettPhonebrandDAO() {
public void settPhonebrandDAO(TPhonebrandDAO tPhonebrandDAO) {
this.tPhonebrandDAO = tPhonebrandDAO;
class BrandFilter extends StringFilter
public BrandFilter(String pattern)
public boolean accept(Node node) {
String vl=tn.getAttribute("class");
if(vl!=null&&vl.equals(this.getPattern()))
public List<TPhonebrand> getInforFromZOL()
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]))));
* <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 title="Samsung(三星) 手机" href="/cell_phone_index/subcate57_98_list_1.html">Samsung(三星)</a>
public List<TPhonebrand> findNormalBrand(NodeList nl1)
List<TPhonebrand> list=new ArrayList<TPhonebrand>();
Node n1=nl1.elementAt(i); //获取第i个class=manu normal的结点
NodeList nl2=n1.getChildren();
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);
public List<TPhonebrand> findOtherBrand(NodeList nl1) //
List<TPhonebrand> list=new ArrayList<TPhonebrand>();
Node n1=nl1.elementAt(i); //定位到第i个class=manu txt的结点
NodeList nl2=n1.getChildren();
for(int j=0;j<nl2.size();j++) //遍历manu txt结点下的li结点
Node n2=nl2.elementAt(j); //定位到第j个li的结点
TPhonebrand tphonebrand=new TPhonebrand();
LinkTag _an=(LinkTag)n2.getFirstChild();//获取品牌链接
String name=_an.getLinkText().replace("手机", "");
tphonebrand.setPhonebrandName(name);
tphonebrand.setRelateURL(url);
public boolean alter(Action obj) {
public boolean delete(Action obj) {
public boolean save(Action obj) {
public static void main(String[] args) {
TPhonebrandManageService tPhonebrandManageService=new TPhonebrandManageService();
List<TPhonebrand> tPhjonebrandList=tPhonebrandManageService.getInforFromZOL();
for(TPhonebrand tPhonebrand:tPhjonebrandList)
System.out.println(tPhonebrand.getPhonebrandName()