以前挖的坑,早晚要往里掉。基础太薄弱,要恶补。在此程序前,我还对Servlet没有一个清晰的概念;一周时间写好此程序之后,对Servlet的理解清晰许多。
这周一直在恶补Spring,今天正好完成了Spring的每日任务,于是抽空来写一下博客,希望这篇随笔可以帮到各位新手们。
此文章省略了bean,这个很简单,有需要的可以自行创建。
一、 简单介绍
这是一个非常简单的一个程序,功能并不完整,只实现了学生方面的登录和选课操作,但是代码干净、整洁。
主要模块:1. 登录方面写入了MD5密码加密模块;
2. 选课方面查询、选中、取消选中操作;
3. 拦截器。
二、整体预览
1. Web项目预览
其中applicationContext.xml是Druid配置文件。虽然Druid是配好的,但是写着写着莫名用得JDBC。
2. lib文件夹->jar包
3. pages文件夹->jsp页面
4. src文件夹->.java
三、 JSP代码
1. 登录——login.jsp
学生登录
2. 学生选课主页面——studentIndex.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
学生选课
学生选课界面
课程名称
剩余量
总数量
任课教师
课程地点
课程时间
课程时长
操作
${courseList.courseName }
${courseList.courseRemain }
${courseList.courseTotal }
${courseList.courseTeacher }
${courseList.coursePlace }
${courseList.courseTime }
${courseList.courseTimelength }
3. 学生选中的课程信息显示页面——studentInfo.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
学生课程
课程名称
任课教师
课程地点
课程时间
课程时长
操作
${studentCourseList.courseName }
${studentCourseList.courseTeacher }
${studentCourseList.coursePlace }
${studentCourseList.courseTime }
${studentCourseList.courseTimelength }
四、 Servlet代码
1. 登录功能的Servlet——LoginServlet.java
帐号见数据库(下文有显示)
密码为123
package com.studentselect.servlet;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import com.studentselect.util.MD5Util;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
protected void process(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "zhao1110";
Connection conn = (Connection) DriverManager.getConnection(url, username, password);
Statement statement = (Statement) conn.createStatement();
//根据学号查询
//获取学号
req.setCharacterEncoding("UTF-8");
String keyNum = req.getParameter("numText");
//String keyNum = new String(req.getParameter("numText").getBytes("iso-8859-1"), "utf-8");
if(keyNum == null) {
keyNum = "";
}
String sql1 = "select * from student where student_num='" + keyNum + "'";
ResultSet resultSet = statement.executeQuery(sql1);
//获取密码
req.setCharacterEncoding("UTF-8");
String keyPassword = req.getParameter("passowrdText");
//String keyPassword = new String(req.getParameter("passowrdText").getBytes("iso-8859-1"), "utf-8");
if(keyPassword == null) {
keyPassword = "";
}
//密码加密
MD5Util md5 = new MD5Util();
String newString = "";
try {
newString = md5.EncoderByMd5(keyPassword);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//比对密码
String passwordString = "";
while (resultSet.next()) {
passwordString = resultSet.getString("student_password");
}
if (passwordString.equals(newString)) {
//将学号存入session
HttpSession session = req.getSession();
session.setAttribute("numSession", keyNum);
resp.sendRedirect("/StudentSelect/FindServlet");
} else {
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write("");
resp.setHeader("refresh", "0; url=/StudentSelect");
}
resultSet.close();
statement.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. 主页显示信息的Servlet——FindServlet.java
package com.studentselect.servlet;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import com.studentselect.bean.Course;
public class FindServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
public void process(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
// 加载数据库驱动,注册到驱动管理器
Class.forName("com.mysql.jdbc.Driver");
// 数据库连接字符串
String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8";
// 数据库用户名
String username = "root";
// 数据库密码
String password = "zhao1110";
// 创建Connection连接
Connection conn = (Connection) DriverManager.getConnection(url, username, password);
// SQL语句
String sql = "select * from course";
// 获取Statement
Statement statement = (Statement) conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
List courseList = new ArrayList();
while (resultSet.next()) {
Course course = new Course();
course.setCourseId(resultSet.getInt("course_Id"));
course.setCourseName(resultSet.getString("course_Name"));
course.setCourseRemain(resultSet.getInt("course_Remain"));
course.setCourseTotal(resultSet.getInt("course_Total"));
course.setCourseTeacher(resultSet.getString("course_Teacher"));
course.setCoursePlace(resultSet.getString("course_Place"));
course.setCourseTime(resultSet.getString("course_Time"));
course.setCourseTimelength(resultSet.getString("course_Timelength"));
courseList.add(course);
}
req.setAttribute("courseList", courseList);
//后台显示数据
/*JSONArray jsonArray = JSONArray.fromObject(courseList);
System.out.println(jsonArray.toString());*/
resultSet.close();
statement.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
req.getRequestDispatcher("pages/studentIndex.jsp").forward(req, resp);
}
}
3. 查询功能的Servlet——SearchServlet.java
package com.studentselect.servlet;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import com.studentselect.bean.Course;
public class SearchServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
protected void process(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String keyString = req.getParameter("search");
if(keyString == null) {
keyString = "";
}
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "zhao1110";
Connection conn = (Connection) DriverManager.getConnection(url, username, password);
Statement statement = (Statement) conn.createStatement();
String sql = "select * from course where course_name like '%" + keyString + "%' or course_remain like '%" + keyString + "%' "
+ "or course_total like '%" + keyString + "%' or course_teacher like '%" + keyString + "%'"
+ " or course_place like '%" + keyString + "%' or course_time like '%" + keyString + "%'"
+ " or course_timelength like '%" + keyString + "%'";
ResultSet resultSet = statement.executeQuery(sql);
List courseList = new ArrayList();
while (resultSet.next()) {
Course course = new Course();
course.setCourseId(resultSet.getInt("course_Id"));
course.setCourseName(resultSet.getString("course_Name"));
course.setCourseRemain(resultSet.getInt("course_Remain"));
course.setCourseTotal(resultSet.getInt("course_Total"));
course.setCourseTeacher(resultSet.getString("course_Teacher"));
course.setCoursePlace(resultSet.getString("course_Place"));
course.setCourseTime(resultSet.getString("course_Time"));
course.setCourseTimelength(resultSet.getString("course_Timelength"));
courseList.add(course);
}
req.setAttribute("courseList", courseList);
//后台显示数据
/*JSONArray jsonArray = JSONArray.fromObject(courseList);
System.out.println(jsonArray.toString());*/
resultSet.close();
statement.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
req.getRequestDispatcher("pages/studentIndex.jsp?search='"+keyString+"'").forward(req, resp);
}
}
4. 选中课程时触发的Servlet——RemainAddServlet.java
package com.studentselect.servlet;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class RemainAddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
protected void process(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "zhao1110";
Connection conn = (Connection) DriverManager.getConnection(url, username, password);
Statement statement = (Statement) conn.createStatement();
//String keyString = new String(req.getParameter("id").getBytes("iso-8859-1"), "utf-8");
req.setCharacterEncoding("UTF-8");
String keyString = req.getParameter("id");
if(keyString == null) {
keyString = "";
resp.sendRedirect("FindServlet");
return;
}
//添加课程
String numSession = (String) req.getSession().getAttribute("numSession");
String sql1 = "select student_selected_course from student where student_num = '" + numSession + "'";
ResultSet resultSet = statement.executeQuery(sql1);
String courseString = "";
while (resultSet.next()) {
courseString = resultSet.getString("student_selected_course");
}
//检查课程选择是否重复
String[] courseStrings = courseString.split(",");
for (int i=0; i
5. 取消选中的课程时触发的Servlet——CancelServlet.java
package com.studentselect.servlet;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class CancelServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
protected void process(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "zhao1110";
Connection conn = (Connection) DriverManager.getConnection(url, username, password);
Statement statement = (Statement) conn.createStatement();
//String keyString = new String(req.getParameter("id").getBytes("iso-8859-1"), "utf-8");
req.setCharacterEncoding("UTF-8");
String keyString = req.getParameter("id");
if(keyString == null) {
keyString = "";
resp.sendRedirect("FindServlet");
return;
}
String numSession = (String) req.getSession().getAttribute("numSession");
String sql1 = "select student_selected_course from student where student_num = '" + numSession + "'";
ResultSet resultSet = statement.executeQuery(sql1);
//取出课程字符串
String courseString = "";
while (resultSet.next()) {
courseString = resultSet.getString("student_selected_course");
}
//找到课程id
Integer spot = courseString.indexOf(keyString);
courseString = courseString.substring(0, spot) + courseString.substring(spot+2);
//更新课程数据
String sql2 = "update student set student_selected_course='" + courseString + "' where student_num = '" + numSession + "'";
statement.executeUpdate(sql2);
//课程余量+1
String sql3 = "update course set course_remain=course_remain+1 where course_id = '"+ keyString + "'";
statement.executeUpdate(sql3);
statement.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
resp.getWriter().print("{\"data\":\"返回json数据!\"}");
}
}
6. 学生选中的课程信息显示Servlet——StudentInfoServlet.java
package com.studentselect.servlet;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import com.studentselect.bean.Course;
import com.studentselect.bean.Student;
public class StudentInfoServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
process(req, resp);
}
protected void process(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "zhao1110";
Connection conn = (Connection) DriverManager.getConnection(url, username, password);
Statement statement = (Statement) conn.createStatement();
String numSession = (String) req.getSession().getAttribute("numSession");
String sql1 = "select * from student where student_num = '" + numSession + "'";
ResultSet resultSet = statement.executeQuery(sql1);
//判断参数是否为空
/*req.setCharacterEncoding("UTF-8");
String keyString = req.getParameter("id");
if(keyString == null) {
keyString = "";
resp.sendRedirect("FindServlet");
return;
}*/
List courseStudentList = new ArrayList();
while (resultSet.next()) {
Student student = new Student();
student.setStudentSelectedCourse(resultSet.getString("student_selected_course"));
courseStudentList.add(student);
}
String courseStudentString = courseStudentList.get(0).getStudentSelectedCourse();
String[] array = courseStudentString.split(",");
List studentCourseList = new ArrayList();
for (String s:array) {
String sql2 = "select * from course where course_id = '" + s + "'";
resultSet = statement.executeQuery(sql2);
while (resultSet.next()) {
Course course = new Course();
course.setCourseId(resultSet.getInt("course_Id"));
course.setCourseName(resultSet.getString("course_Name"));
course.setCourseTeacher(resultSet.getString("course_Teacher"));
course.setCoursePlace(resultSet.getString("course_Place"));
course.setCourseTime(resultSet.getString("course_Time"));
course.setCourseTimelength(resultSet.getString("course_Timelength"));
studentCourseList.add(course);
}
}
req.setAttribute("studentCourseList", studentCourseList);
//后台显示数据
/*JSONArray jsonArray2 = JSONArray.fromObject(studentCourseList);
System.out.println(jsonArray2.toString());*/
//返回json数据
/*PrintWriter out = resp.getWriter();
out.print(jsonArray2.toString());*/
resultSet.close();
statement.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
resp.setCharacterEncoding("UTF-8");
req.getRequestDispatcher("pages/studentInfo.jsp").forward(req, resp);
}
}
7. MD5密码加密——MD5Util.java
package com.studentselect.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.yangcheboshi.util.weibo.http.BASE64Encoder;
public class MD5Util {
/**利用MD5进行加密*/
public String EncoderByMd5(String string)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
//确定计算方法
MessageDigest md5 = MessageDigest.getInstance("MD5");
BASE64Encoder base64en = new BASE64Encoder();
//加密后的字符串
@SuppressWarnings("static-access")
String newString = base64en.encode(md5.digest(string.getBytes("utf-8")));
return newString;
}
//判断用户密码是否正确
public boolean checkpassword(String newpassword,String initialpassword)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
if(EncoderByMd5(newpassword).equals(initialpassword))
return true;
else
return false;
}
}
五、 filter拦截器代码
1. 登录拦截——LoginFilter.java
package com.studentselect.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class LoginFilter implements Filter{
@Override
public void init(FilterConfig arg0) throws ServletException {
System.out.println("------login过滤器初始化------");
}
@Override
public void destroy() {
System.out.println("------login过滤器销毁------");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//对request和response进行一些预处理
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
HttpServletRequest req = (HttpServletRequest)request;
Object numSession = req.getSession().getAttribute("numSession");
String url = req.getRequestURI();
if (numSession != null || (url.endsWith("pages/login.jsp") || url.endsWith("LoginServlet"))) {
chain.doFilter(request, response); //让目标资源执行,放行
return;
} else {
req.getRequestDispatcher("/").forward(request, response);
}
}
}
2. JSP页面拦截——JSPFilter.java
package com.studentselect.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class JSPFilter implements Filter {
@Override
public void init(FilterConfig arg0) throws ServletException {
System.out.println("------.jsp过滤器初始化------");
}
@Override
public void destroy() {
System.out.println("------.jsp过滤器销毁------");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//对request和response进行一些预处理
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
HttpServletRequest req = (HttpServletRequest)request;
String url = req.getRequestURI();
if (!(url.endsWith(".jsp"))) {
chain.doFilter(request, response); //让目标资源执行,放行
return;
} else {
req.getRequestDispatcher("/").forward(request, response);
}
}
}
六、 web.xml配置
StudentSelect
pages/login.jsp
pages/default.jsp
LoginFilter
com.studentselect.filter.LoginFilter
LoginFilter
/*
JSPFilter
com.studentselect.filter.JSPFilter
JSPFilter
/*
FindServlet
com.studentselect.servlet.FindServlet
FindServlet
/FindServlet
StudentInfoServlet
com.studentselect.servlet.StudentInfoServlet
StudentInfoServlet
/StudentInfoServlet
SearchServlet
com.studentselect.servlet.SearchServlet
SearchServlet
/SearchServlet
RemainAddServlet
com.studentselect.servlet.RemainAddServlet
RemainAddServlet
/RemainAddServlet
CancelServlet
com.studentselect.servlet.CancelServlet
CancelServlet
/CancelServlet
LoginServlet
com.studentselect.servlet.LoginServlet
LoginServlet
/LoginServlet
DruidWebStatFilter
com.alibaba.druid.support.http.WebStatFilter
exclusions
*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
DruidWebStatFilter
/*
DruidStatView
com.alibaba.druid.support.http.StatViewServlet
resetEnable
true
loginUsername
overfly
loginPassword
zhao1110
DruidStatView
/druid/*
七、 表结构
八、 程序运行图
九、简单说说
1. filter拦截器我是用来拦截未登录就访问内容和地址栏URL直接访问Servlet,我将用户的登录信息存在Session中,用来判断用户是否已经登录。
2. 密码加密是用户将密码输入提交后,MD5Util对密码进行加密操作,转换成一系列字符编码,然后用转换后的字符编码与数据库进行比对。
虽然MD5是不可逆的,但是我认为依旧不安全,但是能在一定程度上简单防止它人盗取数据库获取用户信息这种黑客行为。
——2018-03-15