Strutsでユーザー登録を実現する機能


1.web.xmlでフィルタを構成する
 
まず、私たちはwebにいます.xmlにフィルタを設定すると、ユーザーがすべてのページにアクセスするときにログインする必要があります.
 
フィルタの設定コードは次のとおりです.
 
<filter>
  <description>     </description>
  <display-name>loginFilter</display-name>
  <filter-name>loginFilter</filter-name>
  <filter-class>com.tntxia.filter.LoginFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>loginFilter</filter-name>
  <url-pattern>*</url-pattern>
 </filter-mapping>
 <filter-mapping>

url-patternプロパティは、すべてのリクエストがこのフィルタによってフィルタされることを示す*に設定されています.
 
2.Strutsの設定
 
struts-configを設定する.xml
A.FormBean:UserFormを追加
    
<form-bean name="userForm" type="com.tntxia.struts.form.UserForm" />

 
B.ログインのアクションを追加
    
   
<action attribute="userForm" input="/login.jsp"
	name="userForm" path="/login" scope="request"
	type="com.tntxia.struts.action.LoginAction">
	<forward name="/success" path="/uploadPhoto.jsp" />
</action>

 3.UserFormクラスのコード:
   
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.tntxia.struts.form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

/** 
 * MyEclipse Struts
 * Creation date: 06-21-2009
 * 
 * XDoclet definition:
 * @struts.form name="userFormForm"
 */
public class UserForm extends ActionForm {
	/**
	 * 
	 */
	private static final long serialVersionUID = -9144040556996550030L;

	/*
	 * Generated fields
	 */
	
	private String userId;
	
	private String password;

	/** 
	 * Method validate
	 * @param mapping
	 * @param request
	 * @return ActionErrors
	 */
	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

	/** 
	 * Method reset
	 * @param mapping
	 * @param request
	 */
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		// TODO Auto-generated method stub
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

 
4.LoginActionのコード:
 
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.tntxia.struts.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;

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;
import org.apache.struts.upload.FormFile;

import com.tntxia.db.util.DBUtil;
import com.tntxia.struts.form.PhotoForm;

/** 
 * MyEclipse Struts
 * Creation date: 06-21-2009
 * 
 * XDoclet definition:
 * @struts.action validate="true"
 */
public class UploadFileAction extends Action {
	/*
	 * Generated Methods
	 */

	/** 
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		PhotoForm userForm = (PhotoForm)form;
		FormFile file = userForm.getPhoto();
		try{
			UUID uuid = UUID.randomUUID();
			String pre = uuid.toString();
			String ext = file.getFileName().substring(file.getFileName().lastIndexOf("."));
			File saveFile = new File(this.getServlet().getServletContext().getRealPath("/")+"\\upload",pre+ext);
			InputStream in = file.getInputStream();
			FileOutputStream out = new FileOutputStream(saveFile);
			int len = 0;
			byte[] buf = new byte[1024];
			while((len = in.read(buf))!=-1){
				out.write(buf,0,len);
			}
			in.close();
			out.close();
			response.setContentType("text/html;charset=GBK");
			response.getWriter().print(file.getFileName());
			ArrayList<String> params = new ArrayList<String>();
			params.add(userForm.getName());
			params.add(pre+ext);
			DBUtil.executePreparedSQL("insert into photo(name,fileName) values(?,?)", params);
			ArrayList<String> cols = new ArrayList<String>();
			cols.add("name");
			cols.add("fileName");
			Map<String,ArrayList<String>> result = DBUtil.getArrayResult(cols, "select * from photo");
			request.setAttribute("result", result);
		}catch(Exception e){
			e.printStackTrace();
		}
		return mapping.findForward("/success");
	}
}

 
5.ログインフィルタのコード:
 
package com.tntxia.filter;

import java.io.IOException;

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;

public class LoginFilter implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		String uri = req.getRequestURI();
		
		if(uri.indexOf("login.jsp")!=-1||uri.indexOf("login.do")!=-1){
			chain.doFilter(request, response);
		}else if(session.getAttribute("userId")!=null){
			chain.doFilter(request, response);
		}else{
			res.sendRedirect("login.jsp");
		}

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}