strutsによる完全なログインボックスインスタンスの実装


ここ数日ずっと心配しています:自分がますます勉強が嫌いになったと感じて、勉強の方法が間違っているのかもしれません.一ヶ月前に自分に言って、もっと落ち着いて、私はjavaの基礎を補習しながら、struts、spring、ibatis、hibernateの枠組みを勉強して、一日一日が過ぎて、たまに少し悟って、ただ大きな進展がないと感じます.
よく考えてみると、やはり自分の基礎が足りないのか、基本的な勉強をしっかりしなければならないのかと思います.そこで、ここ数日また起点に戻りました:jsp、servlet、javabean、jdbcを強化して、もっと深く、もっとしっかりして、更にこの期間、ゆっくりと設計モードのものを考えて、フレームワークを学ぶ時少し良いかもしれません.だからこれからも実例的なことをすることにします.少なくとも退屈ではありません.勉強にも刺激を与えましょう.
2泊の努力を経て、この登録例を作ったのは、少し遅いですが、手を練習するためには、主に各段階と設計構想を体験することにあります.
jsp+javabean+jdbcでやろうと思っていましたが、怠け者で、先日strutsで作ったログインページ(実現せず、検証コード画像の生成を練習しているだけ)を見て、ついでにこれにしましょう.
環境構成:開発環境myeclipse、フレームstruts、データベースはsqlserver 2000および対応するドライバパッケージを採用する:mssqlserver.jar、msbase.jar、msutil.jar
手順:
1、myeclipseで工事strutslogonを新設し、strutsフレームワークを構築する
2、sqlserverでデータベースmytestを新規作成し、テーブルloginを新規作成します.そのフィールド:username、password.3つの駆動パッケージをWEB-INF/lib/にインポート
3、プロファイルの編集
4、以下のjavaファイル及びjspファイルを編集する
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>3</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>3</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
  	<servlet>
  		<servlet-name>Image</servlet-name>
  		<servlet-class>logon.Image</servlet-class>
  	</servlet>
  	<servlet-mapping>
  		<servlet-name>Image</servlet-name>
  		<url-pattern>/image</url-pattern>
  	</servlet-mapping>
  	
  	<welcome-file-list>
  		<welcome-file>logon.jsp</welcome-file>
  	</welcome-file-list>
  	
</web-app>

struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>
  <data-sources />
  	<form-beans >
  		<form-bean name="logonForm" type="logon.LogonForm"></form-bean>
  	</form-beans>
  <global-exceptions />
  <global-forwards />
  	<action-mappings>
  		<action path="/logon"
  				name="logonForm"
  				type="logon.LogonAction"
  				input="/logon.jsp">
  			<forward name="success" path="/index.jsp"></forward>
  			<forward name="failure" path="/logon.jsp"></forward>
  		</action>
  	</action-mappings>
  <message-resources parameter="com.yourcompany.struts.ApplicationResources" />
</struts-config>



LogonAction.java

package logon;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class LogonAction extends Action{
	private LogonBean objLogonBean = new LogonBean();
	
	public LogonBean getObjLogonBean() {
		return objLogonBean;
	}

	public void setObjLogonBean(LogonBean objLogonBean) {
		this.objLogonBean = objLogonBean;
	}

	public ActionForward execute(ActionMapping mapping,	ActionForm form, 
		HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String target = "success";
		if(!objLogonBean.validate(form, request, response))	target="failure";
		return mapping.findForward(target);
	}
}

LogonBean.java

package logon;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;

public class LogonBean {
	
	String inputrand 	= null;
	String realrand 	= null;
	String username 	= null;
	String password 	= null;
	String sqlstr 		= null;
	String warning 		= null;	
	public boolean validate(ActionForm form,HttpServletRequest request, HttpServletResponse response){

		HttpSession session = request.getSession();
		realrand = (String)session.getAttribute("rand");
		System.out.println(realrand);
		
		if(form!=null){
			LogonForm logonForm = (LogonForm)form;
			inputrand = logonForm.getRand();
			username = logonForm.getUsername();
			password = logonForm.getPassword();
			System.out.println("input:" + inputrand);
		} else {
			inputrand = null;
		}
		
		//              
		if(inputrand.equals("") || username.equals("") || password.equals("")){
			request.setAttribute("warning", "          ");
			return false;
		}
		
		//       ,  false,     
		if(!inputrand.equals(realrand)){
			request.setAttribute("warning", "   ,         ,     !");
			return false;
		}
		
		//                 
		sqlstr = "select * from login where username='" +username+ "' and password='" +password+ "'";
		List list = null;
		list = objLoginDao.ResultToList(objLoginDao.executeQuery(sqlstr));

		//        ,  false,     
		if(list.size()<1){
			request.setAttribute("warning", "   ,            ,     !");
			return false;
		}
		
		request.setAttribute("username", username);
		return true;
	}
	
	private LogonDao objLoginDao = new LogonDao();

	public LogonDao getObjLoginDao() {
		return objLoginDao;
	}

	public void setObjLoginDao(LogonDao objLoginDao) {
		this.objLoginDao = objLoginDao;
	}
}

LogonDao.java

package logon;

import java.sql.*; 
import java.util.*; 

public class LogonDao{ 
	
	String 		sDBDriver	= "com.microsoft.jdbc.sqlserver.SQLServerDriver"; 
	String 		url			= "jdbc:sqlserver://localhost:1433;DatabaseName=mytest"; 
	String 		user		= "sa"; 
	String 		password	= "1"; 
	Statement 	stmt		= null; 
	Connection 	conn		= null; 
	ResultSet 	rs			= null; 
	List 		list 		= null;	//   ,    ResultSet List  
	
	public LogonDao(){ 
		try{ 
			Class.forName(sDBDriver).newInstance(); 
			System.out.println("         "); 
		} 
		catch(Exception e) 
		{ 
			e.printStackTrace() ; 
		} 
	} 
	
	//       sql         
	public ResultSet executeQuery(String sql){ 
		System.out.println(sql);
		try{ 
			conn=DriverManager.getConnection(url,user,password); 
			Statement stmt=conn.createStatement(); 
			System.out.println("       "); 
			rs=stmt.executeQuery(sql); 
		} 
		catch(SQLException ex){ 
			System.err.println(ex.getMessage()); 
		} 
		return rs; 
	} 
	
	/**
	 * @description:             List,    
	 * @param rs	    ResultSet    
	 * @return	    List  
	 */
	public List ResultToList(ResultSet rs){
		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			int numberOfColumns = rsmd.getColumnCount();
			//
			System.out.println("numberOfColumns: " + numberOfColumns);
			Map rsMap = null;
			list = new ArrayList();
			
			while(rs.next()){
				rsMap = new HashMap(numberOfColumns);
				for(int r=1;r<numberOfColumns+1;r++){
					rsMap.put(rsmd.getColumnName(r), rs.getObject(r));
				}
				list.add(rsMap);
			}
		}
		catch(SQLException ex){
			System.err.println(ex.getMessage());
		}
		return list;
	}
	
	//      
	public void executeUpdate(String sql){ 
		stmt=null; 
		rs=null; 
		try{ 
			conn=DriverManager.getConnection(url,user,password); 
			Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); 
			stmt.executeQuery(sql); 
			stmt.close(); 
			conn.close(); 
		} 
		catch(SQLException ex){ 
			System.err.println(ex.getMessage()); 
		} 
	} 
	
	//   Statement   
	public void closeStmt() 
	{ 
		try{ 
			stmt.close(); 
		} 
		catch(SQLException e) 
		{ 
			e.printStackTrace(); 
		} 
	} 
	
	//       
	public void closeConn() 
	{ 
		try{ 
			conn.close(); 
		} 
		catch(SQLException e) 
		{ 
			e.printStackTrace(); 
		} 
	} 
} 

LogonForm.java

package logon;

import org.apache.struts.action.ActionForm;

public class LogonForm extends ActionForm {
	private String username;
	private String password;
	private String rand;
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getRand() {
		return rand;
	}
	public void setRand(String rand) {
		this.rand = rand;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
}

Image.java

package logon;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Image extends HttpServlet {
 
	//public static final long serialVersionUID = 1L ;
 
    //private static final String CONTENT_TYPE = "text/html; charset=GBK";

    public 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);
    }

    //Initialize global variables
    public void init() throws ServletException {
    }

    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        //       
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        //         
        int width = 60, height = 20;
        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(0, 0, width, height);

        //    
        g.setFont(new Font("Times New Roman", Font.PLAIN, 18));

        //   
        //g.setColor(new Color());
        //g.drawRect(0,0,width-1,height-1);

        //     155    ,                  
        g.setColor(getRandColor(160, 200));
        for (int i = 0; i < 155; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }

        //          (4   )
        String sRand = "";
        for (int i = 0; i < 4; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
            //           
            g.setColor(new Color(20 + random.nextInt(110),
				20 + random.nextInt(110),
				20 + random.nextInt(110)));
            //           ,          ,        
            g.drawString(rand, 13 * i + 6, 16);
        }

		//       SESSION
	    request.getSession().setAttribute("rand", sRand);
	
	    //     
	    g.dispose();
	
		//        
		//ImageIO.write(image, "JPEG", response.getOutputStream());
		JPEGImageEncoder encode = JPEGCodec.createJPEGEncoder(response.
		getOutputStream());
		encode.encode(image);
	}

	//Clean up resources
	public void destroy() {
	}
}

logon.jsp

<%@ page language="java" pageEncoding="gbk"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<%
	String msg = null;
	msg = (String)request.getAttribute("warning");
%>
<html>
<head>
    <title>logon.jsp</title>
</head>

<body>
	<html:form action="/logon.do" method="post">
     	<table border="0" cellspacing="0" cellpadding="0" style="border:#1A3C79 1px solid;" bgcolor="white" align="center">
	        <tr height="10"><td colspan="2"></td></tr>
	        <tr height="22"><td colspan="2" align="center">    </td></tr>
	        <tr height="22">
	          	<td width="100" align="right">   :</td>
	          	<td width="180" align="left"><input name="username" type="text" style="width:120px;height:18px;"></td>
	        </tr>
	        <tr height="22">
	          	<td align="right"> &nbsp;&nbsp; :</td>
	          	<td align="left"><input name="password" type="password" style="width:120px;height:18px;"></td>
	        </tr>
	    	<tr height="22">
		    	<td align="right">   :</td>
		    	<td align="left">
			     	<table border="0" cellspacing="0" cellpadding="0">
			        	<tr>
			          		<td><input  name="rand" type="text" style="width:70px;height:18px;" maxLength="4"></td>
			          		<td>&nbsp;
			          			<img id="randImage" src="image" onclick="loadimage();" alt="         " style="margin-top:3px;width:60px;height:20px;cursor:hand;">
			          		</td>
			        	</tr>
			     	</table>
		    	</td>
	        </tr>
	        <tr height="25"><td colspan="2" align="center" valign="bottom"><input type="submit" value="  "></td></tr>
	        <tr height="10"><td colspan="2"></td></tr>
      	</table>
    </html:form>
</body>
<script language="javascript"> 
	function loadimage(){ 
		document.getElementById("randImage").src = "image"; 
	}
	
	//          ,       
	msgWarning();
	function msgWarning(){
		var msg = "<%=msg %>";
		if(msg!="null")alert(msg);
	}
</script>
</html>

index.jsp

<html>
<head>
    <title>index.jsp</title>
</head>
<body>
	<br>
	<h3 align="center">${username},welcoming your comming!</h3>
</body>
</html>