kisonlee
2009-09-12 15:12
浏览 250
已采纳

哪位帮忙分析下我的SSH小工程,非常感谢

WEB-INF/applicationContext.xml
[code="java"]<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
















model/User.hbm.xml




org.hibernate.dialect.MySQLDialect
true
false
update
20








PROPAGATION_REQUIRED,readOnly
PROPAGATION_REQUIRED





mgr

<property name="interceptorNames">
    <list>
        <value>transactionInterceptor</value>
    </list>
</property>





[/code]

WEB-INF/web.xml
[code="java"]
<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<context-param>  
 <param-name>contextConfigLocation</param-name>  
 <param-value>/WEB-INF/applicationContext.xml</param-value>  
</context-param>  
<!-- 用于初始化Spring容器的Listener -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true </param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>openSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>openSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>struts-cleanup</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
</filter>
<filter-mapping>
    <filter-name>struts-cleanup</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>


[/code]

model.User.java
[code="java"]package model;

public class User
{
private int Id;
private String username;
private String password;

public int getId()
{
    return Id;
}
public void setId(int id)
{
    Id = id;
}
public String getUsername()
{
    return username;
}
public void setUsername(String username)
{
    this.username = username;
}
public String getPassword()
{
    return password;
}
public void setPassword(String password)
{
    this.password = password;
}

}[/code]

model/User.hdm.xml
[code="java"]<?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">









[/code]

login.jsp
[code="java"]<%@ page language="java" import="java.util.*"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%@taglib prefix="sx" uri="/struts-dojo-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

function refresh() { document.getElementById("authImg").src = "authImg?d=" + new Date().getTime(); }




sx:head/











/s:form
验证码如图:看不清?单击此处刷新

[/code]

action.LoginAction.java
[code="java"]package action;

import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;

public class LoginAction extends BaseAction
{
private static final long serialVersionUID = 1L;

public String getUsername()
{
    return username;
}
public void setUsername(String username)
{
    this.username = username;
}
public String getPassword()
{
    return password;
}
public void setPassword(String password)
{
    this.password = password;
}
public String getVercode()
{
    return vercode;
}
public void setVercode(String vercode)
{
    this.vercode = vercode;
}

@SuppressWarnings("unchecked")
public String execute() throws Exception
{
    Map session = ActionContext.getContext().getSession();
    String ver = (String)session.get("authImg");

    if (ver.equals(vercode))
    {
        int userId = mgr.loginValid(username,password);

        if (userId > 0)
        {
            return SUCCESS;
        }
        else
        {
            addActionError(getText("noMatch"));
        }
    }
    else
    {
        System.out.println("0k3");
        addActionError(getText("vercodeErr"));
    }
    return "failure";
}

private String username;
private String password;
private String vercode;

}
[/code]

UserDAOHibernate.java
[code="java"]package dao.user;

import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import model.User;

public class UserDAOHibernate extends HibernateDaoSupport implements UserDAO
{
@SuppressWarnings("unchecked")
public User findUserByNameAndPass(String username , String password)
{
List ul = null;
try
{
[color=red]ul = getHibernateTemplate().find("from User au where au.username = ? and au.password = ?" ,new String[]{username,password});[/color]
} catch(DataAccessException e)
{
System.out.println("数据访问异常");
e.printStackTrace();
}

    System.out.println(ul.size());
    if (ul != null && ul.size() >= 1)
    {
        return (User)ul.get(0);
    }
    return null;
}

@SuppressWarnings("unchecked")
public User findUserByName(String username)
{
  [color=red]  List ul = getHibernateTemplate().find("from User au where au.username = ?" ,username);[/color]
    if (ul != null && ul.size() >= 1)
    {
        return (User)ul.get(0);
    }
    return null;
}

@Override
public User get(int id)
{
    return (User)getHibernateTemplate().get(User.class, id);
}

}
[/code]

问题描述,1.验证码不显示,2.但是后台能发现6位验证码,当正确的用户名,密码,和后台的验证码后,jsp页面出现:
description The server encountered an internal error () that prevented it from fulfilling this request.

exception

java.lang.reflect.InvocationTargetException
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
org.apache.struts2.dispatcher.ActionContextCleanUp.doFilter(ActionContextCleanUp.java:102)
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:174)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)

控制台出现:
12:16:11,779 DEBUG SessionImpl:248 - opened session at timestamp: 12527289717
12:16:12,193 DEBUG JDBCTransaction:82 - begin
12:16:12,194 DEBUG ConnectionManager:444 - opening JDBC connection
12:16:12,197 DEBUG JDBCTransaction:87 - current autocommit status: true
12:16:12,200 DEBUG JDBCTransaction:90 - disabling autocommit
12:16:12,469 DEBUG JDBCTransaction:186 - rollback
12:16:12,471 DEBUG JDBCTransaction:227 - re-enabling autocommit
12:16:12,475 DEBUG JDBCTransaction:197 - rolled back JDBC Connection
12:16:12,476 DEBUG ConnectionManager:325 - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!
12:16:12,480 DEBUG ConnectionManager:464 - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
12:16:12,480 DEBUG ConnectionManager:325 - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!

非常感谢大家。。。。。

[b]问题补充:[/b]
liyaxi

现在异常没了,但是还是无法显示验证码图片

我的所有action都是默认命名空间,并且没有重命名的action

另外我生成图片的类是:
[code="java"]package authImg;

import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;

public class AuthImg
{
private static final long serialVersionUID = 1L;
//设置图形验证码中字符串的字体和大小

private ByteArrayInputStream image;//图像   
private String str;//验证码   

public AuthImg()
{   
    init();
}   
/*  
 * 取得AuthImg实例  
 */  
public static AuthImg Instance(){   
    return new AuthImg();   
}   
/*  
 * 取得验证码图片  
 */  
public ByteArrayInputStream getImage()
{   
    return this.image;   
}   
/*  
 * 取得图片的验证码  
 */  
public String getString()
{   
    return this.str;   
}   

/*
 * 生成随机颜色
 */
private Color getRandColor(int fc, int bc)
{
    Random random = new Random();
    if (fc > 255)
        fc = 255;
    if (bc > 255)
        bc = 255;
    int r = fc + random.nextInt(bc - fc);
    int g = fc + random.nextInt(bc - fc);
    int b = fc + random.nextInt(bc - fc);
    return new Color(r, g, b);
}
/*
 * 生成服务器响应的服务方法
 */
public void init()
{
    int width = 100, height = 18;
    //生成一张新图片
    BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
    //在图片中绘制内容
    Graphics g = image.getGraphics();
    Random random = new Random();
    g.setColor(getRandColor(200, 250));
    g.fillRect(1, 1, width - 1, height - 1);
    //设定背景色   
    g.setColor(new Color(102, 102, 102));
    g.drawRect(0, 0, width - 1, height - 1);
    g.setFont(new Font("Arial Black", Font.PLAIN, 16));
    //随机生成线条,让图片看起来更加杂乱
    g.setColor(getRandColor(160, 200));
    for (int i = 0; i < 155; i++)
    {
        int x = random.nextInt(width - 1);
        int y = random.nextInt(height - 1);
        int xl = random.nextInt(6) + 1;
        int yl = random.nextInt(12) + 1;
        g.drawLine(x, y, x + xl, y + yl);
    }
    for (int i = 0; i < 70; i++)
    {
        int x = random.nextInt(width - 1);
        int y = random.nextInt(height - 1);
        int xl = random.nextInt(12) + 1;
        int yl = random.nextInt(6) + 1;
        g.drawLine(x, y, x - xl, y - yl);
    }
    //用于保存系统生成的随机字符串
    StringBuffer sRand = new StringBuffer(6);
    for (int i = 0; i < 6; i++)
    {
        String tmp = getRandomChar();
        sRand = sRand.append(tmp);
        //将系统生成的随机字符添加到图形验证码图片上
        g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
        g.drawString(tmp, 15 * i + 10, 15);
    }
    //赋值验证码
    this.str = sRand.toString(); 

    g.dispose();   
    ByteArrayInputStream input = null;   
    ByteArrayOutputStream output = new ByteArrayOutputStream();   
    //输出图形验证码图片
    try
    {   
        ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);   
        ImageIO.write(image, "bmp", imageOut);   
        imageOut.close();   
        input = new ByteArrayInputStream(output.toByteArray());   
    }catch(Exception e){   
        System.out.println("验证码图片产生出现错误:" + e.toString());   
    }  
    //赋值图像  
    this.image = input;   
}
/*
 * 生成随机字符
 */
private String getRandomChar()
{
    int rand = (int) Math.round(Math.random() * 2);
    long itmp = 0;
    char ctmp = '\u0000';
    switch(rand)
    {
    //生成大写字母的情形
    case 1:
        itmp = Math.round(Math.random() * 25 + 65);
        ctmp = (char) itmp;
        return String.valueOf(ctmp);
    //生成小写字母的情形
    case 2:
        itmp = Math.round(Math.random() * 25 + 97);
        ctmp = (char) itmp;
        return String.valueOf(ctmp);
    //生成数字的情形
    default:
        itmp = Math.round(Math.random() * 9);
        return String.valueOf(itmp);
    }
}

}
[/code]

产生图片的action是
[code="java"]package action;

import java.io.ByteArrayInputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import authImg.AuthImg;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CreateCodeImgAction extends ActionSupport
{
private static final long serialVersionUID = 1L;

public void setInputStream(ByteArrayInputStream inputStream)
{
    this.inputStream = inputStream;
}

public ByteArrayInputStream getInputStream()
{
    return inputStream;
}

public String execute() throws Exception
{
    HttpServletResponse response = ServletActionContext.getResponse();
    //阻止生成页面被缓存,保证每次重新生成随机验证码
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    AuthImg authImg = AuthImg.Instance();
    // 取得带有随机字符串的图片
    setInputStream(authImg.getImage());
    // 取得随机字符串放入HttpSession

    System.out.println(authImg.getString());

    ActionContext.getContext().getSession().put("authImg", authImg.getString());

    return SUCCESS;
}

private ByteArrayInputStream inputStream;

}[/code]

struts.xml片段
[code="java"]


/spread/spread1.jsp
/login.jsp

    <action name="authImg" class="action.CreateCodeImgAction">     
        <result type="stream">     
            <param name="contentType">image/bmp</param>     
            <param name="inputName">inputStream</param>
        </result>  
        <result name="success">login.jsp</result>
    </action>  
</package>[/code]
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • mafangling 2009-09-14 04:31
    已采纳





    image/bmp

    inputStream



    [b] [color=red]login.jsp [/color] [/b]


    把这个login.jsp 删除掉就可以了,
    最好把, image/bmp 改为 image/jpeg
    把这个也改了 ImageIO.write(image, "bmp", imageOut); --- ImageIO.write(image, "jpeg", imageOut);
    其实 是人最难发现自己的代码错误的。 你的思路很好, 我已经在我的机子上测试了,
    没问题。 我以前只用下边的。
    [code="xml"]

    image/peg

    inputStream



    [/code] 做下载用。 楼住举一反三 ,触类旁通。 在咱们论坛里有这篇文章 , 题目:struts2下实现了图片验证码,[url] http://tmq.iteye.com/blog/286022 [/url] , 希望对你有帮助。

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • mafangling 2009-09-13 05:58

    你的验证么是如何实现的 , 是不是在一个servlet 类里生成 , 但是我没发现的你的验证码servlet 类 和在web.xml的配置映射。
    验证码的servlet类 在web.xml的 /authImg
    我建议你 先建立一个独立的小项目, 只有验证码的那个servelt 类和一个jsp 文件显示验证码 测试验证码。
    报的异常, 可能是因为struts2.0 pojo类的属性没有获取到。
    在一个你的struts.xml 文件在哪儿。action的配置时有没有namespace , package ;
    这度可能影响大路径问题。 如果有, 建议建议你将 改为 或者 试一下。

    评论
    解决 无用
    打赏 举报
  • mafangling 2009-09-14 04:34

    因为bmp图片格式 ,不是标准的图片格式。

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题