mysql5.0
eclipse
在eclipse中创建一个新的Bynamic WEB PROJECT项目。并创建两个包:com.action\ com.db.com.action包中存放所有的Action类com.db包存放与数据库操作相关的类
在src节点上新建两个文件struts.xml,和struts.properties。在struts.properties中写入下面内容:struts.locale=zh_CNstruts.i18n.encoding=GBK
在struts.xml中编写如下内容:
在web.xml中如下内容:
编写login.jsp页面:<%@ page language='java' contentType='text/html; charset=gb2312'%><%@ taglib prefix='s' uri='/struts-tags' %>
用户登录 |
请输入用户名: 请输入密码: |
在com.db包中添加新类:DBConn.javapackage com.db;import java.sql.Connection;import java.sql.DriverManager;public class DBConn { //得到数据库连接 public static Connection createConnection(){ try { Class.forName('com.mysql.jdbc.Driver'); Connection connection=DriverManager.getConnection('jdbc:mysql://localhost:3306/xsglxt','xsglxt','xsglxt'); return connection; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return null; } } //关闭数据库连接 public static void close(Connection connection){ try { connection.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }}
在com.action中添加新类:LoginAction.javapackage com.action;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import com.db.DBConn;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;public class LoginAction extends ActionSupport{ /** * */ private static final long serialVersionUID = 1L; public String adminusername; public String adminuserpassword; public String action;//操作类型 public String errormsg;//错误消息 @Override public String execute() throws Exception { // TODO Auto-generated method stub if('login'.equals(action)){ try {Connection conn=DBConn.createConnection(); String sqlString='select * from adminuser where Adminusername=? '+ 'and Adminuserpassword=?'; PreparedStatement statement=conn.prepareStatement(sqlString); statement.setString(1,adminusername); statement.setString(2, adminuserpassword); ResultSet rSet=statement.executeQuery(); if(rSet.next()){//如果用户名和密码正确 ActionContext.getContext().getSession().put('adminusername', adminusername); ActionContext.getContext().getSession().put('adminuserpassword', adminuserpassword); ActionContext.getContext().getSession().put('adminuserrole', rSet.getString('Adminuserrole')); DBConn.close(conn); return SUCCESS; } else { errormsg=new String('用户名或者密码错误'); } DBConn.close(conn); } catch (Exception e) { // TODO: handle exception errormsg=new String('数据库连接错误'); } } return INPUT; }}
效果图:
如果亲爱的读者喜欢本经验,请点个赞吧
如果你是javaweb开发学习者,那么请订阅本经验吧!会让你少走弯路!!!!!