struts框架访问数据库
程序员文章站
2022-07-01 09:14:49
...
一 在MySQL数据库中增加一张用户表
二 创建domain对象
package com.cakin.domain;
public class Users {
private int user_id;
private String user_pwd;
private String user_name;
private String user_email;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_pwd() {
return user_pwd;
}
public void setUser_pwd(String user_pwd) {
this.user_pwd = user_pwd;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
}
三 创建service对象
package com.cakin.service;
import java.util.ArrayList;
import com.cakin.domain.Users;
public class UsersService {
public boolean checkUser(Users user)
{
String sql = "select * from users where user_name =? and user_pwd=? ";
SqlHelper sqlHelper= new SqlHelper();
String [] parameters={user.getUser_name(),user.getUser_pwd()};
ArrayList al=sqlHelper.executeQuery(sql,parameters);
if(al.size()==1)
{
return true;
}
else
{
return false;
}
}
}
四 action验证用户
package com.cakin.actions;
//这是一个action(表示小队长,需要继承Action)
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 com.cakin.domain.Users;
import com.cakin.forms.UserForm;
import com.cakin.service.UsersService;
public class LoginAction extends Action {
private int num=0;
//我们需要重新编写一个方法:execute会被自动调用,有点类似servlet的service方法。
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//把form转成对应的UserForm对象
UserForm userForm=(UserForm)form;
//使用service(士兵到数据库去验证)
UsersService usersService =new UsersService();
Users user = new Users();
user.setUser_name(userForm.getUsername());
user.setUser_pwd(userForm.getPassword());
if(usersService.checkUser(user))
{
return mapping.findForward("ok");
}
else
{
return mapping.findForward("err");
}
}
}
上一篇: Struts基本介绍
下一篇: 终端标识