刚開始学习的人非常有用:纯struts框架实现用户登陆

本人新手一枚。也在学习ssh。高手建议从struts2開始学起,所以我就先仅仅用struts2写了一个demo。能够有助于理解struts2在项目中的作用。

首先简单了解一下struts2 的MVC模式:

刚開始学习的人非常有用:纯struts框架实现用户登陆

M:就是业务逻辑层,代码体现就是:service层

V:就是视图层,代码提现就是:jsp

C:就是控制层。代码提现就是:actionservlet

那么我们会讲代码贴上。并会加一些凝视

首先我们是创建一个动态webproject;

project展示:先依照我的包结构。建好包结构

刚開始学习的人非常有用:纯struts框架实现用户登陆

项目依赖的包:点击此处下载jar包

刚開始学习的人非常有用:纯struts框架实现用户登陆

上代码:

首先 web.xml

<?

xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>struts2-5</display-name> <filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> </web-app>

然后是struts.xml

<?xml version="1.0" encoding="UTF-8"?

>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="defalut" extends="struts-default">
<action name="user_*_*" class="com.sino.java.action.{1}Action" method="{2}">
<result name="success">/pages/success.jsp</result>
<result name="error">/pages/error.jsp</result>
<result name="tologin">/index.jsp</result>
<result name="show">/pages/show.jsp</result>
<result name="regsuccess">/pages/regsuccess.jsp</result>
<result name="input">/pages/reg.jsp</result>
<result name="showbook">/pages/showbook.jsp</result>
</action> </package>
</struts>

我把sql也贴出来吧,后面我会提供下载的连接

/*
SQLyog Ultimate v11.24 (32 bit)
MySQL - 5.5.24 : Database - struts2_4
*********************************************************************
*/ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`struts2_4` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `struts2_4`; /*Table structure for table `user` */ DROP TABLE IF EXISTS `user`; CREATE TABLE `user` (
`name` varchar(30) DEFAULT NULL,
`username` varchar(30) NOT NULL,
`password` varchar(30) DEFAULT NULL,
PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `user` */ insert into `user`(`name`,`username`,`password`) values ('DLK','admin','admin'); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

config.properties:

#请改动以下的数据库username与password,并导入上面的数据库文件
userDaoFactory=com.sino.java.dao.UserDao
url=jdbc:mysql://localhost:3306/struts2_4? useUnicode=true&characterEncoding=UTF-8
user=root
password=root

log4j.properties

#private static final Logger log = Logger.getLogger(LoginAction.class);
log4j.rootLogger=INFO,A1,R log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.Target=System.out
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%c]%m%n log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=sshe.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.Threshold=ALL
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n

然后就是

java文件:

我依照上面的项目展示的文件夹来贴代码:

----------------------------------------------------------------------------------------

package com.sino.java.action;

import java.util.Iterator;
import java.util.List; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sino.java.been.User;
import com.sino.java.dao.UserDao;
import com.sino.java.dao.impl.UserDaoImpl;
import com.sino.java.service.UserService;
import com.sino.java.service.impl.UserServiceImpl; public class LoginAction extends ActionSupport implements ModelDriven<User> {
private static final Logger log = Logger.getLogger(LoginAction.class);
private User user; private UserService userservice; private UserDao userdao; public UserDao getUserdao() {
return userdao;
} public void setUserdao(UserDao userdao) {
this.userdao = userdao;
} public User getUser() {
return user;
} public void setUser(User user) {
this.user = user;
} private String msg; public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
} // 用户登录
public String login() {
// 是否已经登陆
ActionContext action = ActionContext.getContext();
if (action.getSession().get("username") == ""
|| action.getSession().get("username") == null) {
userservice = new UserServiceImpl();
userdao = new UserDaoImpl(); log.info("登陆页面传来的数据:用户名:" + user.getUsername() + "+密码:"
+ user.getPassword());
log.info("userservice:" + userservice.toString());
log.info("user:" + user.toString());
log.info("userdao:" + userdao.toString()); User users = userservice.login(user.getUsername(),user.getPassword());
log.info("数据库查询的数据:" + users.getName());
log.info("数据库查询的数据:" + users.getUsername());
log.info("数据库查询的数据:" + users.getPassword());
log.info(users); if (!"".equals(users.getName()) && users.getName() != null) {
action.getSession().put("username", users.getUsername());
action.getSession().put("name", users.getName());
msg = "恭喜登陆成功!" + users.getName();
return SUCCESS;
} else {
msg = "用户名或密码错误! ";
return "tologin";
}
} else {
msg = "已经登陆" + user.getUsername();
return SUCCESS;
}
} // 注冊用户
public String reg() {
userservice = new UserServiceImpl(); log.info("userservice:" + userservice.toString());
int a = userservice.reg(user.getName(), user.getUsername(),
user.getPassword(), user.getAge(), user.getSex());
log.info("结果:" + a);
log.info("传人的数据为:" + user.toString());
if (a != 0) {
return "regsuccess";
} else {
return "regerror";
}
} public String show() {
userdao = new UserDaoImpl();
ActionContext action = ActionContext.getContext();
String name = (String) action.getSession().get("name");
List<User> userlist = userdao.getAllUser(name); log.info("数据库查到数据长度>>" + userlist.size());
Iterator it = userlist.iterator();
while (it.hasNext()) {
User user = new User();
user = (User) it.next();
log.info("数据库查询出来的用户名:" + user.getUsername());
log.info("数据库查询出来的密码:" + user.getPassword());
}
HttpServletRequest hsr = ServletActionContext.getRequest();
hsr.setAttribute("userlist", userlist);
return "show";
} public String logout() {
ActionContext action = ActionContext.getContext();
log.info("将session设置为空!并退出登陆。");
action.getSession().put("username", null); return "tologin";
} @Override
public User getModel() {
// TODO Auto-generated method stub
if (user == null) {
user = new User();
}
return user;
} }

-------------------------------------------------------------

package com.sino.java.been;

public class User {
private String name;
private String username;
private String age;
private String sex;
private String password; public User() {
// TODO Auto-generated constructor stub
} public User(String name, String username, String age, String sex,
String password) {
super();
this.name = name;
this.username = username;
this.age = age;
this.sex = sex;
this.password = password;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getAge() {
return age;
} public void setAge(String age) {
this.age = age;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} }

----------------------------------------------------------------------------------------

package com.sino.java.dao;

import java.util.List; 

import com.sino.java.been.User;

public interface UserDao {
public List<User> getAllUser(String name);
public User getUser(String username, String password);
public int insert(User user);
}

------------------------------------------------------------------------------------------

package com.sino.java.dao.factory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; import com.sino.java.dao.UserDao; public class DaoFactory {
// 注意 对象的 创建顺序
private static UserDao userDao = null;
private static DaoFactory instance = new DaoFactory(); private DaoFactory() {
try {
Properties prop = new Properties();
// InputStream inStream = new FileInputStream(new
// File("src/daoconfig.properties"));
// 长处:文件不一定要和路径绑定,仅仅要文件从在于 ClassPath 中 就能够找得到
InputStream inStream = DaoFactory.class.getClassLoader()
.getResourceAsStream("config.properties");
prop.load(inStream);
// 从配置文件里获得的 value 值 都是字符串(String)
String userDaoClzz = prop.getProperty("userDaoFactory");
System.out.println("userdao-"+userDaoClzz);
// 通过反射方式 创建对象
Class clazz = Class.forName(userDaoClzz);
userDao = (UserDao) clazz.newInstance();
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
} public static DaoFactory getInstance() {
return instance;
} public static UserDao getUserDao() {
return userDao;
} }

--------------------------------------------------------------------------------------------------

package com.sino.java.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List; import org.apache.log4j.Logger; import com.sino.java.been.User;
import com.sino.java.dao.UserDao;
import com.sino.java.service.impl.UserServiceImpl;
import com.sino.java.utils.JdbcUtils; public class UserDaoImpl implements UserDao {
private static final Logger log = Logger.getLogger(UserDaoImpl.class); public int insert(User user) {
Connection con = null;
PreparedStatement ps = null;
int i = 0;
ResultSet rs = null;
try {
con = JdbcUtils.getConn();
String sql = "insert into user(name,username,password) values(?,?,?) ";
ps = con.prepareStatement(sql);
ps.setString(1, user.getName());
ps.setString(2, user.getUsername());
ps.setString(3, user.getPassword()); i = ps.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
}finally
{
JdbcUtils.free(rs, ps, con);
}
return i;
} @Override
public List<User> getAllUser(String name) {
// TODO Auto-generated method stub
Connection con = null;
List<User> userlist = new ArrayList<User>();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = "select * from user where name= ? ";
con = JdbcUtils.getConn();
ps = con.prepareStatement(sql); ps.setString(1, name);
rs = ps.executeQuery(); while (rs.next()) {
User user = new User();
user.setUsername(rs.getString(2));
user.setPassword(rs.getString(3));
userlist.add(user);
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace(); }
return userlist;
} public User getUser(String username, String password) {
User user = new User();
ResultSet rs = null;
PreparedStatement ps = null;
Connection conn = null;
try {
conn = JdbcUtils.getConn();
String sql = "select * from user where username=? and password=? ";
/*
* String url =
* "jdbc:mysql://localhost:3306/struts2_4? useUnicode=true&characterEncoding=UTF-8"
* ;
*
* Class.forName("com.mysql.jdbc.Driver"); con =
* DriverManager.getConnection(url,"root","root");
*/
ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery(); while (rs.next()) {
user.setName(rs.getString(1));
user.setUsername(rs.getString(2));
user.setPassword(rs.getString(3));
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JdbcUtils.free(rs, ps, conn);
}
return user; } }

-----------------------------------------------------------------------------------------------------------

package com.sino.java.service;

import com.sino.java.been.User;

/**
* @author Administrator
*
*/
public interface UserService { public User login(String username,String password); public int reg(String name,String username,String password,String age,String sex); public void save(User user) throws Exception; //public DataGrid datagrid(User user); public void delete(String ids); public void update(User user) throws Exception; public void roleEdit(User user); public void editUserInfo(User user); }

-----------------------------------------------------------------------------------------------

package com.sino.java.service.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List; import org.apache.log4j.Logger; import com.opensymphony.xwork2.inject.Factory;
import com.sino.java.action.LoginAction;
import com.sino.java.been.User;
import com.sino.java.dao.UserDao;
import com.sino.java.dao.factory.DaoFactory;
import com.sino.java.dao.impl.UserDaoImpl;
import com.sino.java.service.UserService; public class UserServiceImpl implements UserService{
private static final Logger log = Logger.getLogger(UserServiceImpl.class);
UserDao userDao = new UserDaoImpl(); @Override
public User login(String username,String password) {
// TODO Auto-generated method stub
User user = userDao.getUser(username,password);
return user;
} @Override
public int reg(String name, String username, String password, String age, String sex) {
User user = new User();
user.setName(name);
user.setUsername(username);
user.setPassword(password);
user.setAge(age);
user.setSex(sex);
return userDao.insert(user);
} @Override
public void save(User user) throws Exception {
// TODO Auto-generated method stub } @Override
public void delete(String ids) {
// TODO Auto-generated method stub } @Override
public void update(User user) throws Exception {
// TODO Auto-generated method stub } @Override
public void roleEdit(User user) {
// TODO Auto-generated method stub } @Override
public void editUserInfo(User user) {
// TODO Auto-generated method stub }
}

---------------------------------------------------------------------------------------------------------

package com.sino.java.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; import org.apache.log4j.Logger; import com.sino.java.dao.factory.DaoFactory;
import com.sino.java.dao.impl.UserDaoImpl; // 该工具类不须要被继承
public final class JdbcUtils {
private static String url = "";
private static String user = "";
private static String password = "";
private static final Logger log = Logger.getLogger(UserDaoImpl.class);
// 不同意被创建
private JdbcUtils() {
} static {
try {
Class.forName("com.mysql.jdbc.Driver");
Properties prop = new Properties();
// InputStream inStream = new FileInputStream(new
// File("src/daoconfig.properties"));
// 长处:文件不一定要和路径绑定。仅仅要文件从在于 ClassPath 中 就能够找得到
InputStream inStream = DaoFactory.class.getClassLoader()
.getResourceAsStream("config.properties");
try {
prop.load(inStream);
} catch (IOException e) {
// TODO Auto-generated catch block
log.info("load error");
e.printStackTrace();
}
// 从配置文件里获得的 value 值 都是字符串(String)
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
Class.forName("com.mysql.jdbc.Driver");
log.info("------------------url user password ------------");
log.info(url);
log.info(user);
log.info(password);
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
} public static Connection getConn() throws SQLException {
return DriverManager.getConnection(url, user, password);
} public static void free(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
log.info("test");
}
}

项目源代码下载连接:点击下载

本人新手,假设发现问题也请留言不吝赐教,一起进步。

上一篇:HDU 5652 India and China Origins


下一篇:如何搭建struts2框架