用eclipse写个人网站
这个我个人写网站时候积累的经验
你好! 如果你拥有一些编程基础,我会在我的个人经验上向大家介绍我写网站的历程。
第一步–安装工具
首先安装好eclipse。
第二步–创建工程
在创建web工程时,可能在自己的项目里找不到要创建的Dynamic Web Project,这时因为你的eclipse还没有安装相应的功能。
第三步–添加路径
右键项目点击properties
在Java Build Path中添加相应的路径,注意一定要在Classpath中添加,不然后续操作会出问题,然后点击Add External JARS…
将下列包全部导入
再将他们复制到下图lib当中
第4步–配置数据库文档
我使用的时c3p0连接池,不同的链接方法可能会有所差异,可以百度进行解决。
相关文件1
文件内代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<named-config name="mysql-config">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/assetmanager?characterEncoding=utf-8</property>
<property name="user">root</property>
<property name="password">123456</property>
<!-- 初始化连接池中的连接数 -->
<property name="initialPoolSize">10</property>
<!--最大空闲时间 -->
<property name="maxIdleTime">30</property>
<!--连接池中保留的最大连接数 -->
<property name="maxPoolSize">100</property>
<!-- 连接池中保留的最小连接数-->
<property name="minPoolSize">10</property>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement">3</property>
</named-config>
</c3p0-config>
相关文件2
另外的声明文档
内部代码如下:
############
drivername=com.mysql.jdbc.Driver
url=jdbc:mysql:///myweb?useUnicode=true&characterEncoding=utf-8
username=root
password=123456
##########//c3p0
maxPoolSize=200
minPoolSize=5
initialPoolSize=10
checkoutTimeout=300000
相关文件3
内部代码如下:
# ERROR ----> WARN ---> INFO ---> DEBUG
log4j.rootLogger=DEBUG,stdout,logfile
# stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
# logfile
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=bbs.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%p %d %F %M %m%n
存放位置
他们全部都直接存放再如下图的位置
即工程的src里面
第5步–编写链接数据库代码
要创建3个文件
代码1:
package com.hpe.util;
import java.sql.Connection;
import java.util.Properties;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* 数据库连接池
* @author Administrator
*
*/
public class DBDataSource {
//修改 数据库连接参
public static String DRIVER;
public static String URL;
public static String USER;
public static String PWD;
public static int maxPoolSize;
public static int minPoolSize;
public static int initialPoolSize;
public static int checkoutTimeout;
private static ComboPooledDataSource cpDataSource = null;
//加载驱动
static {
try {
//读取配置文件,加载JDBC四大参数
Properties config = new Properties();
config.load(DBDataSource.class.getClassLoader().getResourceAsStream("db.properties"));
DRIVER = config.getProperty("drivername");
URL = config.getProperty("url");
USER = config.getProperty("username");
PWD = config.getProperty("password");
maxPoolSize = Integer.parseInt(config.getProperty("maxPoolSize"));
minPoolSize = Integer.parseInt(config.getProperty("minPoolSize"));
initialPoolSize = Integer.parseInt(config.getProperty("initialPoolSize"));
checkoutTimeout = Integer.parseInt(config.getProperty("checkoutTimeout"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**************** c3p0 数据库连接池 启动方法******************/
private static void c3p0DataSource() throws Exception {
cpDataSource = new ComboPooledDataSource();
cpDataSource.setDriverClass(DRIVER);
cpDataSource.setJdbcUrl(URL);
cpDataSource.setUser(USER);
cpDataSource.setPassword(PWD);
cpDataSource.setMaxPoolSize(maxPoolSize);
cpDataSource.setMinPoolSize(minPoolSize);
cpDataSource.setInitialPoolSize(initialPoolSize);
cpDataSource.setCheckoutTimeout(checkoutTimeout);
}
/**
* c3p0数据库连接入
*
* @return
* @throws Exception
*/
public static Connection getConnectionC3P0() throws Exception {
if (cpDataSource == null) {
c3p0DataSource();
}
Connection conn = null;
if (cpDataSource != null) {
conn = cpDataSource.getConnection();
}
return conn;
}
}
代码2:
package com.hpe.util;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
/**
* 数据库操作辅助类
* @version 3.0
* @author yaohc
*/
public class DBUtil {
private static Logger logger = Logger.getLogger("DBUtil");
// 创建一个与事务相关的局部线程变量
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
//private static Connection conn;
/**
* 该语句必须是 SQL INSERT、UPDATE 、DELETE 语句
*
* @param sql
* @return
* @throws Exception
*/
public int execute(String sql) throws Exception {
return execute(sql,new Object[]{});
}
/**
* 该语句必须是 SQL INSERT、UPDATE 、DELETE 语句
* insert into table values(?,?,?,?)
* @param sql
* @param paramList:参数,与SQL语句中的占位符一
* @return
* @throws Exception
*/
public int execute(String sql,Object[] paramList) throws Exception {
if (sql == null || sql.trim().equals("")) {
logger.info("parameter is valid!");
}
Connection conn = null;
//创建执行对象
PreparedStatement pstmt = null;
int result = 0;
try {
conn = getConnection();
// 预编译sql语句
pstmt = DBUtil.getPreparedStatement(conn, sql);
// 填充占位符(给SQL语句传递参数)
setPreparedStatementParam(pstmt, paramList);
if (pstmt == null) {
return -1;
}
result = pstmt.executeUpdate();
} catch (Exception e) {
logger.info(e.getMessage());
throw new Exception(e);
} finally {
closeStatement(pstmt);
closeConn(conn);
}
return result;
}
/**
* 事物处理类
* @param connection
* @param sql
* @param paramList:参数,与SQL语句中的占位符一
* @return
* @throws Exception
*/
public int execute(Connection conn,String sql,Object[] paramList) throws Exception {
if (sql == null || sql.trim().equals("")) {
logger.info("parameter is valid!");
}
PreparedStatement pstmt = null;
int result = 0;
try {
pstmt = DBUtil.getPreparedStatement(conn, sql);
setPreparedStatementParam(pstmt, paramList);
if (pstmt == null) {
return -1;
}
result = pstmt.executeUpdate();
} catch (Exception e) {
logger.info(e.getMessage());
throw new Exception(e);
} finally {
closeStatement(pstmt);
}
return result;
}
/**
* 获取实体类型的方法,type为实体类类型。
* @param type
* @param sql
* @param paramList
* @return
* @throws Exception
*/
public Object getObject(Class<?> type, String sql,Object[] paramList) throws Exception {
// 获取javaBean属性
BeanInfo beanInfo = Introspector.getBeanInfo(type);
// 创建 JavaBean 对象
Object obj = type.newInstance();
//获取Javabean中的所有属性,并给 JavaBean 对象的属性赋值
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
Map map = getObject(sql, paramList);
if(map != null){
for (int i = 0; i< propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (map != null && map.containsKey(propertyName)) {
Object value = map.get(propertyName);
Object[] args = new Object[1];
args[0] = value;
try{
descriptor.getWriteMethod().invoke(obj, args);
}catch(Exception e){
logger.info("检测一下Table列,和实体类属性:" + propertyName + ""
+ "是否一致,并且是否是" + value.getClass() + "类型");
throw new Exception("检测一下Table列,和实体类属性:" + propertyName + ""
+ "是否一致,并且是否是" + value.getClass() + "类型");
}
}
}
}else{
obj = null;
}
return obj;
}
public List<Class<?>> getQueryList(Class<?> type, String sql,Object[] paramList) throws Exception {
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
List<Map<String,Object>> list = getQueryList(sql, paramList);
List beanList = new ArrayList();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Map<String, Object> map = (Map<String, Object>) iterator.next();
Object obj = type.newInstance();
for (int i = 0; i< propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (map != null && map.containsKey(propertyName)) {
Object value = map.get(propertyName);
Object[] args = new Object[1];
args[0] = value;
try{
descriptor.getWriteMethod().invoke(obj, args);
}catch(Exception e){
logger.info("检测一下Table列,和实体类属性:" + propertyName + ""
+ "是否一致,并且是否是" + value.getClass() + "类型");
throw new Exception("检测一下Table列,和实体类属性:" + propertyName + ""
+ "是否一致,并且是否是" + value.getClass() + "类型"); }
}
}
beanList.add(obj);
}
return beanList;
}
/**
* 将查询数据库获得的结果集转换为Map对象
*
* @param sql:查询
* @return
*/
public List<Map<String, Object>> getQueryList(String sql) throws Exception {
return getQueryList(sql,new Object[]{});
}
/**
* 将查询数据库获得的结果集转换为Map对象
*
* @param sql:查询
* @param paramList:参数
* @return
*/
public List<Map<String, Object>> getQueryList(String sql, Object[] paramList) throws Exception {
if (sql == null || sql.trim().equals("")) {
logger.info("parameter is valid!");
return null;
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Map<String, Object>> queryList = null;
try {
conn = getConnection();
pstmt = DBUtil.getPreparedStatement(conn, sql);
setPreparedStatementParam(pstmt, paramList);
if (pstmt == null) {
return null;
}
rs = getResultSet(pstmt);
queryList = getQueryList(rs);
} catch (RuntimeException e) {
logger.info(e.getMessage());
System.out.println("parameter is valid!");
throw new Exception(e);
} finally {
closeResultSet(rs);
closeStatement(pstmt);
closeConn(conn);
}
return queryList;
}
/**
* 分页查询
* @param sql
* @param params 查询条件参数
* @param page 分页信息
* @return
*/
public Page getQueryPage(Class<?> type, String sql,Object[] params,Page page){
int totalPages = 0; //页数
Long rows = 0l;//数据记录数
//分页工具类
List<Class<?>> list = null;
Map countMap = null;
try {
list = this.getQueryList(type,sql
+ " limit "
+ (page.getCurPage()-1)*page.getPageNumber()
+" , "+page.getPageNumber(),params);
countMap = this.getObject(" "
+ "select count(*) c from ("+ sql +") as t ", params);
rows = (Long)countMap.get("c");
//求余数
if(rows % page.getPageNumber() ==0){
totalPages = rows.intValue() / page.getPageNumber();
}else{
totalPages = rows.intValue() / page.getPageNumber() + 1;
}
page.setRows(rows.intValue());
page.setList(list);
page.setTotalPage(totalPages);
}catch(Exception e){
e.printStackTrace();
}
return page;
}
/**
* 将查询数据库获得的结果集转换为Map对象
* @param sql:查询
* @return
*/
public Map<String, Object> getObject(String sql) throws Exception {
return getObject(sql,new Object[]{});
}
/**
* 将查询数据库获得的结果集转换为Map对象
*
* @param sql:查询
* @param paramList:参数
* @return
*/
public Map<String, Object> getObject(String sql, Object[] paramList) throws Exception {
if (sql == null || sql.trim().equals("")) {
logger.info("parameter is valid!");
return null;
}
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Map map = new HashMap<String,Object>();
try {
conn = getConnection();
pstmt = DBUtil.getPreparedStatement(conn, sql);
setPreparedStatementParam(pstmt, paramList);
if (pstmt == null) {
return null;
}
//针对查询的执行操作
rs = getResultSet(pstmt);
List list = getQueryList(rs);
if(list.isEmpty()){
return null;
}
//获取list中第一个元素
map = (HashMap) list.get(0);
} catch (RuntimeException e) {
logger.info(e.getMessage());
logger.info("parameter is valid!");
throw new Exception(e);
} finally {
closeResultSet(rs);
closeStatement(pstmt);
closeConn(conn);
}
return map;
}
private static PreparedStatement getPreparedStatement(Connection conn, String sql) throws Exception {
if (conn == null || sql == null || sql.trim().equals("")) {
return null;
}
PreparedStatement pstmt = conn.prepareStatement(sql.trim());
return pstmt;
}
private void setPreparedStatementParam(PreparedStatement pstmt, Object[] paramList) throws Exception {
if (pstmt == null || paramList == null) {
return;
}
DateFormat df = DateFormat.getDateTimeInstance();
for (int i = 0; i < paramList.length; i++) {
//-
if (paramList[i] instanceof Integer) {
int paramValue = ((Integer) paramList[i]).intValue();
pstmt.setInt(i + 1, paramValue);
} else if (paramList[i] instanceof Float) {
float paramValue = ((Float) paramList[i]).floatValue();
pstmt.setFloat(i + 1, paramValue);
} else if (paramList[i] instanceof Double) {
double paramValue = ((Double) paramList[i]).doubleValue();
pstmt.setDouble(i + 1, paramValue);
} else if (paramList[i] instanceof Date) {
pstmt.setString(i + 1, df.format((Date) paramList[i]));
} else if (paramList[i] instanceof Long) {
long paramValue = ((Long) paramList[i]).longValue();
pstmt.setLong(i + 1, paramValue);
} else if (paramList[i] instanceof String) {
pstmt.setString(i + 1, (String) paramList[i]);
}
//= pstmt.setObject(i + 1, paramList[i]);
}
return;
}
/**
* 获得数据库查询结果集
*
* @param pstmt
* @return
* @throws Exception
*/
//针对查询的执行操作
private ResultSet getResultSet(PreparedStatement pstmt) throws Exception {
if (pstmt == null) {
return null;
}
ResultSet rs = pstmt.executeQuery();
return rs;
}
/**
* @param rs
* @return
* @throws Exception
*/
//打印结果集
private List<Map<String, Object>> getQueryList(ResultSet rs) throws Exception {
if (rs == null) {
return null;
}
//得到结果集的结构,比如字段数、字段名等
ResultSetMetaData rsMetaData = rs.getMetaData();
//得到结果集的列数
int columnCount = rsMetaData.getColumnCount();
List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
while (rs.next()) {
//获取结果集的每一列的值,结合3得到一个Map,键是列名,值的值
Map<String, Object> dataMap = new HashMap<String, Object>();
for (int i = 0; i < columnCount; i++) {
//把指定列的名称和列的值放到map里
dataMap.put(rsMetaData.getColumnLabel(i + 1), rs.getObject(i + 1));
}
dataList.add(dataMap);
}
return dataList;
}
/**
* 关闭数据库
*
* @param conn
*/
private void closeConn(Connection conn) {
if (conn == null) {
return;
}
try {
conn.close();
} catch (SQLException e) {
logger.info(e.getMessage());
}
}
/**
* 关闭
*
* @param stmt
*/
private void closeStatement(Statement stmt) {
if (stmt == null) {
return;
}
try {
stmt.close();
} catch (SQLException e) {
logger.info(e.getMessage());
}
}
/**
* 关闭
*
* @param rs
*/
private void closeResultSet(ResultSet rs) {
if (rs == null) {
return;
}
try {
rs.close();
} catch (SQLException e) {
logger.info(e.getMessage());
}
}
/**
* 可以选择三个不同的数据库连接
*
* @param JDBC
* ,JNDI(依赖web容器 DBCP
* @return
* @throws Exception
*/
public static Connection getConnection() throws Exception {
Connection conn = tl.get();
if(conn ==null){
conn = DBDataSource.getConnectionC3P0();
}
return conn;
}
/***********事务处理方法************/
/**
* 开启事务
*/
public static void beginTranscation() throws Exception{
Connection conn = tl.get();
if(conn != null){
logger.info("事务已经开始!");
throw new SQLException("事务已经开始!");
}
conn = DBDataSource.getConnectionC3P0();
conn.setAutoCommit(false);
tl.set(conn);
}
/**
* 结束事务
* @throws SQLException
*/
public static void endTranscation() throws SQLException{
Connection conn = tl.get();
if(conn == null){
logger.info("当前没有事务!");
throw new SQLException("当前没有事务!");
}
conn.commit();
}
/**
* 回滚
* @throws SQLException
*/
public static void rollback() throws SQLException{
Connection conn = tl.get();
if(conn == null){
logger.info("当前没有事务,不能回滚!");
throw new SQLException("当前没有事务,不能回滚!");
}
conn.rollback();
}
/**
* 事务处理,关闭资源
* @throws SQLException
*/
public static void closeConn() throws SQLException{
Connection conn = tl.get();
if(conn == null){
logger.info("当前没有连接,不需要关闭Connection。");
throw new SQLException("当前没有连接,不需要关闭Connection。");
}
conn.close();
tl.remove();
}
}
代码3:
package com.hpe.util;
import java.util.ArrayList;
import java.util.List;
/*
* 分页实体类
*/
public class Page {
//每页显示的条数
private int pageNumber=5;
//当前页
private int curPage;
//总条数
private int rows;
//总页数
private int totalPage;
//要现实的list
private List list=new ArrayList();
public int getPageNumber() {
return pageNumber;
}
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public int getCurPage() {
return curPage;
}
public void setCurPage(int curPage) {
this.curPage = curPage;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
@Override
public String toString() {
return "Page [pageNumber=" + pageNumber + ", curPage=" + curPage + ", rows=" + rows + ", totalPage=" + totalPage
+ ", list=" + list + "]";
}
}
这些代码按顺序分别对应上面3个文件内的代码
第6步–编写后端代码
总体结构如下(第一个包不用):
创建数据层(在src下)
内部代码如下:
package Pojo;
public class AdminPo {
private int id; // 账户id
private String name; // 账户姓名
private String pwd; //密码;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
/**
* @param id
* @param name
* @param pwd
*/
public AdminPo( String name, String pwd) {
super();
this.name = name;
this.pwd = pwd;
}
public AdminPo(int id, String name, String pwd) {
super();
this.id = id;
this.name = name;
this.pwd = pwd;
}
public AdminPo() {
super();
}
}
创建持久层接口和实例化持久层
内部代码:
package Dao;
import Pojo.AdminPo;
public interface IAdminDao {
// 根据用户名和密码查询,登录
AdminPo login(String name,String pwd);
// 根据姓名查询
AdminPo findByName(String name);
// 更改账户信息
int update(AdminPo admin);
//注册用户信息
int add(AdminPo admin);
}
内部代码:
package DaoImpl;
import Pojo.AdminPo;
import Dao.IAdminDao;
import com.hpe.util.DBUtil;
public class AdminDaoImpl implements IAdminDao {
private DBUtil dbUtil = new DBUtil();
/**
* 登录功能 输入:String 管理员账号 String 管理员密码 返回值:AdminPo 账号对象
*
*/
public AdminPo login(String name, String pwd) {
// 查询语句 (动态)
String sql = "select * from admin where name = ? and pwd = ?";
// 参数列表
Object[] objects = { name, pwd };
// 调用DBUtil中的getObject方法进行查询
AdminPo aPo = null;
try {
aPo = (AdminPo) dbUtil.getObject(AdminPo.class, sql, objects);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 返回结果
return aPo;
}
public AdminPo findByName(String name) {
// 根据姓名查询
String sql = "select * from admin where name =?";
// 参数列表
Object[] objects = { name };
// 调用DBUtil中的getObject方法进行查询
AdminPo aPo = null;
try {
aPo = (AdminPo) dbUtil.getObject(AdminPo.class, sql, objects);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 返回结果
return aPo;
}
@Override
public int update(AdminPo admin) {
// TODO Auto-generated method stub
String sql = "update admin set name = ?, pwd = ? where id=?";
// 占位符的参数列表
Object[] objects = { admin.getName(), admin.getPwd(), admin.getId() };
// 借助dbutil
int result = 0;
try {
// 结果返回默认值是失败
result = dbUtil.execute(sql, objects);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
@Override
public int add(AdminPo admin) {
// TODO Auto-generated method stub
String sql = "INSERT INTO admin (name, pwd) VALUES (?, ?)";
// 占位符的参数列表
Object[] objects = { admin.getName(), admin.getPwd()};
// 借助dbutil
int result = 0;
try {
// 结果返回默认值是失败
result = dbUtil.execute(sql, objects);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
创建服务层
服务层接口
内部代码:
package Service;
import Pojo.AdminPo;
public interface IAdminService {
AdminPo longin(String name,String pwd);
// 修改1表示成功,0表示失败,-1表示用户名已存在
int update(AdminPo admin);
// 修改1表示成功,0表示失败,-1表示用户名已存在
int add(AdminPo admin);
}
服务层的实现:
内部代码:
package ServiceImpl;
import Dao.IAdminDao;
import DaoImpl.AdminDaoImpl;
import Pojo.AdminPo;
import Service.IAdminService;
public class AdminServiceImpl implements IAdminService {
private IAdminDao ad = new AdminDaoImpl();
public AdminPo longin(String name, String pwd) {
// TODO Auto-generated method stub
// 直接调用 admindao中的方法
return ad.login(name, pwd);
}
@Override
public int update(AdminPo admin) {
// 1.查找当前数据库中是否已经存在同名的账号,如果存在则返回-1
AdminPo apo1 = ad.findByName(admin.getName());
if (apo1 != null && apo1.getId() != admin.getId()) {
return -1;
}
// 2.如果不存在,则根据id进行修改并返回修改度的结果
return ad.update(admin);
}
@Override
public int add(AdminPo admin) {
// 1.查找当前数据库中是否已经存在同名的账号,如果存在则返回-1
AdminPo apo1 = ad.findByName(admin.getName());
if (apo1 != null && apo1.getId() != admin.getId()) {
return -1;
}
// 2.如果不存在,添加新用户
return ad.add(admin);
}
}
创建servlet
内部代码(在这个当中有些代码对大家是没有用的,大家在学习的过程中自行删改):
package Servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.hpe.util.Page;
import Pojo.AdminPo;
import Pojo.PeoplePo;
import Service.IAdminService;
import Service.IGradeService;
import Service.IPeopleService;
import ServiceImpl.AdminServiceImpl;
import ServiceImpl.GradeServiceImpl;
import ServiceImpl.PeopleServiceImpl;
/**
* 描述:Admin的控制层servlet 描述: 用来处理Admin账号业务
*
* @author Baoliang Che 时间: 版本: 1.0.0 备注:
*/
@WebServlet("/AdminServlet")
public class AdminServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private IAdminService as = new AdminServiceImpl();
private IGradeService gs = new GradeServiceImpl();
private IPeopleService ps = new PeopleServiceImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void login(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
System.out.println("--------找到了name----" + name + "-----");
System.out.println("--------找到了pwd----" + pwd + "-----");
// 2.调用Service层中的login方法,并获取返回值
AdminPo admin = as.longin(name, pwd);
// 3.如果返回值不为空,提示登陆成功,则进入后台主界面
if (admin != null) {
// 保存当前帐号信息,以便main.jsp显示
HttpSession hSession = request.getSession();
hSession.setAttribute("admin", admin);
response.getWriter().write("<script>" + "alert('恭喜你登陆成功!');" + "window.location.href='"
+ request.getContextPath() + "/main.jsp';" + "</script>");
}
// 4.如果返回值为空,提示账号和密码不正确、请重新登录,再次进入登陆界面
else {
response.getWriter().write("<script>" + "alert('登陆失败!请检查用户名和密码!');" + "window.parent.location.href='"
+ request.getContextPath() + "/admin.jsp';" + "</script>");
}
}
protected void logout(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1.移除当前共享数据
HttpSession hSession = request.getSession();
hSession.removeAttribute("admin");
response.getWriter().write("<script>" + "alert('注销退出!');" + "window.parent.location.href='"
+ request.getContextPath() + "/admin.jsp';" + "</script>");
}
protected void allInfo(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 1.获取成绩信息,并将其放入作用域
System.out.println("--------来到了allInfo里面---------");
HttpSession session = request.getSession();
// 2.获取通告信息列表,并将其放入作用域;
List list = gs.findTypeAll();
session.setAttribute("gradeList", list);
//3.根据返回值看,进行相关页面的响应main.jsp
request.getRequestDispatcher("/main.jsp").forward(request, response);
// 4.跳转到首页
request.getRequestDispatcher("/main.jsp").forward(request, response);
}
// 更改管理员信息
protected void adminUpdate(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("update-------------------");
// 1.获取表单中修改后的管理员姓名和密码,获取当前帐号的ID
String name = request.getParameter("name"); // 修改后的姓名
String pwd = request.getParameter("pwd"); // 修改后的密码
System.out.println(name + " " + pwd);
int id = Integer.parseInt(request.getParameter("id")); // 当前帐号的id,要在网页里先找到
// 2.向Service层提交修改业务
// 3.获取Service返回的结果
AdminPo admin2 = new AdminPo(id, name, pwd);
int result = as.update(admin2);
if (result == 1) {
// 4.根据结果1,如果修改,提示“修改成功”则重新登陆
HttpSession hSession = request.getSession();
hSession.removeAttribute("admin");
// 此时需要将Session中的admin移除
response.getWriter().write("<script>" + "alert('恭喜你修改成功!');" + "window.parent.location.href='"
+ request.getContextPath() + "/admin.jsp';" + "</script>");
} else if (result == -1) {
response.getWriter().write("<script>" + "alert('用户名已存在!');" + "window.location.href='"
+ request.getContextPath() + "/edit_change_admin.jsp';" + "</script>");
} else if (result == 0) {
response.getWriter().write("<script>" + "alert('修改失败!');" + "window.location.href='"
+ request.getContextPath() + "/edit_change_admin.jsp';" + "</script>");
}
}
// 注册新账号
protected void adminAdd(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("---------add-------------------");
// 1.获取表单中的管理员姓名和密码
String name = request.getParameter("name_new"); // 姓名
String pwd = request.getParameter("pwd_new"); // 密码
System.out.println(name + " " + pwd);
// 2.向Service层提交修改业务
// 3.获取Service返回的结果
AdminPo admin2 = new AdminPo(name, pwd);
int result = as.add(admin2);
if (result == 1) {
// 4.根据结果1,如果修改,提示“修改成功”则重新登陆
HttpSession hSession = request.getSession();
AdminPo admin3 = as.longin(name, pwd);
hSession.setAttribute("admin",admin3);
response.getWriter().write("<script>" + "alert('恭喜你注册成功!');" + "window.parent.location.href='"
+ request.getContextPath() + "/main.jsp';" + "</script>");
} else if (result == -1) {
response.getWriter().write("<script>" + "alert('用户名已存在!');" + "window.location.href='"
+ request.getContextPath() + "/admin.jsp';" + "</script>");
} else if (result == 0) {
response.getWriter().write("<script>" + "alert('注册失败!');" + "window.location.href='"
+ request.getContextPath() + "/admin.jsp';" + "</script>");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 先转码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
// 为了在同一个doPost方法中处理多个请求业务,需要一些标记来区分不同的请求
// 对于login提供一个login的标签
// 对于update提供一个update的请求标签
// 针对登录请求进行处理
// 1.获取请求中的账号和密码参数
String action = request.getParameter("action");
if (action.equals("login")) {
// 处理login请求
login(request, response);
} else if (action.equals("allInfo")) {
allInfo(request, response);
} else if (action.equals("logout")) {
System.out.println("----------------logout---------------");
logout(request, response);
} else if (action.equals("update")) {
// 处理update请求
adminUpdate(request, response);
}else if (action.equals("admin_add")) {
// 处理update请求
adminAdd(request, response);
}
}
}
第7步,编写jsp文件
配置web.xml
在WebContent下的WEB-INF中添加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" version="3.0">
<display-name>myweb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>PoepleServlet</servlet-name>
<servlet-class>Servlet.PeopleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PoepleServlet</servlet-name>
<url-pattern>/myweb/PoepleServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>AdminServlet</servlet-name>
<servlet-class>Servlet.AdminServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AdminServlet</servlet-name>
<url-pattern>/myweb/AdminServlet</url-pattern>
</servlet-mapping>
</web-app>
这代码的大概意思就是当你在jsp文件中使用action操作时,这个文件就为jsp的跳转提供了一个位置简称之类。
登录jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<meta name="description" content="">
<meta name="author" content="">
<title>用户登录界面</title>
<!-- 引导核心CSS -->
<link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="bootstrap-3.3.7-dist/css/signin.css" rel="stylesheet">
<!-- 引导核心CSS -->
<link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<!-- 引导主题 -->
<link href="bootstrap-3.3.7-dist/css/bootstrap-theme.min.css"
rel="stylesheet">
<!-- 针对Surface/桌面Windows 8错误的IE10视口攻击 -->
<link href="bootstrap-3.3.7-dist/css/ie10-viewport-bug-workaround.css"
rel="stylesheet">
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>欢迎来到我的登录页面</h1>
<p>请在下方进行登录!</p>
</div>
<form class="form-signin"
action="${pageContext.request.contextPath}/AdminServlet?action=login"
method="post">
<h2 class="form-signin-heading">请登录</h2>
<label for="inputEmail" class="sr-only">邮箱地址</label> <input
type="email" id="inputEmail" class="form-control" name="name"
placeholder="Email address" required autofocus> <label
for="inputPassword" class="sr-only">密码</label> <input
type="password" id="inputPassword" class="form-control" name="pwd"
placeholder="Password" required>
<div class="checkbox">
<label> <input type="checkbox" value="remember-me">
记住我
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
<button class="btn btn-lg btn-primary btn-block" type="button"
data-toggle="modal" data-target="#exampleModal" data-whatever="">注册</button>
</form>
</div>
<!-- /container -->
<!-- javascript的弹出内容 -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="exampleModalLabel">新用户注册</h4>
</div>
<form name="sign_up" class="form-signin"
action="${pageContext.request.contextPath}/AdminServlet?action=admin_add"
method="post">
<div class="modal-body">
<div class="form-group">
<label for="recipient-name" class="control-label">用户名:</label> <input
type="email" class="form-control" id="recipient-name" name="name_new">
</div>
<div class="form-group">
<label for="message-text" class="control-label">密码:</label> <input
type="text" class="form-control" id="recipient-name" name="pwd_new">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="submit" class="btn btn-primary">注册</button>
</div>
</form>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script
src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery
|| document
.write('<script src="bootstrap-3.3.7-dist/js/jquery.min.js"><\/script>')
</script>
<script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script src="bootstrap-3.3.7-dist/js/docs.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="bootstrap-3.3.7-dist/js/ie10-viewport-bug-workaround.js"></script>
<script type="text/javascript" src="bootstrap-3.3.7-dist/js/and.js"></script>
</body>
</html>
这当中的一些css文件我是在bootstrap当中下载的,大家也可以自己先写一个form表单进行测试一下。