本文主要是介绍基于web的学生管理系统(二)java代码阶段,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
代码实现
(一)dao包下代码
1、BaseDao
package com.offcn.dao;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.SQLException;
import java.util.List;
public class BaseDao<T> {
static ComboPooledDataSource ds = null;
static QueryRunner qr = null;
static{
ds = new ComboPooledDataSource();//创建c3p0的连接池对象
qr = new QueryRunner(ds);
}
//封装增删改方法
public int update(String sql,Object...params){
try {
return qr.update(sql,params);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
//单行查询
public T queryOne(String sql,Class<T> clazz,Object... params){
try {
return qr.query(sql,new BeanHandler<>(clazz),params);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
//多行查询
public List<T> queryMore(String sql, Class<T> clazz, Object...params){
try {
return qr.query(sql,new BeanListHandler<>(clazz),params);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
//聚合查询
public Number queryScar(String sql,Object...params){
try {
return qr.query(sql,new ScalarHandler<Number>(),params);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
}
2、StudentDao
package com.offcn.dao;
import com.offcn.entity.Page;
import com.offcn.entity.Student;
import java.util.List;
public class StudentDao extends BaseDao<Student> {
//删除学生信息
public boolean delete(int id){
String sql = "delete from stu where sid=?";
return update(sql,id)>0 ? true : false;
}
//添加学生信息
public boolean insert(Student s){
String sql = "insert into stu(name,age,tel,bir,sex,spic)values(?,?,?,?,?,?)";
Object[] param={s.getName(),s.getAge(),s.getTel(),s.getBir(),s.getSex(),s.getSpic()};
return update(sql,param)>0 ? true : false;
}
//根据id查询学生信息
public Student stuSinSer(int id){
String sql = "select * from stu where sid=?";
return queryOne(sql,Student.class,id);
}
//修改学生信息
public boolean updateStu(Student s,int id){
String sql = "update stu set name=?,age=?,tel=?,bir=?,sex=?,spic=?where sid=?";
Object[] param={s.getName(),s.getAge(),s.getTel(),s.getBir(),s.getSex(),s.getSpic(),id};
return update(sql,param)>0 ? true : false;
}
//模糊查询
public List<Student> StuLike(String name,String sex,Page p){
StringBuffer sql = new StringBuffer("select * from stu where 1=1");
if(name!=null&&!"".equals(name)){
sql.append(" and name like '%"+name+"%'");
}
if("0".equals(sex)||"1".equals(sex)){
sql.append(" and sex="+sex);
}
sql.append(" limit ?,?");
return queryMore(sql.toString(),Student.class,p.getStartIndex(),p.getPageSize());
}
public int LikeNum(String name,String sex){
StringBuffer sql = new StringBuffer("select count(*) from stu where 1=1");
if(name!=null&&!"".equals(name)){
sql.append(" and name like '%"+name+"%'");
}
if("0".equals(sex)||"1".equals(sex)){
sql.append(" and sex="+sex);
}
return queryScar(sql.toString()).intValue();
}
}
3、UserDao
package com.offcn.dao;
import com.offcn.entity.User;
public class UserDao extends BaseDao<User> {
//根据用户名和密码查询用户信息
public User login(String username,String password){
String sql = "select * from user where username=? and pwd=?";
return queryOne(sql,User.class,username,password);
}
//添加用户信息
public Boolean register(User u){
String sql = "insert into user(username,pwd,name,tel,bir) values(?,?,?,?,?)";
Object[] param = {u.getUsername(),u.getPwd(),u.getName(),u.getTel(),u.getBir()};
return update(sql,param)>0 ? true : false;
}
}
(二)entity包下代码
1.Student类
package com.offcn.entity;
import java.util.Date;
public class Student {
private int sid;
private String name;
private int age;
private String tel;
private Date bir;
private int sex;
private String spic;
public Student() {
}
public Student(String name, int age, String tel, Date bir, int sex, String spic) {
this.name = name;
this.age = age;
this.tel = tel;
this.bir = bir;
this.sex = sex;
this.spic = spic;
}
public String getSpic() {
return spic;
}
public void setSpic(String spic) {
this.spic = spic;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public Date getBir() {
return bir;
}
public void setBir(Date bir) {
this.bir = bir;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
}
2、User类
package com.offcn.entity;
import java.util.Date;
public class User {
private String username;
private String pwd;
private String name;
private String tel;
private Date bir;
public User() {
}
public User(String username, String pwd, String name, String tel, Date bir) {
this.username = username;
this.pwd = pwd;
this.name = name;
this.tel = tel;
this.bir = bir;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", pwd='" + pwd + '\'' +
", name='" + name + '\'' +
", tel='" + tel + '\'' +
", bir=" + bir +
'}';
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public Date getBir() {
return bir;
}
public void setBir(Date bir) {
this.bir = bir;
}
}
3、Page类
package com.offcn.entity;
public class Page {
private int curPage;//当前页
private int pageSize;//页容量
private int nextPage;//下一页
private int prevPage;//上一页
private int rows;//总记录数
private int endPage;//总页数
private int startIndex;//每一页的起始行下标
//总体初始化
public Page(int rows,String curPage) {
this.rows = rows;
this.pageSize=5;
initCurPage(curPage);
initPrevPage();
initEndPage();
initNextPage();
initStartIndex();
}
//属性初始化
//初始化当前页
public void initCurPage(String curPage){
//当页面不传当前页,或当前页为空字符串默认首页
if(curPage==null||"".equals(curPage)){
this.curPage = 1;
}else {
this.curPage=Integer.valueOf(curPage);
}
}
//初始化上一页
public void initPrevPage(){
if(curPage>1){
prevPage=curPage-1;
}else {
prevPage=1;
}
}
//初始化下一页
public void initNextPage(){
if(curPage<endPage){
nextPage=curPage+1;
}else {
nextPage=endPage;
}
}
//初始化总页数
public void initEndPage(){
if(rows%pageSize==0){
endPage=rows/pageSize;
}else {
endPage=rows/pageSize+1;
}
}
//初始化起始行
public void initStartIndex(){
startIndex=(curPage-1)*pageSize;
}
public int getCurPage() {
return curPage;
}
public void setCurPage(int curPage) {
this.curPage = curPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getNextPage() {
return nextPage;
}
public void setNextPage(int nextPage) {
this.nextPage = nextPage;
}
public int getPrevPage() {
return prevPage;
}
public void setPrevPage(int prevPage) {
this.prevPage = prevPage;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getEndPage() {
return endPage;
}
public void setEndPage(int endPage) {
this.endPage = endPage;
}
public int getStartIndex() {
return startIndex;
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
}
(三)filter包下代码
1、EncodeFilter类
package com.offcn.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
//Filter过滤器,解决乱码
@WebFilter("/*")
public class EncodeFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
}
2、LoginFilter类
package com.offcn.filter;
import com.offcn.entity.User;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
//登录过滤器
@WebFilter("/*")
public class LoginFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//向下转型
HttpServletRequest req = (HttpServletRequest)servletRequest;
HttpServletResponse resp = (HttpServletResponse)servletResponse;
//获取uri地址
String uri = req.getRequestURI();
//截取出需要的地址
String uriPath = uri.substring(uri.lastIndexOf("/")+1);
//判断,所有登录之前的操作直接放行,否则查看是否有用户信息,有就直接放行,没有就回到登录页面去登录
if("register.jsp".equals(uriPath)||"register".equals(uriPath)||"hello".equals(uriPath)||"index.jsp".equals(uriPath)){
filterChain.doFilter(req,resp);
}else {
HttpSession session = req.getSession();
Object user = (User)session.getAttribute("user");
if(user!=null){
filterChain.doFilter(req,resp);
}else{
resp.sendRedirect("index.jsp");
}
}
}
}
(四)login包下代码
1、Login类
package com.offcn.login;
import com.offcn.dao.UserDao;
import com.offcn.entity.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/hello")
public class Login extends HttpServlet{
//实例化dao对象
UserDao ud = new UserDao();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//从网页上获取用户名和用户密码
String username = req.getParameter("username");
String password = req.getParameter("password");
//获取记住密码的勾选状态
String save = req.getParameter("save");
//调用userdao的登录方法,用一个User对象接收
User us = ud.login(username,password);
//判断us是否有值,有值,则用户存在切密码正确,进行登录操作,没值则进入登录失败页面
if(us != null){
//如果记住密码勾选,则进行记住密码操作
if("checkon".equals(save)){
//创建Cookie对象,将用户输入的用户名和密码存入Cookie
//实现记住密码功能
Cookie c1 = new Cookie("username",us.getUsername());
Cookie c2 = new Cookie("password",us.getPwd());
//给Cookie设置过期时间
c1.setMaxAge(60*60*24*7);
c2.setMaxAge(60*60*24*7);
//将Cookie响应到浏览器
resp.addCookie(c1);
resp.addCookie(c2);
}
//实现用户跟踪校验功能,没有登录没法进入其他页面
//创建session,将us对象绑定到session
HttpSession session = req.getSession();
session.setAttribute("user",us);
//登录之后转发到主页面
req.getRequestDispatcher("student").forward(req,resp);
}else {
//登录失败进入登录失败页面
resp.sendRedirect("login_fail.jsp");
}
}
}
2、LoginOut类
package com.offcn.login;
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 java.io.IOException;
@WebServlet("/logout")
public class LogOut extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.invalidate();
resp.sendRedirect("index.jsp");
}
}
3、Register类
package com.offcn.login;
import com.offcn.dao.UserDao;
import com.offcn.entity.User;
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 java.io.IOException;
//注册
@WebServlet("/register")
public class Register extends HttpServlet {
UserDao ud = new UserDao();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取信息
String username = req.getParameter("username");
String pwd = req.getParameter("pwd");
String name = req.getParameter("name");
String tel = req.getParameter("tel");
String bir = req.getParameter("bir");
//存入数据库
User u = new User(username,pwd,name,tel,DateUtil.dateformat(bir));
boolean b = ud.register(u);
if(b){
resp.sendRedirect("index.jsp");
}else {
resp.sendRedirect("register.jsp");
}
}
}
4、InsertServlet类
package com.offcn.login;
import com.offcn.dao.StudentDao;
import com.offcn.entity.Student;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
//插入学生信息操作
@MultipartConfig
@WebServlet("/insert")
public class InsertServlet extends HttpServlet {
//实例化StudentDao
StudentDao sd = new StudentDao();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取页面中输入的学生信息
String name = req.getParameter("name");
String age = req.getParameter("age");
String tel = req.getParameter("tel");
String bir = req.getParameter("bir");
String sex = req.getParameter("sex");
Part part = req.getPart("spic");
//获取图片信息的名字
String filename = part.getSubmittedFileName();
//给图片重新命名
filename = UUID.randomUUID()+filename;
//图片的保存路径
String path = "d:/pic";
//实例化Student,并将获取的学生信息传入
Student student = new Student(name,Integer.parseInt(age),tel,DateUtil.dateformat(bir),Integer.parseInt(sex),filename);
//调用插入学生信息方法,将信息传入数据库
boolean b = sd.insert(student);
if(b){
//如果插入成功,则创建文件夹存储图片,并跳转回主页面
File f = new File(path);
if(!f.exists()){
f.mkdir();
}
part.write(path+File.separator+filename);
resp.sendRedirect("student");
}
}
}
5、DeleteServlet类
package com.offcn.login;
import com.offcn.dao.StudentDao;
import javax.servlet.ServletContext;
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 java.io.IOException;
//删除操作的servlet
@WebServlet("/delete")
public class deleteServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取要删除学生的id
int id = Integer.parseInt(req.getParameter("id"));
//实例化StudentDao
StudentDao sd = new StudentDao();
//调用删除学生信息方法
boolean b = sd.delete(id);
//删除之后跳转回主页面
resp.sendRedirect("student");
}
}
6、StuServlet类
package com.offcn.login;
import com.offcn.dao.StudentDao;
import com.offcn.entity.Page;
import com.offcn.entity.Student;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@MultipartConfig
@WebServlet("/student")
public class StuServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String curPage = req.getParameter("curPage");
String name = req.getParameter("name");
String sex = req.getParameter("sex");
StudentDao sd = new StudentDao();
int rows = sd.LikeNum(name,sex);
Page p = new Page(rows,curPage);
List<Student> list = sd.StuLike(name,sex,p);
req.setAttribute("list",list);
req.setAttribute("p",p);
req.setAttribute("name",name);
req.setAttribute("sex",sex);
req.getRequestDispatcher("stuservlet.jsp").forward(req,resp);
}
}
7、UpdateServlet类
package com.offcn.login;
import com.offcn.dao.StudentDao;
import com.offcn.entity.Student;
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 java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/update")
public class UpdateServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
StudentDao sd = new StudentDao();
Student s1 = sd.stuSinSer(Integer.parseInt(id));
req.setAttribute("s1",s1);
req.getRequestDispatcher("/update.jsp").forward(req,resp);
}
}
8、Update2类
package com.offcn.login;
import com.offcn.dao.StudentDao;
import com.offcn.entity.Student;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;
@MultipartConfig
@WebServlet("/update2")
public class Update2 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
StudentDao sd = new StudentDao();
String id = req.getParameter("id");
String name = req.getParameter("name");
String age = req.getParameter("age");
String tel = req.getParameter("tel");
String bir = req.getParameter("bir");
String sex = req.getParameter("sex");
String spic = req.getParameter("spic");
Part part = req.getPart("newspic");
String path = "d:/pic";
String filename = part.getSubmittedFileName();
String pic = spic;
if(!"".equals(filename)){
filename= UUID.randomUUID()+filename;
pic = filename;
part.write(path+File.separator+pic);
File f = new File(path+File.separator+spic);
f.delete();
}
Student s2 = new Student(name,Integer.parseInt(age),tel,DateUtil.dateformat(bir),Integer.parseInt(sex),pic);
boolean b = sd.updateStu(s2,Integer.parseInt(id));
if(b){
resp.sendRedirect("student");
}
}
}
9、DateUtils类
package com.offcn.login;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//日期工具类
//做字符串转日期,日期转字符串的操作
public class DateUtil {
//将字符串转为日期类型
public static Date dateformat(String s){
SimpleDateFormat sdf = new SimpleDateFormat("YY-MM-dd");
try {
return sdf.parse(s);
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
//将日期类型转为字符串
public static String format(Date d){
SimpleDateFormat sdf = new SimpleDateFormat("YY-MM-dd");
try {
return sdf.format(d);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
}
这篇关于基于web的学生管理系统(二)java代码阶段的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!