<2>Struts2.0注册RegisterAction中验证码的逻辑实现
- package com.tarena.dang.user.action;
- import java.io.*;
- import org.apache.struts2.ServletActionContext;
- import com.opensymphony.xwork2.ActionContext;
- import com.tarena.dang.domain.User;
- import com.tarena.dang.user.service.UserService;
- import com.tarena.dang.user.service.UserServiceImpl;
- /**
- * 注册页面的Action控制器业务实现
- * @author JimmyZhang
- *
- */
- public class RegisterAction {
- private UserService userService;
- //使用实体对象简化与表单元素对应关系
- private User user;
- private String vcode;
- //定义与文件域upload赌赢的属性
- private File upload;//上传文件
- private String uploadFileName;//上传文件的文件名
- private String uploadContentType;//上传文件类型
- public String getVcode() {
- return vcode;
- }
- public void setVcode(String vcode) {
- this.vcode = vcode;
- }
- public User getUser() {
- return user;
- }
- public void setUser(User user) {
- this.user = user;
- }
- public RegisterAction(){
- userService = new UserServiceImpl();
- System.out.println("【RegisterAction】调用默认无参构造方法");
- }
- public String execute() throws Exception{
- //判断用户输入的验证与session中是否一直一致
- ActionContext ac = ActionContext.getContext();
- String session_vocode = (String)ac.getSession().get("vcode");
- if(!vcode.equals(session_vocode)){
- ac.put("vcode_info", "<img src='/dang/images/wrong.gif'/>验证码不匹配");
- return "input";
- }
- boolean isSuccess = userService.register(user);
- if(isSuccess){
- //上传头像,File upload-->/images/user/userName.jpg
- //得到服务器端的物理路径
- String path = ServletActionContext
- .getServletContext().getRealPath("/images/user/"+user.getUserName()+".jpg");
- //创建服务器端文件的File对象
- File dest = new File(path);
- //upload-->dest
- InputStream fis = new FileInputStream(upload);
- OutputStream fos = new FileOutputStream(dest);
- byte[] b = new byte[1024];
- int n;
- while((n=fis.read(b,0,b.length))!=-1){
- fos.write(b,0,n);
- }
- fos.close();
- fis.close();
- //注册成功
- ac.put("user", user);
- return "ok";
- }else{
- return "input";
- }
- }
- public File getUpload() {
- return upload;
- }
- public void setUpload(File upload) {
- this.upload = upload;
- }
- public String getUploadFileName() {
- return uploadFileName;
- }
- public void setUploadFileName(String uploadFileName) {
- this.uploadFileName = uploadFileName;
- }
- public String getUploadContentType() {
- return uploadContentType;
- }
- public void setUploadContentType(String uploadContentType) {
- this.uploadContentType = uploadContentType;
- }
- }
