创建项目,创建包,添加jar包
四个jsp页面
首页(index.jsp)
使用项目自带的index.jsp即可,提供一个跳转到所有学生列表页面的超链接
所有学生列表页(list.jsp)
添加学生页面(add.jsp)
修改学生信息页面(edit.jsp)
流程分析
代码实现
index.jsp页面
<h2>学生管理系统</h2>
<a href="${pageContext.request.contextPath}/findAllStudents">查询所有学生列表</a>
FindAllStudentsServlet.java
@WebServlet(name = "FindAllStudentsServlet",urlPatterns = "/findAllStudents")
public class FindAllStudentsServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response){
//0.设置响应体和请求体的编码
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
//Servlet干的四件事:参调存转
//1.获取参数(无)
//2.调用service,获取所有学生的信息
StudentService service = new StudentService();
List<Student> students = service.findAllStudents();
//3.把数据保存到域对象中
request.setAttribute("students",students);
//4.转发到另外一个jsp页面
request.getRequestDispatcher("/list.jsp").forward(request, response);
}
}
StudentService.java
public class StudentService {
/**
* 查询所有学生的方法
*/
public List<Student> findAllStudents(){
//调用dao层
StudentDao dao = new StudentDao();
List<Student> students = dao.findAllStudents();
//返回
return students;
}
}
StudentDao.java
public class StudentDao {
/**
* 查询所有学生的方法
*/
public List<Student> findAllStudents(){
//要从文件中真正查询数据
List<Student> students = DataUtil.readAll();
//返回
return students;
}
}
DataUtil.java
public class DataUtil {
//从文件中读取所有学员信息
public static List<Student> readAll(){
//保存所有学生对象信息
List<Student> stuList = new ArrayList<>();
try {
//得到文件真实路径
String realpath = DataUtil.class.getClassLoader().getResource("student.txt").getPath();
//创建字符输入流
Reader isr = new InputStreamReader(new FileInputStream(realpath), "UTF-8");
//创建字符缓冲流
BufferedReader br = new BufferedReader(isr); //装饰者模式
//一次读一行
String row = null;
while ((row = br.readLine()) != null) {//row = "1,张三,m,20"
String[] arr = row.split(","); //[1,张三,m,20]
Student stu = new Student();
stu.setId(arr[0]);
stu.setName(arr[1]);
stu.setSex(arr[2]);
stu.setAge(arr[3]);
//将Student对象添加到集合
stuList.add(stu);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return stuList;
}
}
list.jsp 展示所有学生信息页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
<script>
</script>
</head>
<body>
<a href="">新增</a>
<table border="1" >
<tr>
<th>学号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>操作</th>
</tr>
<%--使用jstl的foreach标签遍历集合--%>
<c:forEach items="${students}" var="s">
<tr>
<td>${s.id}</td>
<td>${s.name}</td>
<td>${s.sex}</td>
<td>${s.age}</td>
<td>
<a href="">修改</a>|
<a href="">删除</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
流程分析
代码实现
list.jsp页面
<a href="${pageContext.request.contextPath}/add.jsp">新增</a> ${isOK}
add.jsp页面
<body>
<form action="${pageContext.request.contextPath}/addStudent" method="post">
学号:<input type="text" name="id"/><br/>
姓名:<input type="text" name="name"/><br/>
性别:<input type="radio" name="sex" value="男" checked/>男
<input type="radio" name="sex" value="女"/>女<br/>
年龄:<input type="text" name="age"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
AddStudentServlet.java
@WebServlet(name = "AllStudentServlet",urlPatterns = "/addStudent")
public class AllStudentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response){
//0.设置响应体和请求体的编码
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
//Servlet的四大功能:参调存转
//1.获取请求参数
Map<String, String[]> map = request.getParameterMap();
//封装到学生对象
Student s = new Student();
//使用BeanUtils
try {
BeanUtils.populate(s,map);
} catch (Exception e) {
e.printStackTrace();
}
//2.调用service
StudentService service = new StudentService();
boolean b = service.addStudent(s);
//3.可以把成功的信息保存到域对象(也可以不保存)
request.setAttribute("isOK", b?"添加成功":"添加失败");
//4.转发到findAllServlet
request.getRequestDispatcher("/findAllStudents").forward(request, response);
}
}
StudentService.java
/**
* 添加学生的方法
*/
public boolean addStudent(Student s){
//调用Dao
StudentDao dao = new StudentDao();
boolean b = dao.addStudent(s);
return b;
}
StudentDao.java
/*
* 添加学生的方法
*/
public boolean addStudent(Student s) {
//把新增的学生信息添加到文件中
//1.先获取所有学生(没有添加之前的)
List<Student> students = DataUtil.readAll();
//2.把新的学生添加到集合中
students.add(s);
//3.把所有学生(添加之后)再写去到文件中
DataUtil.writeAll(students);
//4.返回成功
return true;
}
DataUtil.java
//向文件中写入所有学员信息--覆盖写
public static void writeAll(List<Student> stuList) {
try {
//得到文件真实路径
String realpath = DataUtil.class.getClassLoader().getResource("student.txt").getPath();
//创建字符输出流
Writer osw=new OutputStreamWriter(new FileOutputStream(realpath),"UTF-8");
//创建字符缓冲流
BufferedWriter out = new BufferedWriter(osw);
//循环向文件中写入文本
for (Student stu : stuList) {
out.write(stu.getId() + "," + stu.getName() + "," + stu.getSex() + "," + stu.getAge());
out.newLine();//创建新的一行
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
为了解决所有资源的中文乱码问题,我们建议添加一个全站中文乱码的过滤器
@WebFilter(filterName = "EncodingFilter", urlPatterns = "/*")
public class EncodingFilter implements Filter {
/**
* 销毁方法:项目被卸载或者服务器正常关闭时销毁
*/
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//1.将ServletRequest和ServletResponse转为HttpServletRequest和HttpServletResponse
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//2.请求体和响应体乱码
if (request.getMethod().equalsIgnoreCase("POST")) {
request.setCharacterEncoding("UTF-8");
}
response.setContentType("text/html;charset=UTF-8");
//3.放行,访问目标资源
chain.doFilter(req, resp);
}
/**
* 初始化方法:项目部署到服务器时初始化
*/
public void init(FilterConfig config) throws ServletException {
}
}
流程分析
list.jsp的修改按钮
<tr>
<td>${s.id}</td>
<td>${s.name}</td>
<td>${s.sex}</td>
<td>${s.age}</td>
<td>
<a href="${pageContext.request.contextPath}/findStudent?id=${s.id}">修改</a>|
<a href="${pageContext.request.contextPath}/deleteStudent?id=${s.id}">删除</a>
</td>
</tr>
FindStudentServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response){
//Servlet的四个功能:参调存转
//1.获取请求中的参数
String id = request.getParameter("id");
//2.调用Service
StudentService service = new StudentService();
Student s = service.findStudent(id);
//3.保存到域对象中
request.setAttribute("student",s);
//4.转发到edit.jsp
request.getRequestDispatcher("/edit.jsp").forward(request, response);
}
StudentService.java
/**
* 根据ID查询学生
* @param id
* @return
*/
public Student findStudent(String id) {
//调用Dao
StudentDao dao = new StudentDao();
Student s = dao.findStudent(id);
//返回
return s;
}
StudentDao.java
/**
* 根据id查询学生
*/
public Student findStudent(String id) {
//从文件中查询指定id的学生信息
//1.获取所有学生
List<Student> students = DataUtil.readAll();
//2.查询指定id的学生
for (Student student : students) {
//3.判断
if (student.getId().equals(id)) {
return student;
}
}
//3.如果2中的循环没有找到
return null;
}
edit.jsp进行数据回显
<form action="" method="post">
学号:<input type="text" name="id" value="${student.id}" disabled/><br/>
姓名:<input type="text" name="name" value="${student.name}"/><br/>
性别:<input type="radio" name="gender" value="男" ${student.sex == "男" ? "checked":""}/>男
<input type="radio" name="gender" value="女" ${student.sex == "女" ? "checked":""}/>女<br/>
年龄:<input type="text" name="age" value="${student.age}"/><br/>
<input type="submit" value="提交"/>
</form>
edit.jsp修改数据页面
<form action="${pageContext.request.contextPath}/updateStudent" method="post">
学号:<input type="hidden" name="id" value="${student.id}"/><br/>
姓名:<input type="text" name="name" value="${student.name}"/><br/>
性别:<input type="radio" name="sex" value="男" ${student.sex == "男" ? "checked":""}/>男
<input type="radio" name="sex" value="女" ${student.sex == "女" ? "checked":""}/>女<br/>
年龄:<input type="text" name="age" value="${student.age}"/><br/>
<input type="submit" value="提交"/>
</form>
UpdateStudentServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
//参调存转
//1.获取参数
Map<String, String[]> map = request.getParameterMap();
Student s = new Student();
try {
BeanUtils.populate(s,map);
} catch (Exception e) {
e.printStackTrace();
}
//2.调用service
StudentService service = new StudentService();
boolean b = service.updateStudent(s);
//3.结果保存到域对象
request.setAttribute("isOK",b?"修改成功":"修改失败");
//4.转发
request.getRequestDispatcher("/findAllStudents").forward(request, response);
}
StudentService.java
/**
* 修改学生
*/
public boolean updateStudent(Student s) {
//调用Dao
StudentDao dao = new StudentDao();
boolean b = dao.updateStudent(s);
//返回
return b;
}
StudentDao.java
/**
* 修改学生
*/
public boolean updateStudent(Student s) {
//把文件中的指定id的学生信息改为最新信息
//1.获取所有学生(未修改之前)
List<Student> students = DataUtil.readAll();
//2.修改
for (Student student : students) {
//判断
if (student.getId().equals(s.getId())) {
//修改
student.setName(s.getName());
student.setAge(s.getAge());
student.setSex(s.getSex());
}
}
//3.把所有学生(修改之后)再写去到文件中
DataUtil.writeAll(students);
//4.返回结果
return true;
}
流程分析
代码实现
list.jsp
<tr>
<td>${s.id}</td>
<td>${s.name}</td>
<td>${s.sex}</td>
<td>${s.age}</td>
<td>
<a href="">修改</a>|
<a href="${pageContext.request.contextPath}/deleteStudent?id=${s.id}">删除</a>
</td>
</tr>
DeleteStudentServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response){
//0.设置响应体和请求体的编码
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
//Servlet四大功能:参调存转
//1.获取请求参数
String id = request.getParameter("id");
//2.调用Service
StudentService service = new StudentService();
boolean b = service.deleteStudent(id);
//3.保存域对象
request.setAttribute("isOK",b?"删除功能":"删除失败");
//4.请求转发
request.getRequestDispatcher("/findAllStudents").forward(request, response);
}
StudentService.java
/**
* 根据ID删除学生
*/
public boolean deleteStudent(String id) {
//调用Dao
StudentDao dao = new StudentDao();
boolean b = dao.delteStudent(id);
return b;
}
StudentDao.java
/**
* 删除学生的方法
* @param id
* @return
*/
public boolean deleteStudent(String id) {
//把文件中指定id的学生删除
//1.先获取所有学生(没有删除之前的)
List<Student> students = DataUtil.readAll();
//2.根据id 从集合students中把学生删除
for (Student student : students) {
//判断
if (student.getId().equals(id)) {
students.remove(student);
break;
}
}
//3.把所有学生(删除之后)再写去到文件中
DataUtil.writeAll(students);
//4.返回成功
return true;
}
用户通过客户端/浏览器把本地的文件,通过网络上传到服务器,并保存到服务器本地磁盘中
使用浏览器实现文件上传的三要素:
a.请求方式必须是post
b.上传文件的file标签,必须提供一个name属性
c.form标签的enctype属性值必须为multipart/form-data(表示需要使用文件上传功能)
如果是普通表单(没有文件需要上传的),
其属性值为enctype="application/x-www-form-urlencoded"(默认的)
示例:
<form action="..." method="post" enctype="multipart/form-data">
<input type="file" name=".."/>
</form>
第一种:
借助Apache提供的一个 commons-fileupload.jar 包实现[今天讲解]【最最最恶心】
第二种:
使用Servlet3.0提供的 注解方式上传文件,很简单
第三种:
SpringMVC实现的文件上传【最最最变态的简单】
首先你要把Apache用于文件上传相关jar包导入到项目中:
commons-fileupload-1.3.1.jar
commons-io-2.6.jar
/**
* 接收文件上传表单的Servlet
*/
@WebServlet(name = "FileUploadServlet",urlPatterns = "/upload")
public class FileUploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// doPost(req,resp);//StackOverflowError
doGet(req,resp);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//0.设置响应体和请求体的编码
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
//使用Apache提供的commons-file-upload.jar解析普通项和文件项
//1.创建一个 磁盘文件项的工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory();
//2.创建 核心的解析文件上传数据的对象
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
//3.使用核心类的对象,解析请求中的数据
try {
List<FileItem> fileItems = servletFileUpload.parseRequest(request);
//4.遍历集合
for (FileItem fileItem : fileItems) {
//5.判断是普通项还是文件项
if (fileItem.isFormField()) {
//6.代表的是普通项
String fieldName = fileItem.getFieldName();
String fieldValue = fileItem.getString();
System.out.println(fieldName + "=" + fieldValue);
}else{
//7.代表的是文件项
//a.获取文件的名字
String fileName = fileItem.getName();
//b.获取文件的输入流
InputStream in = fileItem.getInputStream();
//8.创建和fileName一样同名文件
//注意:如果uploads文件夹是空的,那么编译后部署到Tomcat时,会删除该文件夹
//解决方案:
//a.在uploads文件夹下随便放一个文件(保证其不空,不会被删除)
//b.使用File对象的mkdir方法创建该文件夹即可
String realPath = getServletContext().getRealPath("/WEB-INF/uploads");
//判断该文件夹是否存在
File file = new File(realPath);
if (!file.exists()) {
file.mkdir();
}
//9.创建文件的输出流
FileOutputStream fos = new FileOutputStream(realPath+"/"+fileName);
//10.复制
//一个一个字节复制,一个一个字节数组复制,要么使用IOUtils复制
IOUtils.copy(in, fos);
//11.释放资源
fos.close();
in.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}