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

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

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

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

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

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

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

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

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

上代码:

首先 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");
}
}

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

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

刚開始学习的人非常有用:纯struts框架实现用户登陆的更多相关文章

  1. 刚開始学习的人非常有用之chm结尾的參考手冊打开后无法正常显示

    从网上下载了struts2的參考手冊.chm(本文适用全部已.chm结尾的文件)不能正常打开使用. 如图: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/ ...

  2. 刚開始学习的人非常有用:struts2中将jsp数据传到action的几种方式

    先给上struts.xml代码: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE strut ...

  3. wxWidgets刚開始学习的人导引(3)——wxWidgets应用程序初体验

    wxWidgets刚開始学习的人导引全文件夹   PDF版及附件下载 1 前言2 下载.安装wxWidgets3 wxWidgets应用程序初体验4 wxWidgets学习资料及利用方法指导5 用wx ...

  4. wxWidgets刚開始学习的人导引(2)——下载、安装wxWidgets

    wxWidgets刚開始学习的人导引全目录   PDF版及附件下载 1 前言2 下载.安装wxWidgets3 wxWidgets应用程序初体验4 wxWidgets学习资料及利用方法指导5 用wxS ...

  5. wxWidgets刚開始学习的人导引(4)——wxWidgets学习资料及利用方法指导

    wxWidgets刚開始学习的人导引全文件夹   PDF版及附件下载 1 前言2 下载.安装wxWidgets3 wxWidgets应用程序初体验4 wxWidgets学习资料及利用方法指导5 用wx ...

  6. 刚開始学习的人制作VMOS场效应管小功放

    VMOS场效应管既有电子管的长处又有晶体管的长处,用它制作的功率放大器声音醇厚.甜美,动态范围大.频率响应好.因此近年来在音响设备中得到了广泛应用. 大功率的场效应管功率放大器.电.路比較复杂.制作和 ...

  7. wxWidgets刚開始学习的人导引(1)——前言

    wxWidgets刚開始学习的人导引全文件夹   PDF版及附件下载 1 前言2 下载.安装wxWidgets3 wxWidgets应用程序初体验4 wxWidgets学习资料及利用方法指导5 用wx ...

  8. 对于刚開始学习的人Xcode最经常使用的快捷键

    对于刚開始学习的人而言,好多人都是直接使用鼠标进行操作.差点儿非常少使用快捷键,从而再练习编程时比别人慢那么一点,今天就把刚開始学习的人最经常使用的几个快捷键给大家总结下,当然欢迎大家补充. (1)c ...

  9. 【React Native开发】React Native配置执行官方样例-刚開始学习的人的福音(8)

    ),React Native技术交流4群(458982758),请不要反复加群! 欢迎各位大牛,React Native技术爱好者加入交流!同一时候博客左側欢迎微信扫描关注订阅号,移动技术干货,精彩文 ...

随机推荐

  1. 【Floyd矩阵乘法】BZOJ1706- [usaco2007 Nov]relays 奶牛接力跑

    [题目大意] 给出一张无向图,求出恰巧经过n条边的最短路. [思路] 首先题目中只有100条边,却给出了10000个点(实际上最多只能有200个),离散化一下. 后面就是Floyd的新姿势,以前看过的 ...

  2. [转]Android Message.obtain() 和Handler.obtainMessage()的区别

        目录(?)[+]   参考:http://www.2cto.com/kf/201311/255885.html http://www.cnblogs.com/over140/archive/2 ...

  3. SQLite3知识(1)--教程

    1.SQLite3教程 [1].SQLite 教程 2.选择数据库: [2]. SQLite Select 语句 3.更新数据库: [3]. SQLite Update 语句 4.插入数据库: [4] ...

  4. [Linux] tmux 终端复用命令行工具

    tmux 终端复用命令行工具 tmux 是一款终端复用命令行工具,通常用于 Terminal 的窗口管理.可以在终端软件重启后通过命令行恢复上次的 session. 安装运行 macOS 上使用 Ho ...

  5. BZOJ2831(小强的金字塔系列问题--区域整点数求法)

    题目:2831: 小强的金字塔 题意就是给出A,B,C,R,L,然后求 这里其实用到扩展欧几里德.(基本上参照clj的解题报告才理解的) 分析:我们先来分析一般情况: 这里我们假设A<C和B&l ...

  6. shell中set的用法(转)

    使用set命令可以设置各种shell选项或者列出shell变量.单个选项设置常用的特性. 在某些选项之后-o参数将特殊特性打开.在某些选项之后使用+o参数将关闭某些特性, 不带任何参数的set命令将显 ...

  7. ios 得到目录大小 进率是1000

    - (CGFloat)folderSizeAtPath:(NSString *) folderPath {     NSFileManager * manager = [NSFileManager d ...

  8. unix环境高级编程----进程控制wait()

    一.wait()函数 当一个进程中调用wait()函数的时候 (1)假设其全部的子程序都还在执行,则堵塞 (2)假设一个子进程已终止.则等待父进程获取其终止状态. (3)假设没有子进程,则返回错误. ...

  9. json-lib包笔记

    json-lib.jar开发包使用: 依赖包:commons-beanutils.jar;commons-httpclient.jar;commons-lang.jar;ezmorph.jar;不少人 ...

  10. mysqld_safe脚本执行的基本流程

    mysqld_safe脚本执行的基本流程:1.查找basedir和ledir.2.查找datadir和my.cnf.3.对my.cnf做一些检查,具体检查哪些选项请看附件中的注释.4.解析my.cnf ...