显示标签为“Web”的博文。显示所有博文
显示标签为“Web”的博文。显示所有博文

2012年12月20日星期四

Hibernate中findById时出现org.hibernate.MappingException: Unknown entity:的解决办法

 

原因:在使用myeclispe生成pojo和DAO代码后,对相关类进行了重构,改变了包。造成反射时找不到类。

出现错误的findById代码

public Trace findById(Long id) {
        log.debug("getting Trace instance with id: " + id);
        try {
            Trace instance = (Trace) getHibernateTemplate().get("Trace", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

 

修改后的方法

public Trace findById(Long id) {
        log.debug("getting Trace instance with id: " + id);
        try {
            Trace instance = (Trace) getHibernateTemplate().get("cn.cslg.Trace", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

2012年12月15日星期六

使用MyEclipse生成hibernate pojo和dao的过程

 

首先在MyEclipse中配置好数据源并打开。

选择需要生成pojo的表。

在右键菜单中选择 Hibernate Reverse Engineering,按下面的步骤进行设置。

生成pojo和dao之后,可以移动到相关的包。在DAO类中可以通过重构,将方法提取到DAO接口。

注意:如果表中没有主键,则会生成一个额外的类,并使用全部字段作为联合主键。

 

QQ截图20121215185333

 

QQ截图20121215185352

QQ截图20121215185407

2010年12月22日星期三

在线考试系统

最近做了一个非常简单的在线考试系统:JSP+Servlet+mysql+ajax+存储过程,把一些遇到的问题发到这里记录一下

2010年5月6日星期四

使用WebClient提交中文数据

 

            try
            {
                String url = "http://school.jxllt.com/family/famsmssend_action_new.asp";
                String data = "sel_recelist=" + teacher + "&txta_memo=" + msg;
                byte[] postData = Encoding.GetEncoding("GB2312").GetBytes(data);
                wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                byte[] res = wc.UploadData(url, "POST", postData);
            }
            catch (Exception exp)
            {
                MessageBox.Show(String.Format("程序运行期间发生错误,错误信息:{0}", exp.Message));
            }

2010年5月1日星期六

使用C#、XML和XPATH从HTML中提取特定标记的值

StringReader txtReader;
txtReader = new StringReader(cleanedMarkUp);
XPathDocument xdoc = new XPathDocument(txtReader);

XPathNavigator nav = xdoc.CreateNavigator();

nav.MoveToRoot();

XPathExpression expr = nav.Compile("//tr[@bgcolor='#f3f2f1']");

XPathNodeIterator node = nav.Select(expr);

while (node.MoveNext())
    MessageBox.Show(node.Current.Value);

使用TidyNET清理和转换HTML为XHTML

TidyNet(http://sourceforge.net/projects/tidynet/)是用c#编写的Tidy API,对字符支持比较好,不会出现像NTidy那样的乱码。

Tidy doc = new Tidy();
TidyMessageCollection tmc = new TidyMessageCollection();

            MemoryStream input = new MemoryStream();
            MemoryStream output = new MemoryStream();

            //Set some Tidy options, refer to the HTML Tidy docs for more info
            doc.Options.DocType = DocType.Strict;
            doc.Options.Xhtml = false;
            doc.Options.LogicalEmphasis = true;
            doc.Options.DropFontTags = true;
            doc.Options.DropEmptyParas = true;
            doc.Options.QuoteAmpersand = true;
            doc.Options.TidyMark = true;
            doc.Options.MakeClean = true;
            doc.Options.IndentContent = true;
            doc.Options.SmartIndent = true;
            doc.Options.Spaces = 4;
            doc.Options.WrapLen = 100;
            doc.Options.CharEncoding = CharEncoding.UTF8;
            doc.Options.XmlOut = true;

            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(restext);
            input.Write(byteArray, 0, byteArray.Length);
            input.Position = 0;
            doc.Parse(input, output, tmc);
            foreach (TidyMessage message in tmc)
            {
                if (message.Level == MessageLevel.Error)
                {
                    throw new ApplicationException(String.Format("{0} at line {1} column {2}",
                    message.Message, message.Line,
                    message.Column));
                }
            }

            string cleanedMarkUp = System.Text.Encoding.UTF8.GetString(output.ToArray());

使用NTidy工具清理和规范HTML为XHTML

 

NTidy(http://sourceforge.net/projects/ntidy/)是一个用C++编写的供.NET使用的tidy api. 将NTidy.dll添加到项目引用,并添加

using NTidy; 后即可使用

TidyDocument tdoc = new TidyDocument();
tdoc.LoadConfig("tidy.cfg");
tdoc.SetCharEncoding("gb2312");
TidyStatus status = tdoc.LoadString(restext);
tdoc.CleanAndRepair();

XmlDocument xmldoc = new XmlDocument();
xmldoc.InnerXml = tdoc.Root.Value;

问题:没有考虑编码的问题,中文会被自动转换为类似#C2C8;这样的Unicode编码。

tidy.cfg工具可通过TidyGUI工具(http://pagesperso-orange.fr/ablavier/TidyGUI/)生成。

// HTML Tidy configuration file created by TidyGUI
new-inline-tags: o:p
char-encoding: utf-8
doctype: strict
tidy-mark: no
word-2000: yes
output-xml: yes
output-xhtml: yes
add-xml-decl: yes
assume-xml-procins: yes

参考资料:

http://jeebook.com/blog/?p=606

让WebClient支持cookie和session

.NET中的WebClient组件,通过向网站发送登录请求成功后不能保持session。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace jxlltEasy
{
    class HttpClient : WebClient
    {
        // Cookie 容器
        private CookieContainer cookieContainer;

        /**/
        /// <summary>
        /// 创建一个新的 WebClient 实例。
        /// </summary>
        public HttpClient()
        {
            this.cookieContainer = new CookieContainer();
        }

        /**/
        /// <summary>
        /// 创建一个新的 WebClient 实例。
        /// </summary>
        /// <param name="cookie">Cookie 容器</param>
        public HttpClient(CookieContainer cookies)
        {
            this.cookieContainer = cookies;
        }

        /**/
        /// <summary>
        /// Cookie 容器
        /// </summary>
        public CookieContainer Cookies
        {
            get { return this.cookieContainer; }
            set { this.cookieContainer = value; }
        }

        /**/
        /// <summary>
        /// 返回带有 Cookie 的 HttpWebRequest
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                HttpWebRequest httpRequest = request as HttpWebRequest;
                httpRequest.CookieContainer = cookieContainer;
            }
            return request;
        }
    }
}

2009年10月18日星期日

Filter Servlet控制用户权限

//过滤器代码

package cn.cslg.labsys.filter;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.cslg.labsys.db.DBPoolException;
import cn.cslg.labsys.db.JndiBean;

/**
* 过滤器,对用户登录情况进行检查,如果用户未登录,则转到登录页面处理
*
* @author jimshen
*
*/
public class SessionChecker implements Filter {

    private String targetURI;

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        // 取得HTTP request/response/session对象
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession(false);

        // 如果用户已登录,按既定流程运行
        try{
        if (session != null) {
            String user = (String) session.getAttribute("TNum");
            if (user != null) {
                String url = httpRequest.getRequestURI();
                if(pright(url,user)){
                    chain.doFilter(request, response);
                    return;
                }else
                    return;
            }
        }
        }catch(DBPoolException e){
            throw new ServletException(e);
        }catch(NamingException e){
            throw new ServletException(e);
        }catch(SQLException e){
            throw new ServletException(e);
        }
        httpResponse.sendRedirect(targetURI);

    }

    private boolean pright(String url, String tnum) throws DBPoolException,
            NamingException, SQLException {
        Connection conn = null;
        try {
            conn = JndiBean.getConnection();
            String sql="select * from priviledge where  locate(module,?)<>0 and Tnum=?";
            PreparedStatement pstmt=conn.prepareStatement(sql);
            pstmt.setString(1,url);
            pstmt.setString(2, tnum);
            ResultSet rs=pstmt.executeQuery();
            if(rs.next())
                return true;
            rs.close();
            pstmt.close();
            sql="select * from priviledge where locate(module,?)<>0";
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1,url);
            rs=pstmt.executeQuery();
            if(rs.next())
                return false;
            return true;
        } finally {
            if (conn != null)
                conn.close();
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        targetURI = filterConfig.getInitParameter("targetURI");
    }

    public void destroy() {
    }
}

//过滤器配置(web.xml)
<!-- filter to check user privilidge -->
    <filter>
        <filter-name>SessionChecker</filter-name>
        <filter-class>cn.cslg.labsys.filter.SessionChecker</filter-class>
        <init-param>
            <param-name>targetURI</param-name>
            <param-value>/LabSys/index.jsp</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>SessionChecker</filter-name>
        <url-pattern>/outlines/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>SessionChecker</filter-name>
        <url-pattern>/labfile/*</url-pattern>
    </filter-mapping>

//priviledge表结构
TNum(用户名)    module(模块名,即目录名)
s09002        labfile
s09025        labfile

2008年6月14日星期六

EclipseTidy插件

在Web应用程序开发中,特别是别人拿来的一些代码,难免要碰到一些格式混乱,又存在很多错误的HTML页面。比如说标记不匹配,不正确的属性设置,嵌套混乱等等。但正因为浏览器都有一定的容错性,而致使问题不容易解决,即使想解决也非常困难。

HTML Tidy是一个免费的HTML语言检查工具,检查代码并指出一些与已发布的W3C标准不一致的地方。它可以用来解析包含HTML标记的HTML文件或字符串,并可以自动改正错误,使其与相关标准完全一致。

和HTML Tidy相关的工具有:

  • jtidy,用于java程序的进行HTML格式化和清理的API http://jtidy.sourceforge.net
  • EclipseTidy,eclipse的插件,可在eclipse中对页面进行格式化和清理,使之符合W3C标准

EclipseTidy的下载地址: http://eclipsetidy.sourceforge.net

将下载好的eclipsetidy解压到eclipse安装目录,重新启动eclipse即可生效。

为了能对JSP进行处理,需要在配置中将JSP扩展名加进去。

写了一个从虞城热线上抽取天气预报的程序

写了一个从虞城热线上抽取天气预报的程序,生成了javascript调用代码,调用形式:

<script language="javascript" type="text/javascript" src="http://cse.cslg.cn:8888/weather/weather.js"></javascript>

2008年5月13日星期二

用Servlet生成验证码后session失效问题

在使用Servlet生成验证码时,在JSP中无法取得存放在session中的验证码的正确结果进行比对。经跟踪,发现在Servlet和JSP中的session id不同。百思不得其解,最后用HttpAnalyzer捕捉HTTP包进行分析,发现每个请求中的session ID不同,进而发现是由于准备在系统中使用JForum的单点登录SSO而设置了cookie的原因。

//JFroum SSO Cookie
Cookie cookie = new Cookie("jforumUserInfo",
                            (String) session.getAttribute("UserLogon"));
cookie.setMaxAge(-1);
response.addCookie(cookie);

删除上述的代码段,重启Web App。并清空浏览器的缓存和cookies,问题解决。

相册程序中的表单检查

<script language="JavaScript" type="text/javascript">
<!--
function checkForm(){
    var filename=document.getElementById("photos").value;
    if(filename==""){
        alert("请先选择要上传的照片后再确定上传!");
        return false;
    }else{
        if(!IsImageName(filename)){
            alert("只允许上传jpg、jpeg、png形式的图片!");
            return false;
        }
    }
    return true;
}
function IsImageName(filename){
    var regex=/^.*(\\|\/)[^\.]+.(jpg|png|jpeg)$/
    var splitted=filename.match(regex);
    if(splitted==null)
        return false;
    return true;
}
//-->
</script>

 

<form action="../servlet/PhotoUpload" method="post" enctype="multipart/form-data" name="form1" id="form1" onsubmit="return checkForm();">
  <table width="67%" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td>选择文件</td>
      <td><input type="file" name="photos" id="photos" /></td>
    </tr>
    <tr>
      <td valign="top">照片说明</td>
      <td><textarea name="description" id="description" cols="36" rows="3"></textarea></td>
    </tr>
    <tr>
      <td colspan="2"><center>
        <input name="btnSubmit" type="submit" id="btnSubmit" value="上传" />
      </center>
      </td>
      </tr>
  </table>
  </form>

关于MD5破解网站的感想

前几天在网上看到一个国内的MD5在线查询破解网站 http://www.cmd5.com/ 。下面是该网站的简介:

本站4T硬盘已经上线,共有md5记录457,354,352,282条,宇宙第一,且还在不断增长中,已包含12位及12位以下数字、8位字母、全部7位及以下字母加数字等组合,并针对国内用户做了大量优化,例如已经包含所有手机号码、全国部分大中城市固定电话号码、百家姓、常用拼音等大量组合,另加入了大型网站真实会员密码数据100万条。本站数据量大,查询速度快,同时支持16位及32位密码查询。通过对10万会员的真实动网论坛样本数据的测试,本站对于动网论坛密码的命中率达到83%。全国独此一家。另感谢一热心网友给本站奉上数百万条数据库原始密码样本,大大提高了命中率!

令我诧异的是有人会送上原始密码样本,这样很多系统的安全性就得不到保证了。

看来在系统中如果不能保证绝对没有bug,绝对没有SQL诸如漏洞的话,我要考虑密码保存的方式了。至少换一个非公开加密算法的程序来实现密码的加密存储。