首页 > 代码库 > 模型驱动的登录系统(ModelDriven)

模型驱动的登录系统(ModelDriven)

package model;

public class UserLogin {
	private String username;
	private String password;
	private String result;
	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 getResult() {
		return result;
	}
	public void setResult(String result) {
		this.result = result;
	}
	
	
}

  上面代码是写了一个user类

package model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class LoginAction extends ActionSupport implements
		ModelDriven<UserLogin> {
	private UserLogin model = new UserLogin();
	@Override
	public UserLogin getModel() {
		return model;
	}
	
	@Override
	public String execute() throws Exception{
		String url="jdbc:mysql://localhost:3306/webdb?characterEncoding=UTF-8";
		Class.forName("com.mysql.jdbc.Driver");
		String user="root";
		String password="123456";
		
		PreparedStatement st = null;
		ResultSet rs=null;
		try{
			Connection conn = DriverManager.getConnection(url,user,password);//连接数据库
			if(conn!=null){
				System.out.println("数据库连接成功!");
			}
			else{
				System.out.println("数据库连接失败!");
				return "error";
			}
			String sql = "select * from t_user where user_name=?";
			st = conn.prepareStatement(sql);
			st.setString(1, getModel().getUsername());
			rs = st.executeQuery();
			
			if(rs.next()){
				if(getModel().getPassword().equals(rs.getString("user_password"))){
					getModel().setResult("登录成功!!!");
					return SUCCESS;
				}
			}
			conn.close();
		}
		catch(Exception e){
			e.printStackTrace();
			return "error";
		}
		return ERROR;
	}
	

}

  利用模型驱动返回result,然后输出在页面上

模型驱动的登录系统(ModelDriven)