在线oj项目
文章目录
项目介绍
该项目基于java,servlet,JDBC,ajax技术实现的,该项目实现了登录和注册功能,给用户更好的体验,此外还新增管理员用户,其比普通用户多了几个功能:新增题目,删除题目,删除用户,添加用户,查看题目这些功能,这些功能能让用户体验更加完好,用户提交代码后会给用户提示代码通过情况,此外在运行用户代码前进行安全性检测,这特别适合将目前所有学的知识给运用一下,让自己更好熟练相关技术。
编译模块设计
创建Question类
package compile;publicclassQuestion{private String code;public String getCode(){return code;}publicvoidsetCode(String code){this.code = code;}}
创建Answer类
package compile;//返回前端以该类为标准publicclassAnswer{privateint error;private String reason;private String stdout;private String stderr;publicintgetError(){return error;}publicvoidsetError(int error){this.error = error;}public String getReason(){return reason;}publicvoidsetReason(String reason){this.reason = reason;}public String getStdout(){return stdout;}publicvoidsetStdout(String stdout){this.stdout = stdout;}public String getStderr(){return stderr;}publicvoidsetStderr(String stderr){this.stderr = stderr;}@Overridepublic String toString(){return"Answer{"+"error="+ error +", reason='"+ reason +'\''+", stdout='"+ stdout +'\''+", stderr='"+ stderr +'\''+'}';}}
创建FileUtil类
package compile;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;publicclassFileUtil{//读取文件内容publicstatic String readFile(String filePath){
StringBuffer buffer=newStringBuffer();try(FileReader fileReader=newFileReader(filePath)){while(true){int ch=fileReader.read();if(ch==-1){break;}
buffer.append((char)ch);}
fileReader.close();}catch(IOException e){
e.printStackTrace();}return buffer.toString();}//向指定文件写内容publicstaticvoidwriteFile(String filePath,String content){try(FileWriter fileWriter=newFileWriter(filePath)){
fileWriter.write(content);}catch(IOException e){
e.printStackTrace();}}publicstaticvoidmain(String[] args){
FileUtil.writeFile("d:/test.txt","hello world");
String content=FileUtil.readFile("d:/test.txt");
System.out.println(content);}}
创建CommandUtil类
package compile;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;publicclassCommandUtil{publicstaticintrun(String cmd,String stdoutFile, String stderrFile){try{//创建进程
Process process=Runtime.getRuntime().exec(cmd);if(stdoutFile!=null){
InputStream stdoutFrom=process.getInputStream();
FileOutputStream stdoutTo=newFileOutputStream(stdoutFile);while(true){int ch=stdoutFrom.read();if(ch==-1){break;}//讲内容输入进文件stdoutFile
stdoutTo.write(ch);}
stdoutFrom.close();
stdoutTo.close();}if(stderrFile!=null){
InputStream stderrFrom=process.getErrorStream();
FileOutputStream stderrTo=newFileOutputStream(stderrFile);while(true){int ch=stderrFrom.read();if(ch==-1){break;}//讲内容输入进文件stderrFile
stderrTo.write(ch);}
stderrFrom.close();
stderrTo.close();}int exitCode=process.waitFor();}catch(IOException e){
e.printStackTrace();}catch(InterruptedException e){
e.printStackTrace();}return1;}publicstaticvoidmain(String[] args){
CommandUtil.run("javac","stdout.txt","stderr.txt");}}
创建Task类
package compile;import java.io.File;import java.util.ArrayList;import java.util.List;import java.util.UUID;publicclassTask{privatestatic String WORK_DIR=null;privatestatic String CLASS=null;privatestatic String CODE=null;privatestatic String COMPILE_ERROR=null;privatestatic String STDOUT=null;privatestatic String STDERR=null;publicTask(){//是每次文件夹名字不同
WORK_DIR="./tmp/"+ UUID.randomUUID().toString()+"/";
CODE=WORK_DIR+"Solution.java";
CLASS="Solution";
COMPILE_ERROR=WORK_DIR+"compileError.txt";
STDOUT=WORK_DIR+"stdout.txt";
STDERR=WORK_DIR+"stderr.txt";}public Answer compileAndRun(Question question){
Answer answer=newAnswer();
File workDir=newFile(WORK_DIR);if(!workDir.exists()){
workDir.mkdirs();}//如果用户提交的代码不安全则直接反馈给用户if(!checkCodeSafe(question.getCode())){
System.out.println("用户提交了不安全代码");
answer.setError(3);
answer.setReason("你提交的代码不安全!");return answer;}
FileUtil.writeFile(CODE,question.getCode());//编译该代码
String compileCmd=String.format("javac -encoding utf8 %s -d %s",CODE,WORK_DIR);
System.out.println("编译命令:"+compileCmd);
CommandUtil.run(compileCmd,null,COMPILE_ERROR);
String compileError= FileUtil.readFile(COMPILE_ERROR);
System.out.println(compileError);if(!compileError.equals("")){
System.out.println("编译出错");
answer.setError(1);
answer.setReason(compileError);return answer;}//运行该代码
String runCmd=String.format("java -classpath %s %s",WORK_DIR,CLASS);
System.out.println("运行命令:"+runCmd);
CommandUtil.run(runCmd,STDOUT,STDERR);
String runError= FileUtil.readFile(STDERR);if(!runError.equals("")){
System.out.println("运行出错");
answer.setError(2);
answer.setReason(runError);return answer;}
answer.setError(0);
answer.setStdout(FileUtil.readFile(STDOUT));return answer;}privatebooleancheckCodeSafe(String code){
List<String> blackList=newArrayList<>();
blackList.add("Runtime");
blackList.add("exec");
blackList.add("java.io");
blackList.add("java.net");for(String string:blackList){int pos =code.indexOf(string);if(pos>=0){returnfalse;}}returntrue;}publicstaticvoidmain(String[] args){
Task task=newTask();
Question question=newQuestion();
question.setCode("public class Solution {\n"+" public static void main(String[] args) {\n"+" System.out.println(\"sdfasdasd\");\n"+" }\n"+"}\n");
Answer answer=task.compileAndRun(question);
System.out.println(answer.toString());}}
此外为了用户提交恶意代码或者空代码交了两个CodeInValidException和ProblemNotFoundException类进行 抛出异常。
题目用户管理设设计
设计数据库和库
createdatabaseifnotexists oj_database;use oj_database;droptableifexists oj_table;createtable oj_table(
id intprimarykeyauto_increment,
title varchar(50),levelvarchar(50),
description varchar(4096),
templateCode varchar(4096),
testCode varchar(4096));droptableifexists oj_user;createtable oj_user(
id intprimarykeyauto_increment,
username varchar(50)unique,
password varchar(50)notnull,
isAdmin int);
关于oj_table表单:id是自增主键,title是题目标题,level是代表该题目的难易程度,description是题目描述,templateCode是代码模板,testCode是测试代码。
关于oj_user表单:id是自增主键,username是用户名账号,password是用户密码,isAdmin是判断该用户是否为管理员。
创建DBUtil类
该类是进行数据库连接操作,此外为了线程安全采用了单例模式、
package common;import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;import javax.sql.DataSource;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;publicclassDBUtil{privatestaticfinal String URL="jdbc:mysql://127.0.0.1:3306/oj_database?characterEncoding=utf8&useSSL=false";//数据库地址privatestaticfinal String USERNAME="root";//数据库账号privatestaticfinal String PASSWORD="123456wjh.";//数据库命名privatestatic DataSource dataSource=null;//单例模式privatestatic DataSource getDataSource(){if(dataSource==null){synchronized(DBUtil.class){if(dataSource==null){
MysqlDataSource mysqlDataSource=newMysqlDataSource();
mysqlDataSource.setURL(URL);
mysqlDataSource.setUser(USERNAME);
mysqlDataSource.setPassword(PASSWORD);
dataSource=mysqlDataSource;}}}return dataSource;}publicstatic Connection getConnection()throws SQLException {returngetDataSource().getConnection();}publicstaticvoidclose(Connection connection, PreparedStatement statement, ResultSet resultSet)throws SQLException {if(resultSet!=null){
resultSet.close();}if(statement!=null){
statement.close();}if(connection!=null){
connection.close();}}}
实现题目管理
创建Problem类
创建该类为了以后得到数据库中的数据返回
package dao;publicclassProblem{privateint id;private String level;private String description;private String title;private String templateCode;private String testCode;@Overridepublic String toString(){return"Problem{"+"id="+ id +", level='"+ level +'\''+", description='"+ description +'\''+", title='"+ title +'\''+", templateCode='"+ templateCode +'\''+", testCode='"+ testCode +'\''+'}';}publicintgetId(){return id;}publicvoidsetId(int id){this.id = id;}public String getLevel(){return level;}publicvoidsetLevel(String level){this.level = level;}public String getDescription(){return description;}publicvoidsetDescription(String description){this.description = description;}public String getTitle(){return title;}publicvoidsetTitle(String title){this.title = title;}public String getTemplateCode(){return templateCode;}publicvoidsetTemplateCode(String templateCode){this.templateCode = templateCode;}public String getTestCode(){return testCode;}publicvoidsetTestCode(String testCode){this.testCode = testCode;}}
创建ProblemDAO类
该类作用于题目的管理,与数据库进行交互
package dao;import common.DBUtil;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;publicclassProblemDAO{//插入新题目publicvoidinsert(Problem problem){}//删除题目publicvoiddelete(int id){}//返回题目的基本信息public List<Problem>selectAll(){}//获取指定问题的详细问题public Problem selectOne(int id){}}
insert()方法
//插入新题目publicvoidinsert(Problem problem){
Connection connection=null;
PreparedStatement statement=null;try{
connection= DBUtil.getConnection();//获取数据库连接
String sql="insert into oj_table values(null,?,?,?,?,?)";
statement=connection.prepareStatement(sql);
statement.setString(1,problem.getTitle());
statement.setString(2,problem.getLevel());
statement.setString(3,problem.getDescription());
statement.setString(4,problem.getTemplateCode());
statement.setString(5,problem.getTestCode());int ret=statement.executeUpdate();//执行sql语句if(ret==1){
System.out.println("插入成功!");}else{
System.out.println("题目新增失败!");}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,null);}catch(SQLException throwables){
throwables.printStackTrace();}}}
delete()方法
//删除题目publicvoiddelete(int id){
Connection connection=null;
PreparedStatement statement=null;try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="delete from oj_table where id=?";
statement=connection.prepareStatement(sql);
statement.setInt(1,id);int ret=statement.executeUpdate();//执行sql语句if(ret==1){
System.out.println("删除题目成功!");}else{
System.out.println("删除题目失败!");}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,null);}catch(SQLException throwables){
throwables.printStackTrace();}}}
selectAll()方法
//返回题目的基本信息public List<Problem>selectAll(){
Connection connection=null;
PreparedStatement statement=null;
ResultSet resultSet=null;
List<Problem> list=newArrayList<>();try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="select id,title,level from oj_table";
statement=connection.prepareStatement(sql);
resultSet=statement.executeQuery();//执行sql语句while(resultSet.next()){
Problem problem=newProblem();
problem.setId(resultSet.getInt("id"));
problem.setTitle(resultSet.getString("title"));
problem.setLevel(resultSet.getString("level"));
list.add(problem);}if(list!=null){return list;}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,resultSet);}catch(SQLException throwables){
throwables.printStackTrace();}}return null;}
selectOne()方法
//获取指定问题的详细问题public Problem selectOne(int id){
Connection connection=null;
PreparedStatement statement=null;
ResultSet resultSet=null;try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="select * from oj_table where id=?";
statement=connection.prepareStatement(sql);
statement.setInt(1,id);
resultSet=statement.executeQuery();//执行sql语句if(resultSet.next()){
Problem problem=newProblem();
problem.setId(resultSet.getInt("id"));
problem.setTitle(resultSet.getString("title"));
problem.setLevel(resultSet.getString("level"));
problem.setDescription(resultSet.getString("description"));
problem.setTemplateCode(resultSet.getString("templateCode"));
problem.setTestCode(resultSet.getString("testCode"));return problem;}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,resultSet);}catch(SQLException throwables){
throwables.printStackTrace();}}return null;}
ProblemDAO完整代码
package dao;import common.DBUtil;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;publicclassProblemDAO{//插入新题目publicvoidinsert(Problem problem){
Connection connection=null;
PreparedStatement statement=null;try{
connection= DBUtil.getConnection();//获取数据库连接
String sql="insert into oj_table values(null,?,?,?,?,?)";
statement=connection.prepareStatement(sql);
statement.setString(1,problem.getTitle());
statement.setString(2,problem.getLevel());
statement.setString(3,problem.getDescription());
statement.setString(4,problem.getTemplateCode());
statement.setString(5,problem.getTestCode());int ret=statement.executeUpdate();//执行sql语句if(ret==1){
System.out.println("插入成功!");}else{
System.out.println("题目新增失败!");}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,null);}catch(SQLException throwables){
throwables.printStackTrace();}}}//删除题目publicvoiddelete(int id){
Connection connection=null;
PreparedStatement statement=null;try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="delete from oj_table where id=?";
statement=connection.prepareStatement(sql);
statement.setInt(1,id);int ret=statement.executeUpdate();//执行sql语句if(ret==1){
System.out.println("删除题目成功!");}else{
System.out.println("删除题目失败!");}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,null);}catch(SQLException throwables){
throwables.printStackTrace();}}}//返回题目的基本信息public List<Problem>selectAll(){
Connection connection=null;
PreparedStatement statement=null;
ResultSet resultSet=null;
List<Problem> list=newArrayList<>();try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="select id,title,level from oj_table";
statement=connection.prepareStatement(sql);
resultSet=statement.executeQuery();//执行sql语句while(resultSet.next()){
Problem problem=newProblem();
problem.setId(resultSet.getInt("id"));
problem.setTitle(resultSet.getString("title"));
problem.setLevel(resultSet.getString("level"));
list.add(problem);}if(list!=null){return list;}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,resultSet);}catch(SQLException throwables){
throwables.printStackTrace();}}return null;}//获取指定问题的详细问题public Problem selectOne(int id){
Connection connection=null;
PreparedStatement statement=null;
ResultSet resultSet=null;try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="select * from oj_table where id=?";
statement=connection.prepareStatement(sql);
statement.setInt(1,id);
resultSet=statement.executeQuery();//执行sql语句if(resultSet.next()){
Problem problem=newProblem();
problem.setId(resultSet.getInt("id"));
problem.setTitle(resultSet.getString("title"));
problem.setLevel(resultSet.getString("level"));
problem.setDescription(resultSet.getString("description"));
problem.setTemplateCode(resultSet.getString("templateCode"));
problem.setTestCode(resultSet.getString("testCode"));return problem;}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,resultSet);}catch(SQLException throwables){
throwables.printStackTrace();}}return null;}}
实现用户管理
创建User类
创建User类以便于数据库进行交互
package dao;publicclassUser{privateint id;private String username;private String password;privateint isAdmin;publicintgetId(){return id;}@Overridepublic String toString(){return"User{"+"id="+ id +", username='"+ username +'\''+", password='"+ password +'\''+", isAdmin="+ isAdmin +'}';}publicvoidsetId(int id){this.id = id;}public String getUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}public String getPassword(){return password;}publicvoidsetPassword(String password){this.password = password;}publicintgetIsAdmin(){return isAdmin;}publicvoidsetIsAdmin(int isAdmin){this.isAdmin = isAdmin;}}
创建UserDAO类
创建UserDAO类作为用户管理器类, 负责和数据库交互.
package dao;import common.DBUtil;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;publicclassUserDao{//新增用户publicvoidinsert(User user){}//删除用户publicvoiddelete(int id){}//返回所有用户的信息public List<User>selectAll(){}//通过姓名返回用户信息public User selectOneByName(String username){}//通过id返回用户的信息public User selectOneById(int id){}}
insert()方法
//新增用户publicvoidinsert(User user){
Connection connection= null;
PreparedStatement statement=null;try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="insert into oj_user values(null,?,?,?)";
statement=connection.prepareStatement(sql);
statement.setString(1,user.getUsername());
statement.setString(2,user.getPassword());
statement.setInt(3,user.getIsAdmin());int ret =statement.executeUpdate();//执行sql语句if(ret==1){
System.out.println("插入成功!");}else{
System.out.println("插入失败!");}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,null);}catch(SQLException throwables){
throwables.printStackTrace();}}}
delete()方法
//删除用户publicvoiddelete(int id){
Connection connection= null;
PreparedStatement statement=null;try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="delete from oj_user where id=?";
statement=connection.prepareStatement(sql);
statement.setInt(1,id);int ret =statement.executeUpdate();//执行sql语句if(ret==1){
System.out.println("删除成功!");}else{
System.out.println("删除失败!");}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,null);}catch(SQLException throwables){
throwables.printStackTrace();}}}
selectAll()方法
//返回所有用户的信息public List<User>selectAll(){
Connection connection=null;
PreparedStatement statement=null;
ResultSet resultSet=null;
List<User> list=newArrayList<>();try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="select * from oj_user";
statement=connection.prepareStatement(sql);
resultSet=statement.executeQuery();//执行sql语句while(resultSet.next()){
User user=newUser();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setIsAdmin(resultSet.getInt("isAdmin"));
list.add(user);}if(list==null){return null;}else{return list;}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,resultSet);}catch(SQLException throwables){
throwables.printStackTrace();}}return null;}
selectOneByName()方法
//通过姓名返回用户信息public User selectOneByName(String username){
Connection connection=null;
PreparedStatement statement=null;
ResultSet resultSet=null;try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="select * from oj_user where username=?";
statement=connection.prepareStatement(sql);
statement.setString(1,username);
resultSet=statement.executeQuery();//执行sql语句if(resultSet.next()){
User user=newUser();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setIsAdmin(resultSet.getInt("isAdmin"));return user;}else{return null;}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,resultSet);}catch(SQLException throwables){
throwables.printStackTrace();}}return null;}
selectOneById()方法
//通过id返回用户的信息public User selectOneById(int id){
Connection connection=null;
PreparedStatement statement=null;
ResultSet resultSet=null;try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="select * from oj_user where id=?";
statement=connection.prepareStatement(sql);
statement.setInt(1,id);
resultSet=statement.executeQuery();//执行sql语句if(resultSet.next()){
User user=newUser();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setIsAdmin(resultSet.getInt("isAdmin"));return user;}else{return null;}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,resultSet);}catch(SQLException throwables){
throwables.printStackTrace();}}return null;}
UserDAO完整代码
package dao;import common.DBUtil;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;publicclassUserDao{//新增用户publicvoidinsert(User user){
Connection connection= null;
PreparedStatement statement=null;try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="insert into oj_user values(null,?,?,?)";
statement=connection.prepareStatement(sql);
statement.setString(1,user.getUsername());
statement.setString(2,user.getPassword());
statement.setInt(3,user.getIsAdmin());int ret =statement.executeUpdate();//执行sql语句if(ret==1){
System.out.println("插入成功!");}else{
System.out.println("插入失败!");}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,null);}catch(SQLException throwables){
throwables.printStackTrace();}}}//删除用户publicvoiddelete(int id){
Connection connection= null;
PreparedStatement statement=null;try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="delete from oj_user where id=?";
statement=connection.prepareStatement(sql);
statement.setInt(1,id);int ret =statement.executeUpdate();//执行sql语句if(ret==1){
System.out.println("删除成功!");}else{
System.out.println("删除失败!");}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,null);}catch(SQLException throwables){
throwables.printStackTrace();}}}//返回所有用户的信息public List<User>selectAll(){
Connection connection=null;
PreparedStatement statement=null;
ResultSet resultSet=null;
List<User> list=newArrayList<>();try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="select * from oj_user";
statement=connection.prepareStatement(sql);
resultSet=statement.executeQuery();//执行sql语句while(resultSet.next()){
User user=newUser();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setIsAdmin(resultSet.getInt("isAdmin"));
list.add(user);}if(list==null){return null;}else{return list;}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,resultSet);}catch(SQLException throwables){
throwables.printStackTrace();}}return null;}//通过姓名返回用户信息public User selectOneByName(String username){
Connection connection=null;
PreparedStatement statement=null;
ResultSet resultSet=null;try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="select * from oj_user where username=?";
statement=connection.prepareStatement(sql);
statement.setString(1,username);
resultSet=statement.executeQuery();//执行sql语句if(resultSet.next()){
User user=newUser();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setIsAdmin(resultSet.getInt("isAdmin"));return user;}else{return null;}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,resultSet);}catch(SQLException throwables){
throwables.printStackTrace();}}return null;}//通过id返回用户的信息public User selectOneById(int id){
Connection connection=null;
PreparedStatement statement=null;
ResultSet resultSet=null;try{
connection=DBUtil.getConnection();//获取数据库连接
String sql="select * from oj_user where id=?";
statement=connection.prepareStatement(sql);
statement.setInt(1,id);
resultSet=statement.executeQuery();//执行sql语句if(resultSet.next()){
User user=newUser();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setIsAdmin(resultSet.getInt("isAdmin"));return user;}else{return null;}}catch(SQLException throwables){
throwables.printStackTrace();}finally{try{
DBUtil.close(connection,statement,resultSet);}catch(SQLException throwables){
throwables.printStackTrace();}}return null;}}
服务器API
实现Util类
package common;import dao.User;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;publicclassUtil{//判断用户是否登录publicstatic User checkUser(HttpServletRequest req){
HttpSession session=req.getSession(false);if(session==null){return null;}
User user=(User) session.getAttribute("user");if(user==null){return null;}return user;}}
实现addProblemServlet
package api;import com.fasterxml.jackson.databind.ObjectMapper;import dao.Problem;import dao.ProblemDAO;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.InputStream;import java.io.UnsupportedEncodingException;@WebServlet("/addProblem")publicclassaddProblemServletextendsHttpServlet{private ObjectMapper objectMapper=newObjectMapper();//编译响应staticclassisCorrect{publicint correct;}@OverrideprotectedvoiddoPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
req.setCharacterEncoding("utf8");
resp.setContentType("application/json; charset=utf8");
String body=readBody(req);
isCorrect correct=newisCorrect();//body为空则返回if(body==null){
resp.setContentType("text/html; charset=utf8");
String html="<h3>提交的题目有问题,无法新加成功!</h3>";
resp.getWriter().write(html);return;}
Problem problem=objectMapper.readValue(body,Problem.class);
ProblemDAO problemDAO=newProblemDAO();
problemDAO.insert(problem);
correct.correct=1;
String html=objectMapper.writeValueAsString(correct);
resp.getWriter().write(html);}//实现 readBody 方法, 用来把请求中的 body 部分全读出来。privatestatic String readBody(HttpServletRequest req)throws UnsupportedEncodingException {int contentLength=req.getContentLength();byte[] bytes=newbyte[contentLength];try(InputStream inputStream = req.getInputStream()){
inputStream.read(bytes);
inputStream.close();}catch(IOException e){
e.printStackTrace();}returnnewString(bytes,"utf8");}}
实现CompileServlet
package api;import com.fasterxml.jackson.databind.ObjectMapper;import common.CodeInValidException;import common.ProblemNotFoundException;import common.Util;import compile.Answer;import compile.Question;import compile.Task;import dao.Problem;import dao.ProblemDAO;import dao.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;import java.io.InputStream;import java.io.UnsupportedEncodingException;@WebServlet("/compile")publicclassCompileServletextendsHttpServlet{private ObjectMapper objectMapper=newObjectMapper();//编译请求staticclassCompileRequest{publicint id;public String code;}//编译响应staticclassCompileResponse{publicint error;public String reason;public String stdout;}@OverrideprotectedvoiddoPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
resp.setContentType("application/json;charset=utf8");
User user= Util.checkUser(req);if(user==null){
resp.setStatus(403);
String html="<h3>当前用户未登录</h3>";
resp.getWriter().write(html);return;}
CompileResponse compileResponse=newCompileResponse();
CompileRequest compileRequest=null;
Problem problem=null;try{
resp.setStatus(200);
String body=readBody(req);
compileRequest=objectMapper.readValue(body,CompileRequest.class);
ProblemDAO problemDAO=newProblemDAO();
problem=problemDAO.selectOne(compileRequest.id);if(problem==null){thrownewProblemNotFoundException();}
String testCode=problem.getTestCode();
String requestCode=compileRequest.code;
String finalCode=mergeCode(requestCode,testCode);if(finalCode==null){thrownewCodeInValidException();}
System.out.println(finalCode);
Task task=newTask();
Question question=newQuestion();
question.setCode(finalCode);
Answer answer=task.compileAndRun(question);
compileResponse.error=answer.getError();
compileResponse.reason=answer.getReason();
compileResponse.stdout=answer.getStdout();}catch(ProblemNotFoundException e){
compileResponse.error=3;
compileResponse.reason="题目没有找到 id="+compileRequest.id;}catch(CodeInValidException e){
compileResponse.error=3;
compileResponse.reason="提交的代码不符合要求";}finally{String respString=objectMapper.writeValueAsString(compileResponse);
resp.getWriter().write(respString);}}//合并用户提交的代码privatestatic String mergeCode(String requestCode, String testCode){int pos=requestCode.lastIndexOf("}");if(pos==-1){return null;}
String string=requestCode.substring(0,pos);
string+=testCode+"\n}";return string;}//实现 readBody 方法, 用来把请求中的 body 部分全读出来。privatestatic String readBody(HttpServletRequest req)throws UnsupportedEncodingException {int contentLength=req.getContentLength();byte[] bytes=newbyte[contentLength];try(InputStream inputStream = req.getInputStream()){
inputStream.read(bytes);
inputStream.close();}catch(IOException e){
e.printStackTrace();}returnnewString(bytes,"utf8");}}
实现deleteProblemServlet
package api;import com.fasterxml.jackson.databind.ObjectMapper;import common.Util;import dao.Problem;import dao.ProblemDAO;import dao.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;import java.io.InputStream;import java.io.UnsupportedEncodingException;@WebServlet("/deleteProblem")publicclassdeleteProblemServletextendsHttpServlet{//获取前端页面的数据staticclassAccept{publicint id;}//响应staticclassResult{publicint result;}private ObjectMapper objectMapper=newObjectMapper();@OverrideprotectedvoiddoPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
req.setCharacterEncoding("utf8");
resp.setContentType("application/json; charset=utf8");
String body=readBody(req);//body为空则返回if(body==null){
resp.setContentType("text/html; charset=utf8");
String html="<h3>无法删除成功!</h3>";
resp.getWriter().write(html);return;}
Accept accept=objectMapper.readValue(body,Accept.class);//调用ProblemDAO
ProblemDAO problemDAO=newProblemDAO();
problemDAO.delete(accept.id);
Result result=newResult();
result.result=1;
String html=objectMapper.writeValueAsString(result);
resp.getWriter().write(html);}//实现 readBody 方法, 用来把请求中的 body 部分全读出来。privatestatic String readBody(HttpServletRequest req)throws UnsupportedEncodingException {int contentLength=req.getContentLength();byte[] bytes=newbyte[contentLength];try(InputStream inputStream = req.getInputStream()){
inputStream.read(bytes);
inputStream.close();}catch(IOException e){
e.printStackTrace();}returnnewString(bytes,"utf8");}}
实现isAdminServlet
package api;import com.fasterxml.jackson.databind.ObjectMapper;import common.Util;import dao.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("/admin")publicclassisAdminServletextendsHttpServlet{private ObjectMapper objectMapper=newObjectMapper();@OverrideprotectedvoiddoGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
resp.setContentType("application/json;charset=utf8");
User user= Util.checkUser(req);if(user==null){
resp.setStatus(403);
String html="<h3>当前用户未登录</h3>";
resp.getWriter().write(html);// resp.sendRedirect("login.html");return;}//给前端返回用户的信息
String html=objectMapper.writeValueAsString(user);
resp.getWriter().write(html);}}
实现LoginoutServlet
package api;import common.Util;import dao.User;import dao.UserDao;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")publicclassLoginoutServletextendsHttpServlet{//注销登录@OverrideprotectedvoiddoGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
HttpSession session = req.getSession(false);if(session == null){
resp.setContentType("text/txt; charset=utf-8");
String html ="<h3>当前尚未登录</h3>";
resp.getWriter().write(html);return;}
session.removeAttribute("user");
resp.sendRedirect("login.html");}//管理员删除用户@OverrideprotectedvoiddoPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
req.setCharacterEncoding("utf8");
String username=req.getParameter("username");
resp.setContentType("text/html; charset=utf8");
User user=Util.checkUser(req);if(user==null){
String html="<h3> 当前用户未登录 </h3>";
resp.getWriter().write(html);// resp.sendRedirect("login.html");return;}if(user.getUsername().equals(username)){
String html="<h3>不能删除自己</h3>";
resp.getWriter().write(html);return;}
UserDao userDao=newUserDao();
User user1=userDao.selectOneByName(username);if(user1==null){
String html="<h3>删除用户不存在</h3>";
resp.getWriter().write(html);return;}
userDao.delete(user1.getId());
resp.sendRedirect("function.html");}}
实现LoginServlet
package api;import com.fasterxml.jackson.databind.ObjectMapper;import dao.User;import dao.UserDao;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("/login")publicclassLoginServletextendsHttpServlet{//用户登录操作@OverrideprotectedvoiddoPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
req.setCharacterEncoding("utf8");
resp.setContentType("text/html; charset=utf8");
UserDao userDao=newUserDao();
String username=req.getParameter("username");
String password=req.getParameter("password");if(username==null||password==null||"".equals(username)||"".equals(password)){
String h3="<h3>输入格式错误</h3>";
resp.getWriter().write(h3);return;}
User user=userDao.selectOneByName(username);if(user==null){
String h3="<h3>当前用户为空</h3>";
resp.getWriter().write(h3);return;}if(!user.getUsername().equals(username)||!user.getPassword().equals(password)){
String h3="<h3>当前密码或者账号 错误!</h3>";
resp.getWriter().write(h3);return;}//将登录用户放进session中
HttpSession session=req.getSession(true);
session.setAttribute("user",user);
resp.sendRedirect("index.html");}}
实现ProblemServlet
package api;import com.fasterxml.jackson.databind.ObjectMapper;import common.Util;import dao.Problem;import dao.ProblemDAO;import dao.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;import java.util.List;@WebServlet("/problem")publicclassProblemServletextendsHttpServlet{private ObjectMapper objectMapper=newObjectMapper();@OverrideprotectedvoiddoGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {//设置为json格式
resp.setContentType("application/json;charset=utf8");
User user= Util.checkUser(req);if(user==null){
resp.setContentType("text/html; charset=utf-8");
resp.setStatus(403);
String html="<h3>当前用户未登录</h3>";
resp.getWriter().write(html);return;// resp.sendRedirect("login.html");// return;}
resp.setStatus(200);
String id=req.getParameter("id");
ProblemDAO problemDAO=newProblemDAO();if(id==null||"".equals(id)){
List<Problem> list=problemDAO.selectAll();//讲后台数据进行json格式化,方便前台获取后进行后续操作
String respString=objectMapper.writeValueAsString(list);
resp.getWriter().write(respString);return;}else{
Problem problem=problemDAO.selectOne(Integer.parseInt(id));//讲后台数据进行json格式化,方便前台获取后进行后续操作
String respString=objectMapper.writeValueAsString(problem);
resp.getWriter().write(respString);return;}}}
实现RegisterServlet
package api;import dao.User;import dao.UserDao;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")publicclassRegisterServletextendsHttpServlet{//注册用户@OverrideprotectedvoiddoPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
req.setCharacterEncoding("utf8");
resp.setContentType("text/html; charset=utf8");
String username=req.getParameter("username");
String password=req.getParameter("password");
String admin=req.getParameter("admin");
UserDao userDao=newUserDao();if(username==null||password==null||"".equals(username)||"".equals(password)){
String h3="<h3>输入格式错误</h3>";
resp.getWriter().write(h3);return;}
User user=userDao.selectOneByName(username);if(user!=null){
String h3="<h3>该用户名字已被使用!</h3>";
resp.getWriter().write(h3);return;}
User registerUser=newUser();
registerUser.setUsername(username);
registerUser.setPassword(password);if(admin==null||"".equals(admin)){
registerUser.setIsAdmin(0);
userDao.insert(registerUser);
resp.sendRedirect("login.html");}else{
registerUser.setIsAdmin(Integer.parseInt(admin));
userDao.insert(registerUser);
resp.sendRedirect("function.html");}}}
前端页面实现
前端的页面都是来源于网上免费的模板,这里只会出现前后端交互的相关代码。
login.html
<divclass="login-agileits-top"><!-- 使用form表单将前端输入的数据返回给后端 --><formaction="login"method="post"><p>User Name </p><inputtype="text"class="name"name="username"><p>Password</p><inputtype="password"class="password"name="password"><inputtype="submit"value="Sign In"></form><!-- 点击该按钮则跳转到注册页面 --><divstyle="text-align: center;"><buttonstyle="font-size: large;"><ahref="register.html"style="text-align: center;">SignUp</a></button></div></div>
register.html
<divclass="login-agileits-top"><!-- 使用form表单将前端输入的数据返回给后端 --><formaction="register"method="post"><p>User Name </p><inputtype="text"class="name"name="username"required=""/><p>Password</p><inputtype="password"class="password"name="password"required=""/><inputtype="submit"value="SignUp"></form></div>
index.html
<tbodyid="problemTable"></tbody><scriptsrc="js/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script><scriptsrc="js/app.js"></script><script>//获取问题的部分信息,获取失败则返回登录页面functiongetProblem(){
$.ajax({
url:"problem",
type:"GET",
success:function(data,status){makeProblemTable(data);},error:function(data,status){
location.assign("login.html");}})}//获取用户登录信息,获取失败则返回登录页面functiongetUser(){
$.ajax({
url:"admin",
type:"GET",
success:function(data,status){isAdminUser(data);},error:function(data,status){
location.assign("login.html");}})}//判断目前登录用户是否为管理员,是增加‘管理员页面’functionisAdminUser(user){let div=document.querySelector("#javaoj");if(user.isAdmin){let a=document.createElement("a");
a.innerHTML="管理员页面";
a.href="function.html";
a.target="_blank";
div.appendChild(a);}}functionmakeProblemTable(data){//获取id为problemTable的元素let problemTable=document.querySelector("#problemTable");for(let problem of data){let tr=document.createElement("tr");let tdId=document.createElement("td");
tdId.innerHTML=problem.id;
tr.appendChild(tdId);let tdTitle=document.createElement("td");let a=document.createElement("a");
a.innerHTML=problem.title;
a.href="problemDetail.html?id="+problem.id;
a.target='_blank';
tdTitle.appendChild(a);
tr.appendChild(tdTitle);let tdlevel=document.createElement("td");
tdlevel.innerHTML=problem.level;
tr.appendChild(tdlevel);
problemTable.appendChild(tr);}}getUser();getProblem();</script>
problemDetail.html
<sectionclass="my-5 pt-5"><divclass="container"><divclass="row mt-4"><divclass="col-sm-12 pb-4"><divclass="jumbotron jumbotron-fluid"><divclass="container"id="problemDesc"></div></div></div></div><divclass="row mt-4"><divclass="col-sm-12 pb-4"><divclass="form-group"><labelfor="codeEditor">代码编辑框</label><divid="editor"style="min-height:400px"><textareaclass="form-control"id="codeEditor"style="width: 100%;height: 400px;"></textarea></div></div></div></div><buttontype="button"class="btn btn-primary"id="submitButton">提交</button><divclass="row mt-4"><divclass="col-sm-12 pb-4"><divclass="jumbotron jumbotron-fluid"><divclass="container"><preid="problemResult"></pre></div></div></div></div></div></section><!-- 引入 ace.js ,给用户有更好的体验感--><scriptsrc="https://cdn.bootcdn.net/ajax/libs/ace/1.2.9/ace.js"></script><scriptsrc="https://cdn.bootcdn.net/ajax/libs/ace/1.2.9/ext-language_tools.js"></script><script>functioninitAce(){// 参数 editor 就对应到刚才在 html 里加的那个 div 的 idlet editor = ace.edit("editor");
editor.setOptions({
enableBasicAutocompletion:true,
enableSnippets:true,
enableLiveAutocompletion:true});
editor.setTheme("ace/theme/twilight");
editor.session.setMode("ace/mode/java");
editor.resize();
document.getElementById('editor').style.fontSize ='20px';return editor;}let editor =initAce();// 通过 ajax 从服务器获取到题目的详情functiongetProblem(){// 1. 通过 ajax 给服务器发送一个请求
$.ajax({
url:"problem"+ location.search,
type:"GET",
success:function(data, status){makeProblemDetail(data);},error:function(data,status){
location.assign('login.html');}})}
$.ajax({
url:"problem",
type:"GET",
error:function(data,status){
location.assign('login.html');}});functionmakeProblemDetail(problem){// 1. 获取到 problemDesc, 把题目详情填写进去let problemDesc = document.querySelector("#problemDesc");let h3 = document.createElement("h3");
h3.innerHTML = problem.id +"."+ problem.title +"_"+ problem.level
problemDesc.appendChild(h3);let pre = document.createElement("pre");let p = document.createElement("p");
p.innerHTML = problem.description;
pre.appendChild(p);
problemDesc.appendChild(pre);// 2. 把代码的模板填写到编辑框中. // let codeEditor = document.querySelector("#codeEditor");// codeEditor.innerHTML = problem.templateCode;
editor.setValue(problem.templateCode)// 3. 给提交按钮注册一个点击事件let submitButton = document.querySelector("#submitButton");
submitButton.onclick=function(){// 点击这个按钮, 就要进行提交. (把编辑框的内容给提交到服务器上)let body ={
id: problem.id,// code: codeEditor.value,
code: editor.getValue(),};
$.ajax({
type:"POST",
url:"compile",
data:JSON.stringify(body),
success:function(data, status){let problemResult = document.querySelector("#problemResult");if(data.error ==0){// 编译运行没有问题, 把 stdout 显示到页面中
problemResult.innerHTML = data.stdout;}else{// 编译运行没有问题, 把 reason 显示到页面中
problemResult.innerHTML = data.reason;}},error:function(data,status){
location.assign('login.html');}});}}getProblem();</script>
function.html
<scriptsrc="js/jquery.min.js"></script><!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> --><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script><scriptsrc="js/app.js"></script><script>//判断该用户是否为管理员不是则返回登录页面functiongetUser(){
$.ajax({
url:"admin",
type:"GET",
success:function(data,status){if(!data.isAdmin){
location.assign("index.html");}},
error:function(data,status){
location.assign("login.html");}})}getUser();</script>
deleteUser.html
<divclass="agile-row"><h3>SignUp Form</h3><divclass="login-agileits-top"><!-- 使用form表单将前端输入的数据返回给后端 --><formaction="logout"method="post"><p>UserName</p><inputtype="text"class="name"name="username"><inputtype="submit"value="Delete"></form></div></div><scriptsrc="js/jquery.min.js"></script><script>//判断该用户是否为管理员不是则返回登录页面functiongetUser(){
$.ajax({
url:"admin",
type:"GET",
success:function(data,status){if(!data.isAdmin){
location.assign("index.html");}},
error:function(data,status){
location.assign("login.html");}})}getUser();</script>
deleteProblem.html
<divclass="mt-3 mb-5"><h3>题目列表</h3><tableclass="table table-striped"><thead><tr><th>编号</th><th>标题</th><th>难度</th></tr></thead><tbodyid="problemTable"></tbody></table></div><scriptsrc="js/jquery.min.js"></script><!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> --><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script><scriptsrc="js/app.js"></script><script>//获取题目信息functiongetProblem(){
$.ajax({
url:"problem",
type:"GET",
success:function(data,status){makeProblemTable(data);},error:function(data,status){
location.assign("login.html");}})}//判断该用户是否为管理员不是则返回登录页面functiongetUser(){
$.ajax({
url:"admin",
type:"GET",
success:function(data,status){if(!data.isAdmin){
location.assign("index.html");}},
error:function(data,status){
location.assign("login.html");}})}functionmakeProblemTable(data){let problemTable=document.querySelector("#problemTable");for(let problem of data){let tr=document.createElement("tr");let tdId=document.createElement("td");
tdId.innerHTML=problem.id;
tr.appendChild(tdId);let tdTitle=document.createElement("td");let a=document.createElement("a");
a.innerHTML=problem.title;
a.href="problemDetail.html?id="+problem.id;
a.target='_blank';
tdTitle.appendChild(a);
tr.appendChild(tdTitle);let tdlevel=document.createElement("td");
tdlevel.innerHTML=problem.level;
tr.appendChild(tdlevel);let tdButton=document.createElement("td");let button=document.createElement("button");
button.innerHTML="删除";
button.value=problem.id;
button.id="submit";//给按钮设计一个点击事件
button.onclick=function(){let body={
id: problem.id,};
$.ajax({
url:"deleteProblem",
type:"Post",
data:JSON.stringify(body),
success:function(data,status){if(data){
location.assign("deleteProblem.html");}}})}
tdButton.appendChild(button);
tr.appendChild(tdButton);
problemTable.appendChild(tr);}}getUser();getProblem();</script>
addUser.html
<divclass="login-agileits-top"><!-- 使用form表单将前端输入的数据返回给后端 --><formaction="register"method="post"><p>UserName </p><inputtype="text"class="name"name="username"required=""/><p>Password</p><inputtype="password"class="password"name="password"required=""/><p>isAdmin(是输入1 否则为0)</p><inputtype="text"class="name"name="admin"required=""/><inputtype="submit"value="SignUp"></form></div><scriptsrc="js/jquery.min.js"></script><script>//获取用户登录信息,获取失败则返回登录页面functiongetUser(){
$.ajax({
url:"admin",
type:"GET",
success:function(data,status){if(!data.isAdmin){
location.assign("index.html");}},
error:function(data,status){
location.assign("login.html");}})}getUser();</script>
addProblem.html
<sectionclass="my-5 pt-5"><divclass="container"><divclass="row mt-4"><divclass="col-sm-12 pb-4"><divclass="form-group"><labelfor="title">标题</label><textareaclass="form-control"id="title"style="width: 100%;height: 40px;"></textarea></div></div></div><divclass="row mt-4"><divclass="col-sm-12 pb-4"><divclass="form-group"><labelfor="level">难度</label><textareaclass="form-control"id="level"style="width: 100%;height: 40px;"></textarea></div></div></div><divclass="row mt-4"><divclass="col-sm-12 pb-4"><divclass="form-group"><labelfor="description">题目描述</label><textareaclass="form-control"id="description"style="width: 100%;height: 400px;"></textarea></div></div></div><divclass="row mt-4"><divclass="col-sm-12 pb-4"><divclass="form-group"><labelfor="TestCode">测试用例</label><textareaclass="form-control"id="TestCode"style="width: 100%;height: 400px;"></textarea></div></div></div><divclass="row mt-4"><divclass="col-sm-12 pb-4"><divclass="form-group"><labelfor="codeEditor">代码</label><textareaclass="form-control"id="codeEditor"style="width: 100%;height: 400px;"></textarea></div></div></div><buttontype="button"class="btn btn-primary"id="submitButton">提交</button></div></section><!--footer--><sectionclass="py-5 bg-dark"><divclass="container"><divclass="row"><divclass="col-md-6 offset-md-3 col-sm-8 offset-sm-2 col-xs-12 text-center"><pclass="pt-2 text-muted">© by 文墨轩
</p></div></div></div></section><scriptsrc="js/jquery.min.js"></script><script>functiongetUser(){
$.ajax({
url:"admin",
type:"GET",
success:function(data,status){if(!data.isAdmin){
location.assign("index.html");}},
error:function(data,status){
location.assign("login.html");}})}let button=document.querySelector("#submitButton");
button.onclick=function(){let body={
id:0,
title: title.value,
level: level.value,
description: description.value,
testCode: TestCode.value,
templateCode: codeEditor.value,};
$.ajax({
url:"addProblem",
type:"POST",
data:JSON.stringify(body),
success:function(data,status){if(data.correct){
location.assign("function.html");}}})}getUser();</script>
项目展示
管理员
普通用户
Gitee地址
在线oj代码地址
版权归原作者 文墨轩 所有, 如有侵权,请联系我们删除。