精华内容
下载资源
问答
  • 基于jsp和servlet的项目
    万次阅读 多人点赞
    2019-04-21 20:56:46

    一、项目名称

    使用MVC模式和三层开发架构,开发一个完整的“注册登录退出”模块。

    二、项目环境

    1、软件环境:

    系统环境:win10
    JDK版本: jdk1.8.0_181
    IDE版本:eclipse-java-oxygen-3a-win32-x86_64
    avaEE varsion:JavaEE5 –Web2.5
    Java version: 1.7.
    服务器版本:apache-tomcat-7.0.69
    浏览器版本:Google Chrome浏览器

    2、项目思路 :

    通过MVC开发流程,实现项目的架构。然后利用Servlet+Jsp+Jdbc的功能开发流程,实现登陆注册退出功能。
    通过DataServlet实现服务器在接收到浏览器发送的请求后,会调用对应的Servlet进行请求处理,从而将多个业务逻辑功能组合到一起。

    3、项目所用知识点:

    模板的套用
    MVC开发流程
    Servlet+Jsp+Jdbc的功能开发流程
    request和session作用域的使用
    浏览器发起请求到服务器的方式(重点记忆)
    BaseServlet的抽取和使用

    4、项目架构:

    在这里插入图片描述

    三、项目源码

    数据库设计

    ##创建用户表
    create table t_user(
    uid int(10) not null auto_increment,
    uname varchar(100) not null,
    pwd varchar(100) not null, 
    sex char(4) not null,
    age int(3) not null,
    birthday date not null,
    primary key(uid)
    );
    
    insert into t_user values(default,'张三',123,'男',18,'1988-09-09' );
    insert into t_user values(default,'小七',456,'男',20,'1996-09-09' );
    

    在这里插入图片描述

    UserDaoImpl.java

      package com.bjsxt.dao.impl;
        
        import java.sql.Connection;
        import java.sql.PreparedStatement;
        import java.sql.ResultSet;
        
        import com.bjsxt.dao.UserDao;
        import com.bjsxt.pojo.User;
        import com.bjsxt.util.DBUtil;
        /**
         * 导的不是jdbc包,全是sql包
         * @author chy
         *
         */
        public class UserDaoImpl implements UserDao {
        	//查询用户信息
        	@Override
        	public User getUserInfoDao(String uname, String pwd) {
        		//声明jdbc变量
        		Connection conn=null;
        		PreparedStatement ps=null;
        		ResultSet rs=null;
        		//声明变量
        		User u=null;
        		
        		try {
        			
        			//创建连接
        			conn=DBUtil.getConnection();
        			//创建sql命令
        			String sql="select * from t_user where uname=? and pwd=?";
        			//创建SQL命令对象
        			ps=conn.prepareStatement(sql);
        			//给占位符赋值
        			ps.setString(1,	uname);
        			ps.setString(2, pwd);
        			//执行sql命令
        			rs=ps.executeQuery();
        			//遍历
        			while (rs.next()) {
        				//给变量赋值
        				u=new User();
        				u.setUid(rs.getInt("uid"));
        				u.setUname(rs.getString("uname"));
        				u.setPwd(rs.getString("pwd"));
        				u.setSex(rs.getString("sex"));
        				u.setAge(rs.getInt("age"));
        				u.setBirthday(rs.getString("birthday"));
        			}
        			//关闭资源
        			//返回结果
        		} catch (Exception e) {
        			e.printStackTrace();
        		}finally{
        			DBUtil.closeAll(rs, ps, conn);
        		}
        		
        		return u;
        	}
        
        	//用户注册
        	@Override
        	public int regUserInfoDao(String uname, String pwd, String sex, int age,
        			String birthday) {
        		
        		//创建sql语句
        		String sql="insert into t_user values(default,?,?,?,?,?)";
        		return DBUtil.executeDML(sql, uname,pwd,sex,age,birthday);
        	}
        
        }
    

    UserDao.java

      package com.bjsxt.dao;
        
        import com.bjsxt.pojo.User;
        
        public interface UserDao {
        	/**
        	 * 根据用户名和密码,查询用户信息
        	 * @author chy
        	 *
        	 */
        	User getUserInfoDao(String uname, String pwd);
        
        	
        	int regUserInfoDao(String uname, String pwd, String sex, int age,
        			String birthday);
        
        }
    
    
    

    User.java

     package com.bjsxt.pojo;
        
        public class User {
        	private int uid;
        	private String uname;
        	private String pwd;
        	private String sex;
        	private int age;
        	private String birthday;
        	public int getUid() {
        		return uid;
        	}
        	public void setUid(int uid) {
        		this.uid = uid;
        	}
        	public String getUname() {
        		return uname;
        	}
        	public void setUname(String uname) {
        		this.uname = uname;
        	}
        	public String getPwd() {
        		return pwd;
        	}
        	public void setPwd(String pwd) {
        		this.pwd = pwd;
        	}
        	public String getSex() {
        		return sex;
        	}
        	public void setSex(String sex) {
        		this.sex = sex;
        	}
        	public int getAge() {
        		return age;
        	}
        	public void setAge(int age) {
        		this.age = age;
        	}
        	public String getBirthday() {
        		return birthday;
        	}
        	public void setBirthday(String birthday) {
        		this.birthday = birthday;
        	}
        	public User(int uid, String uname, String pwd, String sex, int age,
        			String birthday) {
        		super();
        		this.uid = uid;
        		this.uname = uname;
        		this.pwd = pwd;
        		this.sex = sex;
        		this.age = age;
        		this.birthday = birthday;
        	}
        	public User() {
        		super();
        	}
        	@Override
        	public int hashCode() {
        		final int prime = 31;
        		int result = 1;
        		result = prime * result + age;
        		result = prime * result
        				+ ((birthday == null) ? 0 : birthday.hashCode());
        		result = prime * result + ((pwd == null) ? 0 : pwd.hashCode());
        		result = prime * result + ((sex == null) ? 0 : sex.hashCode());
        		result = prime * result + uid;
        		result = prime * result + ((uname == null) ? 0 : uname.hashCode());
        		return result;
        	}
        	@Override
        	public boolean equals(Object obj) {
        		if (this == obj)
        			return true;
        		if (obj == null)
        			return false;
        		if (getClass() != obj.getClass())
        			return false;
        		User other = (User) obj;
        		if (age != other.age)
        			return false;
        		if (birthday == null) {
        			if (other.birthday != null)
        				return false;
        		} else if (!birthday.equals(other.birthday))
        			return false;
        		if (pwd == null) {
        			if (other.pwd != null)
        				return false;
        		} else if (!pwd.equals(other.pwd))
        			return false;
        		if (sex == null) {
        			if (other.sex != null)
        				return false;
        		} else if (!sex.equals(other.sex))
        			return false;
        		if (uid != other.uid)
        			return false;
        		if (uname == null) {
        			if (other.uname != null)
        				return false;
        		} else if (!uname.equals(other.uname))
        			return false;
        		return true;
        	}
        	@Override
        	public String toString() {
        		return "User [uid=" + uid + ", uname=" + uname + ", pwd=" + pwd
        				+ ", sex=" + sex + ", age=" + age + ", birthday=" + birthday
        				+ "]";
        	}
        	
        	
        }
    

    UserService.java

     package com.bjsxt.service;
        
        import com.bjsxt.pojo.User;
        
        public interface UserService {
        	/**用户登陆
        	 * 
        	 * @param uname
        	 * @param pwd
        	 * @return
        	 */
        	User getUserInfoService(String uname, String pwd);
        	
        	/**用户注册
        	 * 
        	 * @param uname
        	 * @param pwd
        	 * @param sex
        	 * @param age
        	 * @param birthday
        	 * @return
        	 */
        	int getUserInfoService(String uname, String pwd, String sex, int age,
        			String birthday);
        	
        }
        
        
        UserServiceImpl.java
        
        package com.bjsxt.service.impl;
        
        import com.bjsxt.dao.UserDao;
        import com.bjsxt.dao.impl.UserDaoImpl;
        import com.bjsxt.pojo.User;
        import com.bjsxt.service.UserService;
        
        public class UserServiceImpl implements UserService {
        	//创建Dao对象
        	UserDao ud = new UserDaoImpl();
        	
        	
        	@Override
        	public User getUserInfoService(String uname, String pwd) {
        		//处理登录业务
        		return ud.getUserInfoDao(uname,pwd);
        	}
        
        	
        	//用户注册
        	@Override
        	public int getUserInfoService(String uname, String pwd, String sex,
        			int age, String birthday) {
        		//处理注册业务
        		return ud.regUserInfoDao(uname,pwd,sex,age,birthday);
        	}
        
        }
    

    BaseServlet.java

    package com.bjsxt.servlet;
        
        import java.io.IOException;
        import java.lang.reflect.Method;
        
        import javax.servlet.ServletException;
        import javax.servlet.http.HttpServlet;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        
        public abstract class BaseServlet extends HttpServlet {
        	@Override
        	protected void service(HttpServletRequest req, HttpServletResponse resp)
        			throws ServletException, IOException {
        		//设置请求、响应编码格式
        		req.setCharacterEncoding("utf-8");
        		resp.setContentType("text/html; charset=utf-8");
        		//获取请求信息
        		String methodName = req.getParameter("method");
        		//处理请求信息(动态调用方法处理请求--》反射)
        			try {
        				//反射方法获取所在类的类对象
        				Class cla = this.getClass();
        				//反射方法获取要被调用的方法对象
        				Method m= cla.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
        				//反射执行的方法
        				m.invoke(this, req,resp);
        			} catch (Exception e) {
        				e.printStackTrace();
        			} 
        	}
        }
    

    DataServlet.java

      package com.bjsxt.servlet;
        
        import java.io.IOException;
        import java.lang.reflect.Method;
        import java.util.Calendar;
        
        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.bjsxt.pojo.User;
        import com.bjsxt.service.UserService;
        import com.bjsxt.service.impl.UserServiceImpl;
        
        public  class DataServlet extends BaseServlet {
        	/*@Override
        	protected void service(HttpServletRequest req, HttpServletResponse resp)
        			throws ServletException, IOException {
        		//设置请求、响应编码格式
        		req.setCharacterEncoding("utf-8");
        		resp.setContentType("text/html; charset=utf-8");
        		//获取请求信息
        		String methodName = req.getParameter("method");
        		//处理请求信息(动态调用方法处理请求--》反射)
        			try {
        				//反射方法获取所在类的类对象
        				Class cla = this.getClass();
        				//反射方法获取要被调用的方法对象
        				Method m= cla.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
        				//反射执行的方法
        				m.invoke(this, req,resp);
        			} catch (Exception e) {
        				e.printStackTrace();
        			} 
        	}*/
        	
        	
        	//登陆处理方法
        	public void Userlogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        		//获取请求信息
        				String uname = req.getParameter("uname");
        				String pwd = req.getParameter("pwd");
        				//处理请求信息
        				System.out.println("DataServlet.Userlogin()"+uname+":"+pwd);
        				
        					//创建业务层对象
        					UserService us = new UserServiceImpl();
        					User u= us.getUserInfoService(uname,pwd);
        					System.out.println("用户查询登陆结果为:"+u);
        					
        				//响应处理结果
        					//直接响应	
        					//请求转发
        					
        					//获取session对象
        					HttpSession hs = req.getSession();
        					
        					if (u!=null) {//登陆成功
        						//将用户信息存储到session
        						hs.setAttribute("user", u);
        						
        						//重定向到mian.jsp
        						resp.sendRedirect("/16/main.jsp");
        					}else {//登录失败
        						//将登陆标记添加
        						hs.setAttribute("flag", "loginfalse");
        						//重定向到login.jsp
        						resp.sendRedirect("/16/login.jsp");
        					}
        	}
        	//退出处理方法
        	public void UserOut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        		//获取请求信息
        		//处理请求信息
        			//获取session、销毁session
        			HttpSession hs = req.getSession();
        			hs.invalidate();
        		//相应处理结果
        			//直接响应
        			//请求转发
        			//重定向
        		resp.sendRedirect("/16/login.jsp");
        		}
        	//注册处理方法
        	public void UserReg(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        		//获取请求信息
        				String uname = req.getParameter("uname");
        				String pwd = req.getParameter("pwd");
        				String sex = req.getParameter("sex");
        				int age =Integer.parseInt(req.getParameter("age")) ;
        				String birthday = req.getParameter("birthday");
        				//处理请求信息
        					//获取业务层对象
        				    UserService us = new UserServiceImpl();
        				     //处理注册
        				    int i=us.getUserInfoService(uname, pwd,sex,age,birthday);
        				    
        				//相应处理结果
        				    //获取session对象
        				    HttpSession hs = req.getSession();
        					//重定向到登陆界面
        				    if(i>0){
        						//注册成功,添加标记到session
        				    	hs.setAttribute("flag", "regsuccess");
        						resp.sendRedirect("/16/login.jsp");
        					}else{
        						//重定向到注册页面
        						resp.sendRedirect("/16/login.jsp");
        					}
        	}
        }
    

    DBUtil.java

     package com.bjsxt.util;
        
        import java.io.IOException;
        import java.io.InputStream;
        import java.sql.Connection;
        import java.sql.DriverManager;
        import java.sql.PreparedStatement;
        import java.sql.ResultSet;
        import java.sql.SQLException;
        import java.sql.Statement;
        import java.util.Properties;
        
        public class DBUtil {
        	//声明全局变量记录jdbc参数
        	private static String driver;
        	private static String url;
        	private static String username;
        	private static String password;
        	//使用静态代码块,在类加载时即完成对属性文件的读取
        	static{
        		//动态获取属性配置文件的流对象
        		InputStream in=DBUtil.class.getResourceAsStream("/db.properties");
        		//创建Properties对象
        		Properties p=new Properties();
        		//加载
        		try {
        			p.load(in);//会将属性配置文件的所有数据存储到Properties对象中
        			//将读取的jdbc参数赋值给全局变量
        			driver=p.getProperty("driver");
        			url=p.getProperty("url");
        			username=p.getProperty("username");
        			password=p.getProperty("password");
        			//加载驱动
        			Class.forName(driver);
        		} catch (IOException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		} catch (ClassNotFoundException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
        	}
        	//创建连接对象并返回
        	public static Connection getConnection(){
        		Connection conn=null;
        		try {
        			conn = DriverManager.getConnection(url, username, password);
        		} catch (SQLException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
        		
        		return conn;
        	}
        	//关闭资源
        	public static void closeAll(ResultSet rs,Statement stmt,Connection conn){
        		try {
        			if(rs!=null){
        				rs.close();
        			}
        		} catch (SQLException e1) {
        			// TODO Auto-generated catch block
        			e1.printStackTrace();
        		}
        		try {
        			stmt.close();
        		} catch (SQLException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
        		try {
        			conn.close();
        		} catch (SQLException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
        		
        		
        	}
        	//封装增加删除修改的通用工具方法
        	/**
        	 * @param sql SQL语句
        	 * @param objs	SQL语句占位符实参,如果没有参数则传入null
        	 * @return 返回增删改的结果,类型为int
        	 */
        	public static int executeDML(String sql,Object...objs){
        		// 声明jdbc变量
        				Connection conn = null;
        				PreparedStatement ps = null;
        				int i = -1;
        				try {
        					// 获取连接对象
        					conn = DBUtil.getConnection();
        					// 开启事务管理
        					conn.setAutoCommit(false);
        					// 创建SQL命令对象
        					ps = conn.prepareStatement(sql);
        					// 给占位符赋值
        					if(objs!=null){
        						for(int j=0;j<objs.length;j++){
        							ps.setObject(j+1,objs[j]);
        						}
        					}
        					// 执行SQL
        					i = ps.executeUpdate();
        					conn.commit();
        				} catch (Exception e) {
        					try {
        						conn.rollback();
        					} catch (SQLException e1) {
        						// TODO Auto-generated catch block
        						e1.printStackTrace();
        					}
        					e.printStackTrace();
        				} finally {
        					DBUtil.closeAll(null, ps, conn);
        				}
        				return i;
        	}
        	
        	
        	
        }
    

    db.properties

     driver=com.mysql.jdbc.Driver
     url=jdbc:mysql://localhost:3306/project
     username=root
     password=root
    

    web.xml

      <?xml version="1.0" encoding="UTF-8"?>
        <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
          <display-name>15Progect</display-name>
          <servlet>
            <description>This is the description of my J2EE component</description>
            <display-name>This is the display name of my J2EE component</display-name>
            <servlet-name>UserServlet</servlet-name>
            <servlet-class>com.bjsxt.servlet.UserServlet</servlet-class>
          </servlet>
          <servlet>
            <description>This is the description of my J2EE component</description>
            <display-name>This is the display name of my J2EE component</display-name>
            <servlet-name>OutServlet</servlet-name>
            <servlet-class>com.bjsxt.servlet.OutServlet</servlet-class>
          </servlet>
          <servlet>
            <description>This is the description of my J2EE component</description>
            <display-name>This is the display name of my J2EE component</display-name>
            <servlet-name>RegServlet</servlet-name>
            <servlet-class>com.bjsxt.servlet.RegServlet</servlet-class>
          </servlet>
          <servlet>
            <description>This is the description of my J2EE component</description>
            <display-name>This is the display name of my J2EE component</display-name>
            <servlet-name>DataServlet</servlet-name>
            <servlet-class>com.bjsxt.servlet.DataServlet</servlet-class>
          </servlet>
         
        
          <servlet-mapping>
            <servlet-name>UserServlet</servlet-name>
            <url-pattern>/user</url-pattern>
          </servlet-mapping>
          <servlet-mapping>
            <servlet-name>OutServlet</servlet-name>
            <url-pattern>/out</url-pattern>
          </servlet-mapping>
          <servlet-mapping>
            <servlet-name>RegServlet</servlet-name>
            <url-pattern>/reg</url-pattern>
          </servlet-mapping>
          <servlet-mapping>
            <servlet-name>DataServlet</servlet-name>
            <url-pattern>/data</url-pattern>
      
    
            </servlet-mapping>
        
          <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
          </welcome-file-list>
        </web-app>
    

    info.jsp

     <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
            <%
            String path = request.getContextPath();
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
            %>
        
           
        <!DOCTYPE html>
        <html>
        <head>
          <base href="<%=basePath%>">
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
            <meta name="renderer" content="webkit">
            <title>网站信息</title>  
            <link rel="stylesheet" href="css/pintuer.css">
            <link rel="stylesheet" href="css/admin.css">
            <script src="js/jquery.js"></script>
            <script src="js/pintuer.js"></script>  
        </head>
        <body>
        <div class="panel admin-panel">
          <div><strong><span></span> 网站信息</strong></div>
          <div>
            <form method="post" action="">
              <div>
                <div>
                  <label>网站标题:</label>
                </div>
                <div>
                  <input type="text" name="stitle" value="" />
                  <div></div>
                </div>
              </div>
              <div>
                <div>
                  <label>网站LOGO:</label>
                </div>
                <div>
                  <input type="text" id="url1" name="slogo" class="input tips" style="width:25%; float:left;" value="" data-toggle="hover" data-place="right" data-image=""  />
                  <input type="button" class="button bg-blue margin-left" id="image1" value="+ 浏览上传" >
                </div>
              </div>
              <div>
                <div>
                  <label>网站域名:</label>
                </div>
                <div>
                  <input type="text" name="surl" value="" />
                </div>
              </div>
              <div style="display:none">
                <div>
                  <label>副加标题:</label>
                </div>
                <div>
                  <input type="text" name="sentitle" value="" />
                  <div></div>
                </div>
              </div>
              <div>
                <div>
                  <label>网站关键字:</label>
                </div>
                <div>
                  <textarea name="skeywords" style="height:80px"></textarea>
                  <div></div>
                </div>
              </div>
              <div>
                <div>
                  <label>网站描述:</label>
                </div>
                <div>
                  <textarea name="sdescription"></textarea>
                  <div></div>
                </div>
              </div>
              <div>
                <div>
                  <label>联系人:</label>
                </div>
                <div>
                  <input type="text" name="s_name" value="" />
                  <div></div>
                </div>
              </div>
              <div>
                <div>
                  <label>手机:</label>
                </div>
                <div>
                  <input type="text" name="s_phone" value="" />
                  <div></div>
                </div>
              </div>
              <div>
                <div>
                  <label>电话:</label>
                </div>
                <div>
                  <input type="text" name="s_tel" value="" />
                  <div></div>
                </div>
              </div>
              <div style="display:none;">
                <div>
                  <label>400电话:</label>
                </div>
                <div>
                  <input type="text" name="s_400" value="" />
                  <div></div>
                </div>
              </div>
              <div>
                <div>
                  <label>传真:</label>
                </div>
                <div>
                  <input type="text" name="s_fax" value="" />
                  <div></div>
                </div>
              </div>
              <div>
                <div>
                  <label>QQ:</label>
                </div>
                <div>
                  <input type="text" name="s_qq" value="" />
                  <div></div>
                </div>
              </div>
              <div style="display:none">
                <div>
                  <label>QQ群:</label>
                </div>
                <div>
                  <input type="text" name="s_qqu" value="" />
                  <div></div>
                </div>
              </div>
             
              <div>
                <div>
                  <label>Email:</label>
                </div>
                <div>
                  <input type="text" name="s_email" value="" />
                  <div></div>
                </div>
              </div>
              <div>
                <div>
                  <label>地址:</label>
                </div>
                <div>
                  <input type="text" name="s_address" value="" />
                  <div></div>
                </div>
              </div>  
                      
              <div>
                <div>
                  <label>底部信息:</label>
                </div>
                <div>
                  <textarea name="scopyright" style="height:120px;"></textarea>
                  <div></div>
                </div>
              </div>
              <div>
                <div>
                  <label></label>
                </div>
                <div>
                  <button class="button bg-main icon-check-square-o" type="submit"> 提交</button>
                </div>
              </div>
            </form>
          </div>
        </div>
        </body></html>
    
    

    login.jsp

      <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
        <%
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        %> 
         
         <!DOCTYPE html>
        <html>
        <head>
        <base href="<%=basePath%>">
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
            <meta name="renderer" content="webkit">
            <title>登录</title>  
            <link rel="stylesheet" href="css/pintuer.css">
            <link rel="stylesheet" href="css/admin.css">
            <script src="js/jquery.js"></script>
            <script src="js/pintuer.js"></script>  
        </head>
        <body>
        <div></div>
        <div>
            <div class="line bouncein">
                <div class="xs6 xm4 xs3-move xm4-move">
                    <div style="height:150px;"></div>
                    <div class="media media-y margin-big-bottom">           
                    </div>         
                    <form action="data" method="get">
                    
                    <!-- 声明处理请求的方法 -->
                    <input type="hidden" name="method" value="Userlogin" />
                    <div class="panel loginbox">
                        <div class="text-center margin-big padding-big-top"><h1>chy超级管理系统</h1></div>
                        
                        <!-- 声明java代码块 -->
                        <% 
                        //获取session中的标记
                        Object obj =session.getAttribute("flag"); 
                        if(obj!=null){ 
                        if("loginfalse".equals((String)obj)){ %>
                        <div style="text-align:center;color:red"; ><h1>用户名或密码错误</h1></div>
                      <%
                         }else if("regsuccess".equals((String)obj)){
                      %>
                    <div style="text-align:center;color:red"; ><h1>新用户注册成功</h1></div>
                       <%
                        }
                        }
                        session.invalidate();/* 销毁session */
                        %>
                        
                        <div style="padding:30px; padding-bottom:10px; padding-top:10px;">
                            <div>
                                <div class="field field-icon-right">
                                    <input type="text" class="input input-big" name="uname" placeholder="登录账号" data-validate="required:请填写账号" />
                                    <span class="icon icon-user margin-small"></span>
                                </div>
                            </div>
                            <div>
                                <div class="field field-icon-right">
                                    <input type="password" class="input input-big" name="pwd" placeholder="登录密码" data-validate="required:请填写密码" />
                                    <span class="icon icon-key margin-small"></span>
                                </div>
                            </div>
                            <div>
                                <div>
                                    <input type="text" class="input input-big" name="code" placeholder="填写右侧的验证码" data-validate="required:请填写右侧的验证码" />
                                   <img src="images/passcode.jpg" alt="" width="100" height="32" style="height:43px;cursor:pointer;" onclick="this.src=this.src+'?'">  
                                                           
                                </div>
                            </div>
                        </div>
                        <div style="padding:30px;"><input type="submit" class="button button-block bg-main text-big input-big" value="登录"></div>
                        <div style="font-size:20px; position:relative;left:300px;top:-20px"><a href="reg.jsp">注册</a></div>
                    </div>
                    </form>          
                </div>
            </div>
        </div>
        
        </body>
        </html>
    
    

    main.jsp

     <%@page import="com.bjsxt.pojo.User"%>
        <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
        <%
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        %>
        
            
        <!DOCTYPE html>
        <html>
        <head>
        <base href="<%=basePath%>">
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
            <meta name="renderer" content="webkit">
            <title>chy参与管理系统修改</title>  
            <link rel="stylesheet" href="css/pintuer.css">
            <link rel="stylesheet" href="css/admin.css">
            <script src="js/jquery.js"></script>   
            
            <script type="text/javascript">
           //给退出登陆添加单击事件,通过id选择器
             $(function(){
             $("#out").click(function(){
             return window.confirm("你需要退出登陆吗?")
             })
             })
            </script>
        </head>
        <body style="background-color:#f2f9fd;">
        <div class="header bg-main" style="border:solid 1px">
          <div class="logo margin-big-left fadein-top">
            <h1><img src="images/y.jpg" class="radius-circle rotate-hover" height="50" alt="" />chy超级管理系统</h1>
          </div>
          
          
          <!-- 加入欢迎用户登陆的界面 span行内标签-->
          <!-- 加边框 -->
          <div style="position:relative;left:900px"><span style="font-size:20px;color:white;"> 欢迎:<%=( (User)session.getAttribute("user")).getUname() %>进入系统</span> &nbsp;&nbsp; <a id="out" class="button button-little bg-red" href="data?method=UserOut"><span></span> 退出登录</a> </div>
        
        </div>
        <div>
          <div><strong><span></span>菜单列表</strong></div>
          <h2><span></span>基本设置</h2>
          <ul style="display:block">
            <li><a href="info.html" target="right"><span></span>网站设置</a></li>
            <li><a href="pass.html" target="right"><span></span>修改密码</a></li>
            <li><a href="page.html" target="right"><span></span>单页管理</a></li>  
            <li><a href="adv.html" target="right"><span></span>首页轮播</a></li>   
            <li><a href="book.html" target="right"><span></span>留言管理</a></li>     
            <li><a href="column.html" target="right"><span></span>栏目管理</a></li>
          </ul>   
          <h2><span></span>栏目管理</h2>
          <ul>
            <li><a href="list.html" target="right"><span></span>内容管理</a></li>
            <li><a href="add.html" target="right"><span></span>添加内容</a></li>
            <li><a href="cate.html" target="right"><span></span>分类管理</a></li>        
          </ul>  
        </div>
        <script type="text/javascript">
        $(function(){
          $(".leftnav h2").click(function(){
          $(this).next().slideToggle(200);
          $(this).toggleClass("on"); 
          })
          $(".leftnav ul li a").click(function(){
            $("#a_leader_txt").text($(this).text());
           $(".leftnav ul li a").removeClass("on");
        $(this).addClass("on");
          })
        });
        </script>
        <ul>
          <li><a href="{:U('Index/info')}" target="right"> 首页</a></li>
          <li><a href="##" id="a_leader_txt">网站信息</a></li>
          <li><b>当前语言:</b><span style="color:red;">中文</php></span>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;切换语言:<a href="##">中文</a> &nbsp;&nbsp;<a href="##">英文</a> </li>
        </ul>
        <div>
          <iframe scrolling="auto" rameborder="0" src="info.jsp" name="right" width="100%" height="100%"></iframe>
        </div>
        <div style="text-align:center;">
        </div>
        </body>
        </html>
    
    

    reg.jsp

     <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
        <%
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        %>
        
        
        <!DOCTYPE html>
        <html>
        <head>
        <base href="<%=basePath%>">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        <meta name="renderer" content="webkit">
        <title></title>
        <link rel="stylesheet" href="css/pintuer.css">
        <link rel="stylesheet" href="css/admin.css">
        <script src="js/jquery.js"></script>
        <script src="js/pintuer.js"></script>
        </head>
        <body>
        <div class="panel admin-panel">
          <div><strong><span></span>新用户注册 </strong></div>
          <div>
            <form method="post" action="data">
            <input type="hidden" name="method" value="UserReg" />
                   
              <div>
                <div>
                  <label for="sitename">用户名:</label>
                </div>
                <div>
                  <input type="text" class="input w50" id="mpass" name="uname" size="50" placeholder="请输入新用户名" data-validate="required:请输入原始密码" />       
                </div>
              </div>      
              <div>
                <div>
                  <label for="sitename">新密码:</label>
                </div>
                <div>
                  <input type="password" class="input w50" name="pwd" size="50" placeholder="请输入新密码" data-validate="required:请输入新密码,length#>=5:新密码不能小于5位" />         
                </div>
              </div>
              <div>
                <div>
                  <label for="sitename">确认新密码:</label>
                </div>
                <div>
                  <input type="password" class="input w50" name="" size="50" placeholder="请再次输入新密码" data-validate="required:请再次输入新密码,repeat#pwd:两次输入的密码不一致" />          
                </div>
              </div>
               <div style="position:relative;left:100px; top:-10px">
               性别:男<input type="radio" name="sex" value="" checked="checked"><input type="radio" name="sex" value="" >
               </div>
               <!-- 年龄 -->
               <div>
                <div>
                  <label for="sitename">年龄:</label>
                </div>
                <div>
                  <input type="text" class="input w50" id="mpass" name="age" size="50" placeholder="请输入年龄"  />       
                </div>
              </div>      
                <!-- 出生日期 -->
              <div>
                <div>
                  <label for="sitename">出生日期:</label>
                </div>
                <div>
                  <input type="date" class="input w50" id="mpass" name="birthday" size="50"  />       
                </div>
                
              </div>      
              <div>
                <div>
                  <label></label>
                </div>
                <div>
                  <button class="button bg-main icon-check-square-o" type="submit"> 提交</button>   
                </div>
              </div>      
            </form>
          </div>
        </div>
        </body></html>
    

    运行结果

    在这里插入图片描述

    四、bug以及心得体会

    1、bug:由于粗心引起的bug,均已改正。

    2、心得与体会

    很多时候出现的bug,都是因为自己粗心所导致的。例如页面无法跳转多半是因为重定向的路径没有写对、或者form表单的action没写对、亦或是href后的路径没有写对,要特别注意。

    ​在一开始时,每个请求或独立的业务逻辑(登陆、退出、注册)都要单独使用一个Servlet进行处理。但随着网站功能的增多,Servlet增多导致资源浪费,需要我们进一步的优化。使用反射动态调用其功能处理方法,并将相关的Servlet集成在一个Servlet上。

    虽然使用了反射集成了一个独立的业务逻辑,但是反射不会只使用一次,需要我们在一些Servlet中的service方法中的反射代码声明一遍,然后使用时直接继承声明该反射代码的类。而且,该类最好不能被访问到(删除相应的url-pattern),最好不能被实例化(声明为抽象类)。

    ​刚接触JavaEE项目,需要掌握的知识点很多而且很杂,学起来比较吃力。但是这些零碎的知识点恰恰是今后做项目的基础。我还在不断花费时间去吸收、去归纳这些知识,相信通过本次的学习,我能够更加轻松的掌握这些知识!

    五、项目源码及压缩包

    关注后私信回复 [ servlet ], 即可获取源码哦~~~


    https://pan.baidu.com/s/1ylOi3PXFy6nwoOyVGVrBeg?pwd=yvsn

    更多相关内容
  • 项目基于jsp+servlet+jdbc的青年志愿者信息管理系统-可用于大学生日常课设 1.开发技术:jsp+servlet+jdbc 4.功能点描述: 系统的需求背景 学校拟开发一套青年志愿者信息管理系统,实现青年志愿者档案信息的管理...
  • 基于jsp+servlet的小米商城项目 。如有问题,请联系1666194196 包含购物车页面的实现,通过邮箱验证注册、通过邮箱找回密码、登录,记住密码,分页,按名称搜索商品等功能 运行环境:jdk7+tomcat7+mysql+MyEclipse ...
  • 基于JSP+Servlet项目

    2016-12-29 18:26:28
    自己做的小项目
  • 简介:本项目是javaweb最佳实践,用到一些诸如servlet的最基础的知识。欢迎star。。环境:jdk:jdk1.8.0_121,tomcat:tomcat8.0.52需要了解的知识点:​html,css,JavaScript,jquery等前端基础;java基础;​简单...
  • 基于jsp&servlet开发的购物车项目,有利于初学者学习参考
  • 主要介绍了基于jsp+servlet实现的简单博客系统,以完整实例形式分析了基于jsp+servlet简单博客系统的原理与相关技巧,并附带了完整源码供读者下载学习,需要的朋友可以参考下
  • 项目是一套基于servlet和jsp实现的学生信息管理系统,主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的Java学习者。 包含:项目源码、项目文档、数据库脚本、软件工具等,该项目附带全部源码可作为...
  • JavaWeb期末项目,一个基于JSP和Servlet的学生管理系统实现,前端用了bootstrap一些自定义的css样式,数据库使用mysql 登录页 学生管理 1.开发环境 idea 2018 jdk 1.8 tomcat 9.0 mysql 5.7 2.实现功能 登录(教师,...
  • 基于jsp+servlet的博客

    2015-07-04 17:20:55
    基于jsp的博客.zip,boke,.settings,org.eclipse.wst.jsdt.ui.superType.name,org.eclipse.wst.common.project.facet.core.xml,org.eclipse.wst.common.component,org.eclipse.wst.jsdt.ui.superType.container,....
  • 基于jsp servlet mysql实现的学生选课系统,系统分为教师学生两个角色,教师登录后可管理学生信息、课程信息、选课信息,设置必修学分的下限上限等功能,学生登录后可选课、查看自己选的课程、修改个人信息等...
  • jsp-servlet-课程一,基本情况1,项目jsp-servlet课程的配套示例2,doc目录下为教案3,项目基于servlet3.0规范。jdk环境为1.8,服务器为tomcat7二,第三方库排序第三方组件名称备注1个JSTL JSP标准标签库2个jsp ...
  • 项目名称:基于JSP+Servlet的户籍管理系统 用户类型:双角色(普通用户、管理员) 项目架构:B/S架构 设计思想:MVC 开发语言:Java语言 前端技术:Layui、HTML、CSS、JS、JQuery等技术 后端技术:JSP、Servlet、C3P...
  • 基于jsp+servlet+mysql实现的高校科研项目管理系统设计与项目实现
  • 这是一个myeclipse项目。使用了servletjsp,javabean,jdbc,mysql开发的一个小项目。第一次做的,并不完美,但基本功能都有
  • 项目: 新闻信息发布系统 Java Web项目,2015年4月应Java Web课程要求而设计的一个新闻信息系统。...主要使用JSP+Servlet+JavaBean+JDBC+DBCP技术实现;本人封装了JDBC,增加DBCP数据库连接池,从而可以控制事务。
  • 一个简单的java web项目,实现的借书、还书等功能,后台管理实现了用户的管理、新增图书、删除图书等功能。内含数据库文件。
  • JavaWeb期末项目,一个基于JSP和Servlet的学生管理系统实现,前端用了bootstrap一些自定义的css样式,数据库使用mysql
  • 这个项目基于jsp和servlet实现的手机商店,数据库采用mysql数据库,功能全面。
  • java项目-第88期基于jsp+servlet校园一卡通系统 1、项目简述 该项目是一款在学校的一卡通系统,学生可以注册一个卡,拿着这个电子卡就可以进行图书借阅,图书归还以及卡充值。 包含的功能有:个人信息、修改密码、...
  • 项目基于jsp+servlet+jdbc的学生请假信息管理系统-可用于大学生日常课设 1.后端开发技术:servlet+jdbc 2.前端技术:jsp 3.前端ui:经典蓝色ui 4.功能点描述: (1)学生 查看个人信息、查看个人的晚归记录、填写...
  • jsp+servlet+mysql+学生选课.rar,jsp+servlet+mysql+学生选课,源码,Ten,WebContent,style_1.css,img,StudentSelection.png,login_bg.png,Slogo.png,login_bg1.jpg,login_bg.jpeg,touxiang.png,META-INF,MANIFEST.MF,...
  • Java项目之音乐网站项目的源代码,Java项目之音乐网站项目中涉及并使用的技术为(JSP+SERVLET),如果有需要的小伙伴们,可以下载此项目做一个技术参考。
  • 基于JSP+servlet+MYSQL的Javaweb项目

    千次阅读 2021-03-24 16:00:55
    线索1.Controller2.Service3.dao5.Tran1.jsp文件6.listener总结 前言 CRM项目是寒假在家跟着视频做的一个项目,这个项目可以巩固之前Java基础以及javaweb的一些知识.途中也遇到了各种各样的问题,可以提


    前言

    CRM项目是寒假在家跟着视频做的一个项目,这个项目可以巩固之前Java基础以及javaweb的一些知识.途中也遇到了各种各样的问题,可以提高自己解决问题的能力.


    提示:以下是本篇文章正文内容,下面案例可供参考

    一、项目介绍

    crm项目是一个基于JSP+servlet+MySQL等技术的一个小型项目,项目功能是通过市场活动获得线索信息,然后将线索中的信息转化为客户信息和联系人信息并且可以创建交易记录,难点在于线索信息的转化以及交易阶段图标的改变.虽然是跟着视频做的,但是也是收获满满,尤其感受到了JSP+原生servlet的繁琐之处.并且这个项目中还有好多不足.

    二、样品实例

    1.市场活动界面

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    2.线索界面

    在这里插入图片描述
    点击名称进入详细信息页
    在这里插入图片描述
    点击转化即可把线索转换为联系人客户交易页,可以添加一条线索
    在这里插入图片描述

    交易页点击名称进入详细信息页
    在这里插入图片描述
    点击图标可以更改可能性阶段以及图标样式颜色
    在这里插入图片描述
    在这里插入图片描述

    三、代码

    代码如下:

    1.pom文件

    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.bjpowernode.crm</groupId>
      <artifactId>crm</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>war</packaging>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <dependencies>
    
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
        </dependency>
    
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>4.0.1</version>
          <scope>provided</scope>
        </dependency>
    
        <dependency>
          <groupId>javax.servlet.jsp</groupId>
          <artifactId>jsp-api</artifactId>
          <version>2.1.3-b06</version>
          <scope>provided</scope>
        </dependency>
    
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.4.5</version>
        </dependency>
    
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
        </dependency>
    
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.0.1</version>
        </dependency>
    
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.0.0</version>
        </dependency>
    
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.23</version>
        </dependency>
    
        <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.17</version>
        </dependency>
    
      </dependencies>
      <build>
        <resources>
          <resource>
            <directory>src/main/resources</directory>
            <includes>
              <include>**/*.*</include>
            </includes>
          </resource>
    
    
          <resource>
            <directory>src/main/java</directory>
            <includes>
              <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
          </resource>
        </resources>
      </build>
    </project>
    

    2.web.xml文件

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
      <display-name>crm</display-name>
    <!--  欢迎页-->
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
      </welcome-file-list><filter>
    <!--  登录拦截器-->
      <filter-name>LoginFilter</filter-name>
      <filter-class>com.bjpowernode.crm.web.filter.LoginFilter</filter-class>
    </filter>
      <filter-mapping>
        <filter-name>LoginFilter</filter-name>
        <url-pattern>*.do</url-pattern>
      </filter-mapping>
    <!--  字符编码拦截器-->
      <filter>
        <filter-name>LanJiefilter</filter-name>
        <filter-class>com.bjpowernode.crm.web.filter.LanJiefilter</filter-class>
      </filter>
    <filter-mapping>
      <filter-name>LanJiefilter</filter-name>
      <url-pattern>*.do</url-pattern>
      <url-pattern>*.jsp</url-pattern>
    </filter-mapping>
    <!--  监听器-->
      <listener>
        <listener-class>com.bjpowernode.crm.web.listener.SysInitListener</listener-class>
      </listener>
    
      <servlet>
        <servlet-name>UserController</servlet-name>
        <servlet-class>com.bjpowernode.crm.settings.web.controller.UserController</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>UserController</servlet-name>
        <url-pattern>/settings/user/login.do</url-pattern>
      </servlet-mapping>
    
      <servlet>
        <servlet-name>ActivityController</servlet-name>
        <servlet-class>com.bjpowernode.crm.workbench.web.controller.ActivityController</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>ActivityController</servlet-name>
        <url-pattern>/workbench/Activity/getUserList.do</url-pattern>
        <url-pattern>/workbench/Activity/save.do</url-pattern>
        <url-pattern>/workbench/Activity/search.do</url-pattern>
        <url-pattern>/workbench/Activity/delete.do</url-pattern>
        <url-pattern>/workbench/Activity/edit.do</url-pattern>
        <url-pattern>/workbench/Activity/update.do</url-pattern>
      </servlet-mapping>
      <servlet>
        <servlet-name>ClueController</servlet-name>
        <servlet-class>com.bjpowernode.crm.workbench.web.controller.ClueController</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>ClueController</servlet-name>
        <url-pattern>/workbench/Clue/getUserList.do</url-pattern>
        <url-pattern>/workbench/Clue/save.do</url-pattern>
        <url-pattern>/workbench/Clue/detail.do</url-pattern>
        <url-pattern>/workbench/Clue/showActivityListByClueId.do</url-pattern>
        <url-pattern>/workbench/Clue/unbund.do</url-pattern>
        <url-pattern>/workbench/Clue/getActivityListByClueIdAndName.do</url-pattern>
        <url-pattern>/workbench/Clue/setBundById.do</url-pattern>
        <url-pattern>/workbench/Clue/getActivityListByName.do</url-pattern>
        <url-pattern>/workbench/Clue/convert.do</url-pattern>
      </servlet-mapping>
      <servlet>
        <servlet-name>TranController</servlet-name>
        <servlet-class>com.bjpowernode.crm.workbench.web.controller.TranController</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>TranController</servlet-name>
        <url-pattern>/workbench/transaction/search.do</url-pattern>
        <url-pattern>/workbench/transaction/detail.do</url-pattern>
        <url-pattern>/workbench/transaction/changeStage.do</url-pattern>
    
      </servlet-mapping>
    
    
    </web-app>
    

    3.市场活动

    1.Controller

    package com.bjpowernode.crm.workbench.web.controller;
    
    import com.bjpowernode.crm.settings.domain.User;
    import com.bjpowernode.crm.settings.service.UserService;
    import com.bjpowernode.crm.settings.service.impl.UserServiceImpl;
    import com.bjpowernode.crm.utils.*;
    import com.bjpowernode.crm.vo.PaginationVo;
    import com.bjpowernode.crm.workbench.domain.Activity;
    import com.bjpowernode.crm.workbench.service.ActivityService;
    import com.bjpowernode.crm.workbench.service.impl.ActivityServiceImpl;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class ActivityController extends HttpServlet {
        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("进入到市场活动");
            String path = request.getServletPath();
            if("/workbench/Activity/getUserList.do".equals(path)){
                getUserList(request,response);
    
            }else if("/workbench/Activity/save.do".equals(path)){
                save(request,response);
    
            }else if("/workbench/Activity/search.do".equals(path)){
                pageList(request,response);
            }else if("/workbench/Activity/delete.do".equals(path)){
                delete(request,response);
            }else if("/workbench/Activity/edit.do".equals(path)){
                edit(request,response);
            }else if("/workbench/Activity/update.do".equals(path)){
                update(request,response);
            }
    
        }
    
        private void update(HttpServletRequest request, HttpServletResponse response) {
            System.out.println("进入修改界面");
            String owner  =request.getParameter("owner");
            String name =request.getParameter("name");
            String startTime =request.getParameter("startTime");
            String endTime =request.getParameter("endTime");
            String cost =request.getParameter("cost");
            String description =request.getParameter("describe");
            String id =request.getParameter("id");
    
            String editTime=DateTimeUtil.getSysTime();
            String editBy=((User)request.getSession().getAttribute("user")).getName();
            String owner2=((User)request.getSession().getAttribute("user")).getId();
            Activity activity=new Activity();
            activity.setOwner(owner2);
            activity.setCreateBy(owner);
            activity.setName(name);
            activity.setStartDate(startTime);
            activity.setEndDate(endTime);
            activity.setCost(cost);
            activity.setDescription(description);
            activity.setId(id);
            activity.setEditTime(editTime);
            activity.setEditBy(editBy);
            ActivityService as= (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());
            int result=as.update(activity);
            PrintJson.printJsonObj(response,result);
    
        }
    
        private void edit(HttpServletRequest request, HttpServletResponse response) {
            System.out.println("进入edit界面");
            String id=request.getParameter("id");
            ActivityService as = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());
    
            Map map=new HashMap();
            map=as.getedit(id);
            PrintJson.printJsonObj(response,map);
    
        }
    
        private void delete(HttpServletRequest request, HttpServletResponse response) {
            System.out.println("进入删除界面");
            String[] ids=request.getParameterValues("id");
            ActivityService as = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());
            boolean flag=as.delete(ids);
            PrintJson.printJsonObj(response,flag);
        }
    
        private void pageList(HttpServletRequest request, HttpServletResponse response) {
            System.out.println("进入分页查询");
            ActivityService as= (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());
            Map map=new HashMap();
            int pageSize=Integer.valueOf(request.getParameter("pageSize"));
            int pageNo=Integer.valueOf(request.getParameter("pageNo"));
            int skipCount=(pageNo-1)*pageSize;
            map.put("skipCount",skipCount);
            map.put("pageSize",pageSize);
            map.put("name",request.getParameter("name"));
            map.put("owner",request.getParameter("owner"));
            map.put("startTime",request.getParameter("startTime"));
            map.put("endTime",request.getParameter("endTime"));
            PaginationVo<Activity> vo=as.pageList(map);
            //int total=as.pageCount(map);
            PrintJson.printJsonObj(response,vo);
    
    
    
        }
    
        private void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
            Activity activity=new Activity();
            String id= UUIDUtil.getUUID();
            System.out.println("进入到添加市场活动");
            String owner=request.getParameter("owner");
            String name=request.getParameter("name");
            String startDate=request.getParameter("startDate");
            String endDate=request.getParameter("endDate");
            String cost=request.getParameter("cost");
            String description=request.getParameter("description");
            String createby=((User)request.getSession().getAttribute("user")).getName();
            System.out.println(activity);
            activity.setCost(cost);
            activity.setStartDate(startDate);
            activity.setEndDate(endDate);
            activity.setDescription(description);
            activity.setOwner(owner);
            activity.setName(name);
            activity.setId(id);
            activity.setCreateTime(DateTimeUtil.getSysTime());
            activity.setCreateBy(createby);
            ActivityService as= (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());
            boolean success=as.save(activity);
            response.getWriter().print(success);
    
    
        }
    
        private void getUserList(HttpServletRequest request, HttpServletResponse response) {
            System.out.println("取得用户信息表");
    
            UserService us= (UserService) ServiceFactory.getService(new UserServiceImpl());
            List<User> ulist=us.getUserList();
            PrintJson.printJsonObj(response,ulist);
        }}
    
    

    2.Service实现类

    package com.bjpowernode.crm.workbench.service.impl;
    
    import com.bjpowernode.crm.settings.dao.UserDao;
    import com.bjpowernode.crm.utils.SqlSessionUtil;
    import com.bjpowernode.crm.vo.PaginationVo;
    import com.bjpowernode.crm.workbench.dao.ActivityRemarkDao;
    import com.bjpowernode.crm.workbench.dao.ActivityDao;
    import com.bjpowernode.crm.workbench.domain.Activity;
    import com.bjpowernode.crm.workbench.service.ActivityService;
    
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class ActivityServiceImpl implements ActivityService {
        private UserDao userDao=SqlSessionUtil.getSqlSession().getMapper(UserDao.class);
        private ActivityDao activityDao= SqlSessionUtil.getSqlSession().getMapper(ActivityDao.class);
        private ActivityRemarkDao activityRemarkDao= SqlSessionUtil.getSqlSession().getMapper(ActivityRemarkDao.class);
    
        public boolean save(Activity activity) {
            int result=activityDao.save(activity);
            if (result !=1) {
                return false;
    
            }
            return true;
        }
        public PaginationVo<Activity> pageList(Map map) {
            PaginationVo<Activity> vo=new PaginationVo<Activity>();
            vo.setDataList(activityDao.getActivityListByCondition(map));
            vo.setTotal(activityDao.getTotalByCondition(map));
    
            return vo;
        }
        public boolean delete(String[] ids) {
            int count1=activityRemarkDao.getCountByids(ids);
            int count2=activityRemarkDao.deleteByids(ids);
            boolean flag = true;
            if(count1!=count2){
                flag=false;
            }
            int count3=activityDao.delete(ids);
            if(count3!=ids.length){
                flag=false;
            }
            return flag;
        }
        public List getActivityListByName(String name) {
            List list=activityDao.getActivityListByName(name);
            return list;
        }
    
        public Map getedit(String id) {
            List ulist=userDao.getUserList();
            Activity activity=activityDao.editById(id);
            Map map=new HashMap();
            map.put("ulist",ulist);
            map.put("activity",activity);
            return map;
        }
        public int update(Activity activity) {
            int result =activityDao.update(activity);
            return result;
        }
    
        public List getActivityListByClueIdAndName(Map map) {
            List alist=activityDao.getActivityListByClueIdAndName(map);
            return alist;
        }
    }
    

    3.dao.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
     PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
     "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.bjpowernode.crm.workbench.dao.ActivityDao">
        <delete id="delete">
            delete from tbl_activity
            where id in
            <foreach collection="array" open="(" close=")" item="aid" separator=",">
                 #{aid}
            </foreach>
        </delete>
        <select id="editById" resultType="com.bjpowernode.crm.workbench.domain.Activity">
            select * from tbl_activity where id=#{id}
        </select>
    
        <update id="update">
            update tbl_activity
            set owner  =#{owner},
                name =#{name},
                startDate =#{startDate},
                endDate  =#{endDate},
                cost  =#{cost},
                description =#{description},
                editTime=#{editTime},
                editBy=#{editBy}
               where id=#{id}
        </update>
    
        <insert id="save">
            insert into tbl_activity (
            id,
            owner,
            name,
            startDate,
            endDate,
            cost,
            description,
            createBy,
            createTime
    
            )values (
            #{id},
            #{owner},
            #{name},
            #{startDate},
            #{endDate},
            #{cost},
            #{description},
            #{createBy},
            #{createTime}
            );
        </insert>
    
        <select id="getActivityListByCondition" resultType="com.bjpowernode.crm.workbench.domain.Activity">
            select
            u.name as owner,
            a.startDate,
            a.id,
            a.endDate,
            a.name
            from tbl_activity a
            join tbl_user u
            on u.id=a.owner
            <where>
                <if test="name!=null and name !=''">
                a.name like '%' #{name} '%'
    
                </if>
    
                <if test="owner!=null and owner !=''">
                    u.name like '%' #{owner} '%'
    
                </if>
    
                <if test="stratTime != null and startTime !=''">
                    a.startDate &gt; #{startTime}
    
                </if>
    
                <if test="endTime != null and endTime !=''">
                a.endDate &lt; #{endTime}
                </if>
    
    
            </where>
            order by a.createTime desc
            limit #{skipCount},#{pageSize}
        </select>
        
        <select id="getTotalByCondition" resultType="int">
            select count(*)
            from tbl_activity a
            join tbl_user u
            on u.id=a.owner
            <where>
                <if test="name!=null and name !=''">
                    a.name like '%' #{name} '%'
    
                </if>
    
                <if test="owner!=null and owner !=''">
                    u.name like '%' #{owner} '%'
    
                </if>
    
                <if test="stratTime != null and startTime !=''">
                    a.startDate &gt; #{startTime}
    
                </if>
    
                <if test="endTime != null and endTime !=''">
                    a.endDate &lt; #{endTime}
                </if>
    
    
            </where>
            order by a.createTime desc;
    
        </select>
        <select id="getActivityListByClueIdAndName" resultType="Activity">
            select
            a.id,
            a.name,
            a.startDate,
            a.endDate,
            u.name as owner
            from tbl_activity a
            join tbl_user u
            on u.id=a.owner
            where a.name like '%' #{aname} '%'
            and a.id not in(
            select
                activityid
                from tbl_clue_activity_relation
                where clueId=#{clueId}
            )
        </select>
        <select id="getActivityListByName" resultType="Activity">
             select
            a.id,
            a.name,
            a.startDate,
            a.endDate,
            u.name as owner
            from tbl_activity a
            join tbl_user u
            on u.id=a.owner
            where a.name like '%' #{aname} '%'
        </select>
    </mapper>
    

    市场活动是做的最全的增删改查,其中包括分页查询,条件查询,模糊查询等.

    4.线索

    1.Controller

    package com.bjpowernode.crm.workbench.web.controller;
    
    import com.bjpowernode.crm.settings.domain.User;
    import com.bjpowernode.crm.settings.service.UserService;
    import com.bjpowernode.crm.settings.service.impl.UserServiceImpl;
    import com.bjpowernode.crm.utils.DateTimeUtil;
    import com.bjpowernode.crm.utils.PrintJson;
    import com.bjpowernode.crm.utils.ServiceFactory;
    import com.bjpowernode.crm.utils.UUIDUtil;
    import com.bjpowernode.crm.workbench.domain.Clue;
    import com.bjpowernode.crm.workbench.domain.Tran;
    import com.bjpowernode.crm.workbench.service.ActivityService;
    import com.bjpowernode.crm.workbench.service.ClueService;
    import com.bjpowernode.crm.workbench.service.impl.ActivityServiceImpl;
    import com.bjpowernode.crm.workbench.service.impl.ClueServiceImpl;
    
    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 java.io.IOException;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    
    public class ClueController extends HttpServlet {
        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("进入到市场活动");
            String path = request.getServletPath();
            if("/workbench/Clue/getUserList.do".equals(path)){
                getUserList(request,response);
            }else if("/workbench/Clue/save.do".equals(path)){
                save(request,response);
            }else if("/workbench/Clue/detail.do".equals(path)){
                getClueById(request,response);
            }else if("/workbench/Clue/showActivityListByClueId.do".equals(path)){
                showActivityListByClueId(request,response);
            }else if("/workbench/Clue/unbund.do".equals(path)){
                unbund(request,response);
            }else if("/workbench/Clue/getActivityListByClueIdAndName.do".equals(path)){
                getActivityListByClueIdAndName(request,response);
            }else if("/workbench/Clue/setBundById.do".equals(path)){
                bund(request,response);
            }else if("/workbench/Clue/getActivityListByName.do".equals(path)){
                getActivityListByName(request,response);
            }else if("/workbench/Clue/convert.do".equals(path)){
                convert(request,response);
            }
    
        }
    
        private void convert(HttpServletRequest request, HttpServletResponse response) throws IOException {
            System.out.println("开始转换");
            String a=request.getParameter("a");
            Tran t=null;
            String clueId=request.getParameter("clueId");
            User user= (User) request.getSession().getAttribute("user");
            String createBy=user.getCreateBy();
            if("a".equals(a)){
                t=new Tran();
                String money=request.getParameter("money");
                String name=request.getParameter("name");
                String expectedDate=request.getParameter("expectedDate");
                String stage=request.getParameter("stage");
                String activityId=request.getParameter("activityId");
                t.setMoney(money);
                t.setName(name);
                t.setExpectedDate(expectedDate);
                t.setStage(stage);
                t.setActivityId(activityId);
                t.setId(UUIDUtil.getUUID());
                t.setCreateTime(DateTimeUtil.getSysTime());
                t.setCreateBy(((User)request.getSession().getAttribute("user")).getName());
                
            }
            ClueService cs= (ClueService) ServiceFactory.getService(new ClueServiceImpl());
            boolean flag=cs.convert(t,clueId,createBy);
    
            if(flag){
                response.sendRedirect(request.getContextPath()+"/workbench/clue/index.jsp");
            }
        }
    
        private void getActivityListByName(HttpServletRequest request, HttpServletResponse response) {
            System.out.println();
            String name=request.getParameter("name");
            ActivityService as= (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());
            List list=as.getActivityListByName(name);
            PrintJson.printJsonObj(response,list);
    
        }
    
        private void bund(HttpServletRequest request, HttpServletResponse response) {
            System.out.println("进入关联界面");
            String cid=request.getParameter("cid");
            String[] aids=request.getParameterValues("aid");
            ClueService cs= (ClueService) ServiceFactory.getService(new ClueServiceImpl());
            boolean success=cs.bund(aids,cid);
            PrintJson.printJsonObj(response,success);
        }
    
        private void getActivityListByClueIdAndName(HttpServletRequest request, HttpServletResponse response) {
            String clueId=request.getParameter("id");
            String aname=request.getParameter("aname");
            Map map= new HashMap();
            map.put("clueId",clueId);
    
            map.put("aname",aname);
            ActivityService as= (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());
            List alist=as.getActivityListByClueIdAndName(map);
            PrintJson.printJsonObj(response,alist);
    
        }
    
        private void unbund(HttpServletRequest request, HttpServletResponse response) {
            System.out.println("进入删除关联界面");
            String id=request.getParameter("id");
            ClueService cs= (ClueService) ServiceFactory.getService(new ClueServiceImpl());
            boolean success=cs.unbund(id);
            PrintJson.printJsonObj(response,success);
    
        }
    
        private void showActivityListByClueId(HttpServletRequest request, HttpServletResponse response) {
            System.out.println("");
            String clueId=request.getParameter("clueId");
            ClueService cs= (ClueService) ServiceFactory.getService(new ClueServiceImpl());
            List alist=cs.showActivityListByClueId(clueId);
            PrintJson.printJsonObj(response,alist);
    
        }
    
        private void getClueById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("进入详细信息页");
            String id=request.getParameter("id");
            System.out.println(id);
            ClueService cs= (ClueService) ServiceFactory.getService(new ClueServiceImpl());
            Clue clue=cs.getClueById(id);
            HttpSession session=request.getSession();
            session.setAttribute("c",clue);
    
            request.getRequestDispatcher("/workbench/clue/detail2.jsp").forward(request,response);
        }
    
        private void save(HttpServletRequest request, HttpServletResponse response) {
            System.out.println("进入添加操作页面");
            String id= UUIDUtil.getUUID();
            String fullname=request.getParameter("fullname");
            String appellation=request.getParameter("appellation");
            String owner=request.getParameter("owner");
            String company=request.getParameter("company");
            String job=request.getParameter("job");
            String email=request.getParameter("email");
            String phone=request.getParameter("phone");
            String website=request.getParameter("website");
            String mphone=request.getParameter("mphone");
            String state=request.getParameter("state");
            String source=request.getParameter("source");
            String createBy=((User)request.getSession().getAttribute("user")).getName();
            String createTime= DateTimeUtil.getSysTime();
            String editBy=request.getParameter("editBy");
            String editTime=request.getParameter("editTime");
            String description=request.getParameter("description");
            String contactSummary=request.getParameter("contactSummary");
            String nextContactTime=request.getParameter("nextContactTime");
            String address=request.getParameter("address");
            Clue clue=new Clue();
            clue.setAddress(address);
            clue.setAppellation(appellation);
            clue.setCompany(company);
            clue.setContactSummary(contactSummary);
            clue.setCreateBy(createBy);
            clue.setCreateTime(createTime);
            clue.setDescription(description);
            clue.setEditBy(editBy);
            clue.setEditTime(editTime);
            clue.setEmail(email);
            clue.setFullname(fullname);
            clue.setJob(job);
            clue.setMphone(mphone);
            clue.setNextContactTime(nextContactTime);
            clue.setOwner(owner);
            clue.setWebsite(website);
            clue.setSource(source);
            clue.setState(state);
            clue.setPhone(phone);
            clue.setId(id);
    
            ClueService cs= (ClueService) ServiceFactory.getService(new ClueServiceImpl());
            boolean success=cs.save(clue);
            PrintJson.printJsonObj(response,success);
        }
    
        private void getUserList(HttpServletRequest request, HttpServletResponse response) {
            System.out.println("进入用户获取界面");
            UserService us= (UserService) ServiceFactory.getService(new UserServiceImpl());
            List ulist=us.getUserList();
            PrintJson.printJsonObj(response,ulist);
    
        }
    }
    

    2.Service

    package com.bjpowernode.crm.workbench.service.impl;
    
    import com.bjpowernode.crm.utils.DateTimeUtil;
    import com.bjpowernode.crm.utils.SqlSessionUtil;
    import com.bjpowernode.crm.utils.UUIDUtil;
    import com.bjpowernode.crm.workbench.dao.*;
    import com.bjpowernode.crm.workbench.domain.*;
    import com.bjpowernode.crm.workbench.service.ClueService;
    
    import java.util.List;
    
    public class ClueServiceImpl implements ClueService {
        private ClueDao clueDao= SqlSessionUtil.getSqlSession().getMapper(ClueDao.class);
        private ClueRemarkDao clueRemarkDao=SqlSessionUtil.getSqlSession().getMapper(ClueRemarkDao.class);
        private ContactsActivityRelationDao contactsActivityRelationDao=SqlSessionUtil.getSqlSession().getMapper(ContactsActivityRelationDao.class);
        private ContactsDao contactsDao=SqlSessionUtil.getSqlSession().getMapper(ContactsDao.class);
        private ContactsRemarkDao contactsRemarkDao=SqlSessionUtil.getSqlSession().getMapper(ContactsRemarkDao.class);
        private TranDao tranDao=SqlSessionUtil.getSqlSession().getMapper(TranDao.class);
        private TranHistoryDao tranHistoryDao=SqlSessionUtil.getSqlSession().getMapper(TranHistoryDao.class);
        private TranRemark tranRemark=SqlSessionUtil.getSqlSession().getMapper(TranRemark.class);
        private CustomerDao customerDao=SqlSessionUtil.getSqlSession().getMapper(CustomerDao.class);
        private CustomerRemarkDao customerRemarkDao=SqlSessionUtil.getSqlSession().getMapper(CustomerRemarkDao.class);
        private ClueActivityRelationDao clueActivityRelationDao=SqlSessionUtil.getSqlSession().getMapper(ClueActivityRelationDao.class);
        public boolean bund(String[] aids, String cid) {
            int result=0;
            for (String aid:aids) {
                ClueActivityRelation car =new ClueActivityRelation();
                car.setActivityId(aid);
                car.setClueId(cid);
                car.setId(UUIDUtil.getUUID());
                result=clueActivityRelationDao.bund(car);
            }
    
            boolean success=false;
            if(result==1){
                success=true;
            }
            return success;
        }
    
        public boolean unbund(String id) {
            int result=clueActivityRelationDao.unbund(id);
            boolean success=false;
            if(result==1){
                success=true;
            }
            return success;
        }
    
        public List showActivityListByClueId(String clueId) {
    
            List alist=clueDao.showActivityListByClueId(clueId);
    
    
            return alist;
        }
    
        public boolean convert(Tran t, String clueId, String createBy) {
            boolean flag=true;
    
            //获取线索id获取线索对象
            Clue c=clueDao.getById(clueId);
            String company=c.getCompany();
    
            //根据公司查客户
            Customer customer=customerDao.getBycompany(company);
    
            if(customer==null){
                Customer cus=new Customer();
                cus.setId(UUIDUtil.getUUID());
                cus.setAddress(c.getAddress());
                cus.setContactSummary(c.getContactSummary());
                cus.setCreateBy(c.getCreateBy());
                cus.setCreateTime(DateTimeUtil.getSysTime());
                cus.setDescription(c.getDescription());
                cus.setEditBy(c.getEditBy());
                cus.setEditTime(c.getEditTime());
                cus.setName(c.getFullname());
                cus.setNextContactTime(c.getNextContactTime());
                cus.setOwner(c.getOwner());
                cus.setPhone(c.getPhone());
                cus.setWebsite(c.getWebsite());
                int count =customerDao.save(cus);
                if(count!=1){
                    flag=false;
                }
            }
    
            Contacts con=new Contacts();
            con.setId(UUIDUtil.getUUID());
            con.setAddress(c.getAddress());
            con.setAppellation(c.getAppellation());
            con.setContactSummary(c.getContactSummary());
            con.setCreateBy(c.getCreateBy());
            con.setCreateTime(c.getCreateTime());
            con.setDescription(c.getDescription());
            con.setEditBy(c.getEditBy());
            con.setEditTime(c.getEditTime());
            con.setEmail(c.getEmail());
            con.setFullname(c.getFullname());
            con.setJob(c.getJob());
            con.setMphone(c.getMphone());
            con.setNextContactTime(c.getNextContactTime());
            con.setOwner(c.getOwner());
            con.setSource(c.getSource());
            //con.setCustomerId(customer.getId());
            int count2=contactsDao.save(con);
            if(count2!=1){
                flag=false;
            }
            //查询线索备注
            List<ClueRemark> list=clueRemarkDao.getById(clueId);
            for(ClueRemark cr:list){
            CustomerRemark crk=new CustomerRemark();
            crk.setCreateBy(c.getCreateBy());
            crk.setCreateTime(c.getCreateTime());
            crk.setCustomerId(customer.getId());
            crk.setEditBy(c.getEditBy());
            crk.setEditFlag("0");
            crk.setId(UUIDUtil.getUUID());
            crk.setNoteContent(cr.getNoteContent());
            int count4=customerRemarkDao.save(crk);
            if(count4!=1){
                flag=false;
            }ContactsRemark cok=new ContactsRemark();
                cok.setCreateBy(c.getCreateBy());
                cok.setCreateTime(c.getCreateTime());
                cok.setContactsId(con.getId());
                cok.setEditBy(c.getEditBy());
                cok.setEditFlag("0");
                cok.setId(UUIDUtil.getUUID());
                cok.setNoteContent(cr.getNoteContent());
                int count5=contactsRemarkDao.save(cok);
                if(count4!=1){
                    flag=false;
                }
    
            }
            //线索市场活动关系转换
            List<ClueActivityRelation> clueActivityRelationList=clueActivityRelationDao.getById(clueId);
            for(ClueActivityRelation car:clueActivityRelationList){
                String activityId=car.getActivityId();
                ContactsActivityRelation cor=new ContactsActivityRelation();
                cor.setId(UUIDUtil.getUUID());
                cor.setActivityId(activityId);
                cor.setContactsId(con.getId());
                int count5=contactsActivityRelationDao.save(cor);
                if(count5!=1){
                    flag=false;
                }
            }
            if(t!=null){
                int count6=tranDao.addtran(t);
                TranHistory th=new TranHistory();
                th.setCreateBy(t.getCreateBy());
                th.setCreateTime(t.getCreateTime());
                th.setExpectedDate(t.getExpectedDate());
                th.setId(UUIDUtil.getUUID());
                th.setMoney(t.getMoney());
                th.setStage(t.getStage());
                th.setTranId(t.getId());
                int count7=tranHistoryDao.addtranHistory(t);
                if(count6!=1){
                    flag=false;
                }if(count7!=1){
                    flag=false;
                }
            }
            if(flag){
                int a=clueActivityRelationDao.remove(clueId);
                int b=clueRemarkDao.remove(clueId);
                int d=clueDao.remove(clueId);
    
            }
            return flag;
        }
    
        public Clue getClueById(String id) {
            Clue clue=clueDao.getClueById(id);
    
            return clue;
        }
    
        public boolean save(Clue clue) {
            boolean success=false;
            int result=clueDao.save(clue);
            if(result==1){
                success=true;
            }
    
            return success;
        }
    }
    

    3.dao

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.bjpowernode.crm.workbench.dao.ClueDao">
        <insert id="save">
            insert into tbl_clue(
            id,
            fullname,
            appellation,
            owner,
            company,
            job,
            email,
            phone,
            website,
            mphone,
            state,
            source,
            createBy,
            createTime,
            editBy,
            editTime,
            description,
            contactSummary,
            nextContactTime,
            address
            )values (
            #{id},
            #{fullname},
            #{appellation},
            #{owner},
            #{company},
            #{job},
            #{email},
            #{phone},
            #{website},
            #{mphone},
            #{state},
            #{source},
            #{createBy},
            #{createTime},
            #{editBy},
            #{editTime},
            #{description},
            #{contactSummary},
            #{nextContactTime},
            #{address}
    
            )
    
    
        </insert>
        <select id="getClueById" resultType="Clue">
            select
            c.id,
            c.fullname,
            c.appellation,
            u.name as owner,
            c.company,
            c.job,
            c.email,
            c.phone,
            c.website,
            c.mphone,
            c.state,
            c.source,
            c.createBy,
            c.createTime,
            c.editBy,
            c.editTime,
            c.description,
            c.contactSummary,
            c.nextContactTime,
            c.address
            from tbl_clue c
            join tbl_user u
            on c.owner=u.id
            where c.id=#{id}
        </select>
        <select id="showActivityListByClueId" resultType="Activity">
            select
            car.id as id,
            a.name,
            a.startDate,
            a.endDate,
            u.name as owner
    
    
            from tbl_activity a
            join tbl_user u
            on  u.id=a.owner
            join tbl_clue_activity_relation car
            on a.id=car.activityId
            where car.clueId=#{clueId}
    
        </select>
        <select id="getById" resultType="Clue">
            select * from tbl_clue where id=#{id}
        </select>
    
        <delete id="remove">
            delete from tbl_clue
            where id=#{id}
        </delete>
    	
    	
      	
    </mapper>
    

    其实最主要的部分都在Clue线索阶段.

    5.Tran

    1.jsp文件

    <script type="text/javascript" src="jquery/jquery-1.11.1-min.js"></script>
    <script type="text/javascript" src="jquery/bootstrap_3.3.0/js/bootstrap.min.js"></script>
    
    <script type="text/javascript">
    
    	//默认情况下取消和保存按钮是隐藏的
    	var cancelAndSaveBtnDefault = true;
    	
    	$(function(){
    		$("#remark").focus(function(){
    			if(cancelAndSaveBtnDefault){
    				//设置remarkDiv的高度为130px
    				$("#remarkDiv").css("height","130px");
    				//显示
    				$("#cancelAndSaveBtn").show("2000");
    				cancelAndSaveBtnDefault = false;
    			}
    		});
    		
    		$("#cancelBtn").click(function(){
    			//显示
    			$("#cancelAndSaveBtn").hide();
    			//设置remarkDiv的高度为130px
    			$("#remarkDiv").css("height","90px");
    			cancelAndSaveBtnDefault = true;
    		});
    		
    		$(".remarkDiv").mouseover(function(){
    			$(this).children("div").children("div").show();
    		});
    		
    		$(".remarkDiv").mouseout(function(){
    			$(this).children("div").children("div").hide();
    		});
    		
    		$(".myHref").mouseover(function(){
    			$(this).children("span").css("color","red");
    		});
    		
    		$(".myHref").mouseout(function(){
    			$(this).children("span").css("color","#E6E6E6");
    		});
    		
    		
    		//阶段提示框
    		$(".mystage").popover({
                trigger:'manual',
                placement : 'bottom',
                html: 'true',
                animation: false
            }).on("mouseenter", function () {
                        var _this = this;
                        $(this).popover("show");
                        $(this).siblings(".popover").on("mouseleave", function () {
                            $(_this).popover('hide');
                        });
                    }).on("mouseleave", function () {
                        var _this = this;
                        setTimeout(function () {
                            if (!$(".popover:hover").length) {
                                $(_this).popover("hide")
                            }
                        }, 100);
                    });
    	});
    	$(function () {
    
    
    
    
    	})
    
    	function changeStage(stage,i) {
    
    		$.ajax({
    
    			url : "workbench/transaction/changeStage.do",
    			data : {
    
    				"id" : "${t.id}",
    				"stage" : stage,
    				"money" : "${t.money}",
    				"expectedDate" : "${t.expectedDate}"
    
    			},
    			type : "post",
    			dataType : "json",
    			success : function (data) {
    
    
    				if(data.success){
    
    					//改变阶段成功后刷新阶段,可能性,修改人,修改时间
    
    					$("#stage").html(data.t.stage);
    					$("#posssibility").html(data.t.posssibility);
    					$("#editBy").html(data.t.editBy);
    					$("#editTime").html(data.t.editTime);
    
    					//改变阶段成功后重新判断
    
    					changeIcon(stage,i);
    
    				}else{
    
    
    					alert("改变阶段失败");
    
    				}
    
    
    			}
    
    		})
    
    
    	}
    	function changeIcon(stage,index1) {
    
    		//当前阶段
    		var currentStage = stage;
    		//当前阶段可能性
    		var currentPossibility = $("#possibility").html();
    		//当前阶段的下标
    		var index = index1;
    		//前面正常阶段和后面丢失阶段的分界点下标
    		var point = "<%=point%>";
    
    
    		//前7个一定是黑圈,后两个一个是红叉,一个是黑叉
    		if(currentPossibility=="0"){
    
    			//遍历前7个
    			for(var i=0;i<point;i++){
    
    				//黑圈
    				//移除掉原有的样式
    				$("#"+i).removeClass();
    				//添加新样式
    				$("#"+i).addClass("glyphicon glyphicon-record mystage");
    				//为新样式赋予颜色
    				$("#"+i).css("color","#000000");
    
    			}
    
    			//遍历后两个
    			for(var i=point;i<<%=dvList.size()%>;i++){
    
    				//如果是当前阶段
    				if(i==index){
    
    					//红叉-----------------------------
    					$("#"+i).removeClass();
    					$("#"+i).addClass("glyphicon glyphicon-remove mystage");
    					$("#"+i).css("color","#FF0000");
    
    					//如果不是当前阶段
    				}else{
    
    					//黑叉
    					$("#"+i).removeClass();
    					$("#"+i).addClass("glyphicon glyphicon-remove mystage");
    					$("#"+i).css("color","#000000");
    
    				}
    
    
    			}
    
    			//前7个绿圈,绿色标记,黑圈,后两个一定是黑叉
    		}else{
    
    			//遍历前7个 绿圈,绿色标记,黑圈
    			for(var i=0;i<point;i++){
    
    				//如果是当前阶段
    				if(i==index){
    					//绿色标记
    					$("#"+i).removeClass();
    					$("#"+i).addClass("glyphicon glyphicon-map-marker mystage");
    					$("#"+i).css("color","#90F790");
    					//如果小于当前阶段
    				}else if(i<index){
    
    					//绿圈
    					$("#"+i).removeClass();
    					$("#"+i).addClass("glyphicon glyphicon-ok-circle mystage");
    					$("#"+i).css("color","#90F790");
    
    					//如果大于当前阶段
    				}else{
    
    					//黑圈-
    					$("#"+i).removeClass();
    					$("#"+i).addClass("glyphicon glyphicon-record mystage");
    					$("#"+i).css("color","#000000");
    
    				}
    
    
    			}
    
    			//遍历后两个
    			for(var i=point;i<<%=dvList.size()%>;i++){
    
    				//黑叉
    				$("#"+i).removeClass();
    				$("#"+i).addClass("glyphicon glyphicon-remove mystage");
    				$("#"+i).css("color","#000000");
    			}
    
    		}
    
    
    	}
    	
    </script>
    
    <div style="position: relative; left: 40px; top: -50px;">
    		<%
    			Tran t= (Tran) request.getAttribute("t");
    			String currentStage=t.getStage();
    			String currentpossibility=pMap.get(currentStage);
    			//如果当前阶段可能性为0 前面都黑圈 最后俩一个红叉
    			if("0".equals(currentpossibility)){
    				for (int i = 0; i < dvList.size(); i++) {
    
    					DicValue dv=dvList.get(i);
    					String listStage=dv.getValue();
    					String listPossibility=pMap.get(listStage);
    					//后俩
    					if("0".equals(listPossibility)){
    						if(listPossibility.equals(currentpossibility)){
    							//红叉
    		%>
    		<span id="<%=i%>" onclick="changeStage('<%=listStage%>','<%=i%>')"
    			  class="glyphicon glyphicon-remove mystage"
    			  data-toggle="popover" data-placement="bottom"
    			  data-content="<%=dv.getText()%>" style="color: #FF0000;"></span>
    		-----------
    
    		<%
    
    						}else{
    							//黑×
    							//黑叉-----------------------------------------
    		%>
    
    		<span id="<%=i%>" onclick="changeStage('<%=listStage%>','<%=i%>')"
    			  class="glyphicon glyphicon-remove mystage"
    			  data-toggle="popover" data-placement="bottom"
    			  data-content="<%=dv.getText()%>" style="color: #000000;"></span>
    		-----------
    
    		<%
    
    						}
    
    
    						//前7个
    					}else{
    							//黑圈-----------------------------------------
    		%>
    
    		<span id="<%=i%>" onclick="changeStage('<%=listStage%>','<%=i%>')"
    			  class="glyphicon glyphicon-record mystage"
    			  data-toggle="popover" data-placement="bottom"
    			  data-content="<%=dv.getText()%>" style="color: #000000;"></span>
    		-----------
    
    		<%
    
    
    					}
    				}
    
    
    			}
    			//如果不为0后面都是黑差
    			else{
    				int index=0;
    				for (int i = 0; i < dvList.size(); i++) {
    					DicValue dv = dvList.get(i);
    					String stage=dv.getValue();
    					String possibility=pMap.get(stage);
    					if(stage.equals(currentStage)){
    						index=i;
    						break;
    
    					}
    				}
    				for (int i = 0; i < dvList.size(); i++) {
    
    					DicValue dv=dvList.get(i);
    					String listStage=dv.getValue();
    					String listPossibility=pMap.get(listStage);
    					if("0".equals(listPossibility)){
    						//黑茶
    		%>
    
    		<span id="<%=i%>" onclick="changeStage('<%=listStage%>','<%=i%>')"
    			  class="glyphicon glyphicon-remove mystage"
    			  data-toggle="popover" data-placement="bottom"
    			  data-content="<%=dv.getText()%>" style="color: #000000;"></span>
    		-----------
    
    		<%
    					}else {
    						//绿圈 绿色标记 黑圈
    						if(i==index){
    							//绿色标记
    		%>
    
    		<span id="<%=i%>" onclick="changeStage('<%=listStage%>','<%=i%>')"
    			  class="glyphicon glyphicon-map-marker mystage"
    			  data-toggle="popover" data-placement="bottom"
    			  data-content="<%=dv.getText()%>" style="color: #90F790;"></span>
    		-----------
    
    		<%
    						}else if(i<index){
    							//绿圈
    		%>
    
    		<span id="<%=i%>" onclick="changeStage('<%=listStage%>','<%=i%>')"
    			  class="glyphicon glyphicon-ok-circle mystage"
    			  data-toggle="popover" data-placement="bottom"
    			  data-content="<%=dv.getText()%>" style="color: #90F790;"></span>
    		-----------
    
    		<%
    						}else{
    							//黑圈
    		%>
    
    		<span id="<%=i%>" onclick="changeStage('<%=listStage%>','<%=i%>')"
    			  class="glyphicon glyphicon-record mystage"
    			  data-toggle="popover" data-placement="bottom"
    			  data-content="<%=dv.getText()%>" style="color: #000000;"></span>
    		-----------
    
    		<%
    
    		}
    					}
    				}
    			}
    		%>
    
    

    交易阶段其实主要的麻烦在于Jsp部分需要对阶段图标进行状态分析,至于后台部分不过是普通的增删改查.

    6.listener

    public class SysInitListener implements ServletContextListener {
        public void contextInitialized(ServletContextEvent event) {
            System.out.println("进入创建数据字典界面");
            ServletContext application=event.getServletContext();
            DicService ds= (DicService) ServiceFactory.getService(new DicServiceImpl());
    
            Map<String, List<DicValue>> map=ds.getAll();
    
            Set<String> set=map.keySet();
            for(String key:set){
                application.setAttribute(key+"List",map.get(key));
            }
            Map<String,String> pMap=new HashMap();
            pMap.put("01资质审查","10");
            pMap.put("02需求分析","30");
            pMap.put("03价值建议","40");
            pMap.put("04确定决策者","50");
            pMap.put("05提案/报价","80");
            pMap.put("06谈判/复审","90");
            pMap.put("07成交","100");
            pMap.put("08丢失的线索","0");
            pMap.put("09因竞争丢失关闭","0");
            application.setAttribute("pMap",pMap);
           
    

    把数据字典在项目启动时存至全局作用域中.

    总结

    以上就是项目的主要部分,还有一些其他部分都是常规的增删改查.感觉项目中还存在问题,比如线索转换应该看作是一个事务,不能通过简单的count==1进行判断.应该有异常回滚机制,不然可能会造成数据丢失.后面在SSM改装可以优化一下.
    展开全文
  • 基于jsp+servlet+javabean+mysql实现的具备简单注册登录功能的网站。 实现原理: 基于MVC设计思想 1.用jsp写的界面(负责用表单收集用户信息,并将逻辑处理交给servlet处理,jsp这里充当视图) 2.servlet负责创建...
  • 1.资源包内含有源码、数据库脚本、...4.本项目适合Java初学者,是一个JavaWEB入门级项目,后端技术栈为Servlet3.0,还适应于进行毕业设计课题设计。 5.学技术,切忌急于求成,从基础学起,打好基础,祝你学习愉快。
  • jsp+servlet+javabean实现网上商城项目完整源码,页面很漂亮,而且带有数据库哦!
  • 基于JSP+Servlet+MySQL实现实验管理系统

    千次阅读 多人点赞 2021-01-24 18:58:14
    前言:进行Android项目的同时,JAVAEE课程也有相关的个人项目,做之前没有感受到VUE的“香”(看同行的同学用的很快乐,这个寒假来体验一波),所以还是用最基本的JSP以及Servlet来实现前后端的交互。 项目环境: 1...

    前言:进行Android项目的同时,JAVAEE课程也有相关的个人项目,做之前没有感受到VUE的“香”(看同行的同学用的很快乐,这个寒假来体验一波),所以还是用最基本的JSP以及Servlet来实现前后端的交互。
    项目环境:
    1、Eclipse IDE 4.14.0
    在这里插入图片描述
    2、Tomcat 9.0.39(鉴于当时用zip安装,进行配置时出现一大堆问题,建议使用exe安装
    3、MySQL 8.0配合navicat(相关的安装以及使用在我的另一篇博文里)

    相关的环境准备,自己配置的时候没有及时记录下来,后来看到一篇不错的博文(内含编码格式问题的解决)分享给大家~

    PS:一定要记得调试过程中完善编码格式,不然很可能不会出现自身想要的结果!

    一、需求分析


    用户分为三类:管理员、教师、学生

    管理员
    1、实现用户的增删改查
    2、实现实验的增删改查
    3、实现题库的增删改查

    教师
    1、查看教师信息
    2、查看子实验信息
    3、查看学生成绩信息

    学生
    1、查看学生信息
    2、查看子实验信息
    3、回答试题,提交得到成绩

    二、数据库设计

    采用MySQL8.0配合navicat设计(具体实现方法参考

    • admin表(其实就是用户表)
    -- ----------------------------
    -- Table structure for test
    -- ----------------------------
    DROP TABLE IF EXISTS `admin`;
    CREATE TABLE `admin` (
      `id` varchar(25) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      `name` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      `password` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      `style` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `name` (`name`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
    
    -- ----------------------------
    -- Records of admin
    -- ----------------------------
    INSERT INTO `admin` VALUES ('1', '202f', '123', '学生');
    INSERT INTO `admin` VALUES ('2', 'admin', 'admin', '管理员');
    INSERT INTO `admin` VALUES ('3', '2020s', '123456', '学生');
    INSERT INTO `admin` VALUES ('4', '2020t', '123456', '教师');
    INSERT INTO `admin` VALUES ('6', '203t', '163', '教师');
    INSERT INTO `admin` VALUES ('7', '232s', '124', '学生');
    INSERT INTO `admin` VALUES ('8', '202s', '123', '学生');
    INSERT INTO `admin` VALUES ('9', '210s', '234', '学生');
    
    
    • experiment表(实验表)
    -- ----------------------------
    -- Table structure for test
    -- ----------------------------
    DROP TABLE IF EXISTS `experiment`;
    CREATE TABLE `experiment` (
      `id` varchar(4) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `hour` varchar(4) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `device` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `rule` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `goal` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `tips` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `step` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
    
    -- ----------------------------
    -- Records of experiment
    -- ----------------------------
    INSERT INTO `experiment` VALUES ('1', '化学实验基本操作技能', '4', '电子天平,称量瓶子,表面皿,坩埚,药勺,药品', '用电子天平称量物品时,可采用直接称量法、递减称量法和固定质量称量法。', '1. 熟悉和了解天平的原理、构造、各部件的位置与作用。\r\n\r\n2. 学会差减法和固定质量法的称样方法及操作技术,准确称出实验给出试样或器具的质量。\r\n\r\n3. 学会正确记录测量数据和处理数据。', '1、电子天平应放置在一平稳、固定的工作台上,应避免阳光直射和远离发热器。\r\n\r\n2、电子天平应避免与大型机器或者带干扰的设备连接,已避免其他设备的干扰。\r\n\r\n3、电子天平应使天平远离带有磁性或能产生磁场的物体及设备。\r\n\r\n4、不得在具有爆炸性危险的区域内使用天平。\r\n\r\n5、不得长时间在高湿度或高粉尘的环境中使用天平。\r\n\r\n6、电子天平使用前应通电预热半小时以上。\r\n\r\n7、玻璃器皿使用前必须按规定认真清洗干净,洗净的器皿应是内壁能被水均匀润湿而不粘附水珠。\r\n\r\n8、吸量管和移液管等玻璃量器应先经润洗后方可移取溶液。', '(1)准备两只洁净、干燥的称量瓶,做好记号,在台秤上粗略称其质量。\r\n\r\n(2)将一块表面皿置于分析天平的托盘上,准确称取其质量。\r\n\r\n(3)用药匙将试样加到表面皿中央,开始时加入少量试样,一直到接近所需的药品量时,用右手拇指和中指及手心拿稳药勺,伸向表面皿中心部分上方,食指慢慢轻敲药勺柄,让试样慢慢落入表面皿中,直至达到要求称取质量(0.5884g)时,正确记录测量数据。\r\n\r\n(4)同步骤(2)、(3),称取第2份试样于第2个表面皿中。');
    INSERT INTO `experiment` VALUES ('2', '乙酸乙酯的制备', '4', '无水乙醇、冰醋酸、浓H2SO4、饱和Na2CO3、饱和NaCl、饱和CaCl2电热套、球形冷凝管、圆底烧瓶、分液漏斗', '化学公式', '1.了解从有机酸合成酯的一般原理及方法。\r\n\r\n2. 掌握蒸馏、分液漏斗的使用等操作。', '注意操作的先后顺序', '1.在50ml圆底烧瓶中加入9.5ml(0.2mol)无水乙醇和6ml(0.1mol)冰醋酸,再小心加入2.5ml浓H2SO4,混匀后,加入沸石,装上冷凝管。2.小心加热反应瓶,缓慢回流1/2h,冷却反应物,将回流改成蒸馏装置,接受瓶用冷水冷却,蒸出生成的乙酸乙酯,直到镏出液约为反应物总体积的1/2为止。\r\n\r\n3.在镏出液中慢慢加入饱和Na2CO3,振荡,至不再有CO2气体产生为止。4.得粗产品,计算产率。');
    INSERT INTO `experiment` VALUES ('3', '	\r\n原电池电动势和电极电势的测定', '4', '电位差计,铜片电极,锌片电极,导线,接线板,盐桥,移液管(5mL,4支),烧杯,玻璃棒,天平,洗耳球,洗瓶,药品', '氧化还原反应的本质是氧化剂和还原剂之间发生电子的转移。原电池中得到电子的物质是氧化剂,失去电子的物质是还原剂。物质得失电子能力的大小(或氧化还原能力的强弱)可以用该物质的氧化态-还原态所组成的电对的电极电势的相对高低来衡量。', '1.掌握原电池的组成和电池电动势的测定方法。\r\n\r\n2.了解氧化态(或还原态)浓度变化、配合物形成和沉淀生成对电极电势的影响。', '比较实验步骤1,2,3,所测得的电动势数据差异', '分别配制1.0 mol的CuSO4和 ZnSO4 溶液50ml,用细砂纸除去金属铜、锌片表面的氧化层,洗净、擦干。在30mL的烧杯中加入1.0 molCuSO4溶液15mL,并插入铜电极,组成一个半电池;在另一个30mL的烧杯中加入1.0 molZnSO4溶液15mL,并插入锌电极,组成另一个半电池。用导线将铜、锌片分别与酸度计的正负极相连,两烧杯中间以盐桥连接。用电位计测出原电池');
    INSERT INTO `experiment` VALUES ('5', '\r\n样品的研磨及分级筛分', '4', '振筛机 ', '逆时针旋转手柄,提起上盖,将其固定在立杆上,取下筛具,依次将各标准筛内的物料取出', '本实验主要是对制备的LiFePO4/C材料进行研磨和筛分处理,了解样品的常用研磨方法,了解确定样品粒度组成的方法,掌握标准筛和颗粒粒径的相关知识,了解振筛机的结构和工作原理、操作方法及使用注意事项,将LiFePO4/C进行研磨和标准筛筛分,探讨样品粒度对LiFePO4/C正极材料性能的影响。', '1. 为了稳固振筛机,应用四个地脚将振筛机固定牢固,以免移动。\r\n\r\n2. 定期检查、加注、更换电动机内的机油。\r\n\r\n3. 每次筛分结束后,应擦干净振筛机上筛盘内的灰尘,严禁用水冲洗。\r\n\r\n4. 振筛机工作时,严禁将身体任意部位伸入、靠近振筛机的运动部件,以免受伤。', '1. 在摆放分样筛时,应按照筛孔大小的顺序进行叠放,孔径大的在上面,孔径小的在下面,最下面放置一个筛子底盘。\r\n\r\n2. 将需要进行筛分的试样倒入最上层的筛内,盖好筛盖,然后安放在振筛机机座内。\r\n\r\n3. 逆时针旋转夹筛盘上的提手柄,将整个夹筛盘向下滑,压紧套筛;然后,顺时针旋转夹筛盘的提手柄,其内的顶杆轴夹紧支撑套,将整套分样筛固定结实。\r\n\r\n4. 将振筛机的电源开关打开,振筛机开始工作,同时用秒表计时。\r\n\r\n5. 当振动时间达到要求的时间时,关闭电源开关,振筛机停止工作。');
    INSERT INTO `experiment` VALUES ('6', '正溴丁烷的制备', '5', '正丁醇 3毫升 0.033摩尔\r\n\r\n  溴化钠(无水) 5.1克 0.05摩尔\r\n\r\n  浓硫酸 5毫升 0.094摩尔\r\n\r\n  水 4.1毫升\r\n\r\n  碳酸钠、无水氯化钙。', '本实验中正溴丁烷是由正丁醇与溴化钠、浓硫酸共热而制得', '1、 学习以溴化钠、浓硫酸和正丁醇制备正溴丁烷的原理与方法。\r\n\r\n2、 练习带有吸收有害气体装置的回流加热操作。', '1、 投料时应严格按教材上的顺序;投料后,一定要混合均匀。\r\n\r\n2、 反应时,保持回流平稳进行,防止导气管发生倒吸。', ' 1、投料;2、安装回流装置\r\n\r\n以石棉网覆盖电炉为热源,按图示安装回流装置(含气体吸收部分),注意圆底烧瓶底部与石棉网间的距离和防止碱液被倒吸。\r\n\r\n3、 加热回流\r\n\r\n在石棉网上加热至沸,调整圆底烧瓶底部与石棉网的距离,以保持沸腾而又平稳回流,并时加摇动烧瓶促使反应完成。反应约30-40min。(注意调整距离和摇动烧瓶的操作)。\r\n\r\n4、 分离粗产物\r\n\r\n待反应液冷却后,改回流装置为蒸馏装置(用直形冷凝管冷凝),蒸出粗产物。(注意判断粗产物是否蒸完)。\r\n\r\n5、收集产物');
    
    
    • student表(学生信息表)
    -- ----------------------------
    -- Table structure for test
    -- ----------------------------
    DROP TABLE IF EXISTS `student`;
    CREATE TABLE `student` (
      `id` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      `name` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `age` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `sex` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `position` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `classname` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `address` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `phone` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `namestr` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      PRIMARY KEY (`id`),
      KEY `nam` (`namestr`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of student
    -- ----------------------------
    INSERT INTO `student` VALUES ('1', '黄辉', '21', '男', '班长', '材料1班', '湖南省长沙市湖南大学天马1区', '18916472831', '202f');
    INSERT INTO `student` VALUES ('2', '哈根', '22', '男', '纪律委员', '材料2班', '湖南省长沙市湖南大学天马2区', '13457523523', '2020s');
    INSERT INTO `student` VALUES ('3', '周修', '21', '女', '副班长', '材料1班', '湖南省长沙市湖南大学天马3区', '17445546231', '232s');
    INSERT INTO `student` VALUES ('4', '朱怀', '20', '男', '纪律委员', '材料1班', '湖南省长沙市湖南大学天马3区', '15342321312', '202s');
    INSERT INTO `student` VALUES ('5', '曾萨', '22', '男', '权益委员', '材料1班', '湖南省长沙市湖南大学天马1区', '19834521312', '210s');
    
    
    • teacher表(教师信息表)
    -- ----------------------------
    -- Table structure for test
    -- ----------------------------
    DROP TABLE IF EXISTS `teacher`;
    CREATE TABLE `teacher` (
      `id` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      `name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `age` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `sex` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `position` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `phone` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `namestr` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `namestring` (`namestr`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of teacher
    -- ----------------------------
    INSERT INTO `teacher` VALUES ('1', '陈骄', '46', '男', '教授', '湖南省长沙市岳麓区天马公寓10栋', '15372892042', '2020t');
    INSERT INTO `teacher` VALUES ('2', '莫伐', '53', '女', '讲师', '湖南省长沙市岳麓区望麓公寓3栋', '17634323231', '203t');
    
    
    • test表(试题表)
    -- ----------------------------
    -- Table structure for test
    -- ----------------------------
    DROP TABLE IF EXISTS `test`;
    CREATE TABLE `test` (
      `id` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `acho` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `bcho` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `ccho` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `answer` varchar(4) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of test
    -- ----------------------------
    INSERT INTO `test` VALUES ('1', '吸湿性强、遇水释放较多热量的化学品沾染皮肤后应立刻( )。', '用清水清洗', '用冷水清洗', '用软纸、软布抹去', 'C');
    INSERT INTO `test` VALUES ('10', '应如何简单辨认有味的化学药品?', '用鼻子对着瓶口去辨认气味', '用舌头品尝试剂', '将瓶口远离鼻子,用手在瓶口上方扇动,稍闻其味即可', 'C');
    INSERT INTO `test` VALUES ('12', '2020s', 'sdaf', 'asdf', 'rwetwer', 'B');
    INSERT INTO `test` VALUES ('2', '化学品的安全标签警示词不包括( )。', '小心', '危险', '警告', 'A');
    INSERT INTO `test` VALUES ('3', '对危险废物的容器和包装物以及收集、贮存、运输、处置危险废物的设施、场所,必须( )。', '设置危险废物识别标志', '设置生活垃圾识别标志', '不用设置识别标志', 'A');
    INSERT INTO `test` VALUES ('4', '普通塑料、有机玻璃制品的加热温度不能超过( )。', '40℃', '60℃', '80℃', 'B');
    INSERT INTO `test` VALUES ('5', '取用试剂时,错的说法是( )。', '不能用手接触试剂,以免危害健康和沾污试剂', '瓶塞应倒置桌面上,以免弄脏,取用试剂后,立即盖严,将试剂瓶放回原处,标签朝外', '多取的试剂可倒回原瓶,避免浪费', 'C');
    INSERT INTO `test` VALUES ('6', '下列不可以放入105℃干燥箱干燥的是( )。', '烧杯', '量筒', '锥形瓶', 'B');
    INSERT INTO `test` VALUES ('7', '实验室内使用乙炔气时,说法正确的是( )。', '室内不可有明火,不可有产生电火花的电器', '房间应密闭', '室内应有高湿度', 'A');
    INSERT INTO `test` VALUES ('8', '进行腐蚀品的装卸作业应该戴( )手套。', '帆布', '橡胶', '棉布', 'B');
    INSERT INTO `test` VALUES ('9', '干粉灭火器适用于( )。', '电器起火', '可燃气体起火', '以上都是', 'C');
    
    
    • score(成绩表)
    -- ----------------------------
    -- Table structure for score
    -- ----------------------------
    DROP TABLE IF EXISTS `score`;
    CREATE TABLE `score` (
      `id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      `name` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `experiment` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      `result` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of score
    -- ----------------------------
    INSERT INTO `score` VALUES ('122', '哈根', '乙酸乙酯的制备', '90');
    

    三、数据库封装

    package dao;
    
    import java.sql.*;
     
    public class DbHelper {
    	static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    	private static String url = "jdbc:mysql://localhost:3306/myproject?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=GMT";
    	private static String userName = "root"; 
    	private static String passWord = "huangzhihui@11"; 
    	private static Connection conn = null;
     
    	private DbHelper() {
     
    	}
     
    	public static Connection getConnection() {
    		if (null == conn) {
    			try {
    				Class.forName(JDBC_DRIVER);
    				conn = DriverManager.getConnection(url, userName, passWord);
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    		return conn;
    	}
     
    	public static void main(String[] args) { 
    		System.err.println(getConnection());
    	}
    	
    }
    

    四、实现效果

    登录首页

    在这里插入图片描述

    注册页面

    在这里插入图片描述

    管理员用户管理界面

    在这里插入图片描述

    管理员用户添加界面

    在这里插入图片描述

    管理员用户信息修改界面

    在这里插入图片描述

    管理员用户信息删除界面

    在这里插入图片描述

    管理员实验管理界面

    在这里插入图片描述

    管理员实验添加界面

    在这里插入图片描述

    管理员实验信息修改界面

    在这里插入图片描述

    管理员题库管理界面

    在这里插入图片描述

    管理员题目增加界面

    在这里插入图片描述

    管理员题目修改界面

    在这里插入图片描述

    教师个人信息页面

    在这里插入图片描述

    教师个人信息修改页面

    在这里插入图片描述

    教师子实验信息页面

    在这里插入图片描述

    教师所属学生信息页面

    在这里插入图片描述

    教师查看学生成绩页面

    在这里插入图片描述

    学生个人信息页面

    在这里插入图片描述

    学生个人信息修改页面

    在这里插入图片描述

    学生子实验信息页面

    在这里插入图片描述

    学生子实验测试页面

    在这里插入图片描述

    学生测试结果页面

    在这里插入图片描述

    五、基础代码

    1. 整体的结构还是很简单的,每一个功能实现几乎是共通的!

    NO.1 dao层的管理类

    即实现我们对数据库操作的sql语句
    例如:我书写的Admindao

    package dao;
    
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.List;
     
    import entity.Admin;
     
    public class AdminDao {
    	public List<Admin> getAllAdmin() { 
    		List<Admin> list = new ArrayList<Admin>(); 
    		Connection conn = DbHelper.getConnection();
    		String sql = "select *from admin order by cast(id as decimal)"; 
    		try {
    			PreparedStatement pst = conn.prepareStatement(sql);
    			ResultSet rst = pst.executeQuery();
    			while (rst.next()) {
    				Admin admin = new Admin();
    				admin.setId(rst.getString("id")); 
    				admin.setName(rst.getString("name"));
    				admin.setPassword(rst.getString("password"));
    				admin.setStyle(rst.getString("style"));
    				list.add(admin);
    			}
    			rst.close(); 
    			pst.close(); 
    		} catch (SQLException e) {
    			e.printStackTrace(); 
    		}
    		return list; 
    	}
     
    	public boolean addAdmin(Admin admin) { 
    		String sql = "INSERT INTO `admin`(`id`,`name`,`password`,`style`) VALUES (?,?,?,?)"; 
    		Connection conn = DbHelper.getConnection();
    		try {
    			PreparedStatement pst = conn.prepareStatement(sql);
    			pst.setString(1, admin.getId());
    			pst.setString(2, admin.getName());
    			pst.setString(3, admin.getPassword());
    			pst.setString(4, admin.getStyle());
    			int count = pst.executeUpdate();
    			pst.close();
    			return count > 0 ? true : false; 
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		return false;
    	}
     
    	public boolean updateAdmin(Admin admin) { 
    		String sql = "UPDATE `admin` SET `name`=?,`password`=?,`style`=? WHERE `id` = ?"; 
    		Connection conn = DbHelper.getConnection();
    		try {
    			PreparedStatement pst = conn.prepareStatement(sql);
    			pst.setString(1, admin.getName());
    			pst.setString(2, admin.getPassword());
    			pst.setString(4, admin.getId()); 
    			pst.setString(3, admin.getStyle());
    			int count = pst.executeUpdate();
    			pst.close(); 
    			return count > 0 ? true : false; 
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		return false;
    	}
     
    	public boolean deleteAdmin(int id) { 
    		String sql = "delete from admin where id = ?"; 
    		Connection conn = DbHelper.getConnection();
    		try {
    			PreparedStatement pst = conn.prepareStatement(sql);
    			pst.setInt(1, id);
    			int count = pst.executeUpdate();
    			pst.close();
    			return count > 0 ? true : false; 
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		return false;
    	}
     
    	public Admin selectAdminById(int id) { 
    		Connection conn = DbHelper.getConnection();
    		String sql = "select *from admin where id = " + id;
    		Admin admin = null;
    		try {
    			PreparedStatement pst = conn.prepareStatement(sql);
    			ResultSet rst = pst.executeQuery();
    			while (rst.next()) {
    				admin = new Admin();
    				admin.setId(rst.getString("id"));
    				admin.setName(rst.getString("name"));
    				admin.setPassword(rst.getString("password"));
    				admin.setStyle(rst.getString("style"));
    			}
    			rst.close();
    			pst.close();
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		return admin; 
    	}
    }
    
    

    NO.2 entity层的实体类

    即实现对数据库字段的set和get方法
    例如:我书写的Admin

    package entity;
    
    import java.io.Serializable;
     
    public class Admin implements Serializable { 
     
    	private static final long serialVersionUID = 1L;
     
    	private String id;
    	private String name;
    	private String password;
    	private String style;
    	
    	public String getId() {
    		return id;
    	}
    	public void setId(String id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getPassword() {
    		return password;
    	}
    	public void setPassword(String password) {
    		this.password = password;
    	}
    	public static long getSerialversionuid() {
    		return serialVersionUID;
    	}
    	public String getStyle() {
    		return style;
    	}
    	public void setStyle(String style) {
    		this.style = style;
    	}
     
    }
    
    

    NO.3 servlet层的实现类

    即实现对数据库记录的增删改查方法
    例如:我书写的AddServlet、DeleteServlet、UpdateServlet、ShowServlet

    增  AddServlet.java
    
    package servlet;
    import java.io.IOException; 
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import dao.AdminDao;
    import entity.Admin;
    
    public class AddServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
     
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		this.doPost(req, resp);
    	}
     
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		req.setCharacterEncoding("UTF-8");
    		
    		String id=req.getParameter("id");
    		String name = req.getParameter("name");
    		String password = req.getParameter("password");
    		String style=req.getParameter("style");
    		Admin admin = new Admin();
    		admin.setId(id);
    		admin.setName(name); 
    		admin.setPassword(password);
    		admin.setStyle(style);
    		AdminDao dao = new AdminDao();
    		dao.addAdmin(admin);
    		req.getRequestDispatcher("ShowServlet").forward(req, resp);
    	}
    }
    
    删 DeleteServlet.java
    
    package servlet;
    
    import java.io.IOException; 
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import dao.AdminDao;
     
    public class DeleteServlet extends HttpServlet { 
     
    	private static final long serialVersionUID = 1L;
     
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		this.doPost(req, resp);
    	}
     
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		String idStr = req.getParameter("id"); 
    		if (idStr != null && !idStr.equals("")) {
    			int id = Integer.valueOf(idStr);
    			AdminDao dao = new AdminDao();
    			dao.deleteAdmin(id);
    		}
    		req.getRequestDispatcher("ShowServlet").forward(req, resp);
    	}
     
    }
    
    改 UpdateServlet.java
    
    package servlet;
    
    import java.io.IOException;
     
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import dao.AdminDao;
    import entity.Admin;
     
    public class UpdateServlet extends HttpServlet{  
     
        private static final long serialVersionUID = 1L;
     
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
    		String idStr = req.getParameter("id");
    		if (idStr != null && !idStr.equals("")) {
    			int id = Integer.valueOf(idStr);
    			AdminDao dao = new AdminDao();
    			Admin admin = dao.selectAdminById(id);
    			req.setAttribute("admin", admin);
    		}
    		req.getRequestDispatcher("admin/admin_user_update.jsp").forward(req, resp);
     
    	}
     
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {  
        	
        	req.setCharacterEncoding("UTF-8");
        	resp.setCharacterEncoding("UTF-8");
            String username = req.getParameter("name");
            String userpwd = req.getParameter("password");
            String id = req.getParameter("id");
            String style=req.getParameter("style");
            Admin admin = new Admin();
            admin.setId(id);
            admin.setName(username);
            admin.setPassword(userpwd);
            admin.setStyle(style);
            AdminDao dao = new AdminDao();
            dao.updateAdmin(admin);
            req.getRequestDispatcher("ShowServlet").forward(req, resp);
        }
        
        
     
    }
    
    查 ShowServlet.java
    
    package servlet;
    
    import java.io.IOException;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import dao.AdminDao;
    import entity.Admin;
     
    public class ShowServlet extends HttpServlet { 
     
    	private static final long serialVersionUID = 1L;
     
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		req.setCharacterEncoding("UTF-8");
    		resp.setCharacterEncoding("UTF-8");
    		this.doPost(req, resp);
    	}
     
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		
    		req.setCharacterEncoding("UTF-8");
    		resp.setCharacterEncoding("UTF-8");
    		AdminDao dao = new AdminDao();
    		List<Admin> list = dao.getAllAdmin();
    		req.setAttribute("list", list);
    		req.getRequestDispatcher("admin/admin_user_index.jsp").forward(req, resp);
    	}
    }
    

    NO.4 jsp层的页面类

    即实现搭配servlet的显示页面
    例如:我书写的admin_user_index、admin_user_add、admin_user_update

    admin_user_index.jsp
    
    <%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
        <%@page import="entity.Admin"%>
        <%@page import="dao.*" %>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" >
    <title>显示</title>
        <style type="text/css">
               
    			form h1 {
    				display: inline-block;
    				width: 820px;
    			}
    			.check {
    				padding: 30px 30px;
    			}
    			
    			form {
    				display: inline;
    			}
    			
    			.contain {
    				width: 1298px;
    				border-radius: 10px;
    				border: 1px #bbb solid;
    				background-color: #eee;
    				padding-top: 20px;
    			}
    			
    			button {
    				margin-left: 10px;
    			}
    			
    			
    			.add {
    				float: right;
    				margin-right: 50px;
    			}
    			
        </style>
    </head>
    <body>
    <div class="contain pull-left">
        <h2>用户账号管理</h2>
        
        <a href="../admin/admin_user_add.jsp" target="_self"><button class="btn btn-primary add">添加用户</button></a>
      
        <div class="pull-left">
        <table class="table table-hover">
        <thead>
            <tr>
                <td align="center">编号</td>
                <td align="center">帐号</td>
                <td align="center">密码</td>
                <td align="center">类别</td>
                <td align="center">操作</td>
            </tr>
            
    <% 
        java.util.List<Admin> adminList = new java.util.ArrayList<Admin>();
        AdminDao admindao=new AdminDao();
    	adminList = admindao.getAllAdmin();	
    	for(Admin admin : adminList){
    %>
        <tr>
        <td align="center"><%=admin.getId()%></td>
        <td align="center"><%=admin.getName()%></td>
        <td align="center"><%=admin.getPassword() %></td>
        <td align="center"><%=admin.getStyle() %></td>
        
        <td align="center">
        <a href="..//UpdateServlet?id=<%=admin.getId() %>"
        onclick='return window.confirm("This user will be changed. Are you sure?")'><button class='btn btn-primary'>修改</button></a>
        |<a href="..//DeleteServlet?id=<%=admin.getId() %>" 
        onclick='return window.confirm("This user will be deleted. Are you sure?")'><button class='btn btn-danger'>删除</button></a>
        </td>
        <%} %>
      </tr> 
            
            </thead>
        </table>
        </div>
        </div>
    </body>
    </html>
    
    admin_user_add.jsp
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>    
       <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
       <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
       <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" >
       <title>添加</title>
        <style type="text/css">
               
    			form h1 {
    				display: inline-block;
    				width: 820px;
    			}
    			.check {
    				padding: 30px 30px;
    			}
    			
    			form {
    				display: inline;
    			}
    			
    			.contain {
    				width: 1298px;
    				border-radius: 10px;
    				border: 1px #bbb solid;
    				background-color: #eee;
    				padding-top: 20px;
    			}
    			
    			button {
    				margin-left: 10px;
    			}
    			
    			
    			.add {
    				float: right;
    				margin-right: 50px;
    			}
    			
        </style>
    
      </head>
     
      <body>
      <div class="contain pull-left">
      <h2>用户账号添加</h2>
      
      <div class="pull-left">
      
      <form action="../AddServlet" method="post">
        <table class="table table-hover">
        <thead>
            <tr>
                <td>用户id:</td>
                <td><input type="text" style="width: 40%" name="id" required/></td>
            </tr>
            <tr>
                <td>用户帐号:</td>
                <td><input  type="text" style="width: 40%" name="name" required/></td>
            </tr>
            <tr>
                <td>用户密码:</td>
                <td><input  type="password" style="width: 40%" name="password" required/></td>
            </tr>
            <tr>
                <td>用户类别:</td>
                <td>
                <select name="style" style="width: 40%">
                <option>管理员</option>
                <option>学生</option>
                <option>教师</option>
                </select>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input  type="submit" class='btn btn-primary' value="提交"/>
                    <input  type="reset"  class='btn btn-warning' value="清空"/>
                    <input  type="button"  class='btn btn-success'  value="返回" onclick="history.go(-1)"/>
                </td>
            </tr>
            </thead>
        </table>
       </form>
       </div>
       </div>
      </body>
    </html>
    
    admin_user_update.jsp
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>    
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" >
        <title>修改</title>
        <style type="text/css">
               
    			form h1 {
    				display: inline-block;
    				width: 820px;
    			}
    			.check {
    				padding: 30px 30px;
    			}
    			
    			form {
    				display: inline;
    			}
    			
    			.contain {
    				width: 1298px;
    				border-radius: 10px;
    				border: 1px #bbb solid;
    				background-color: #eee;
    				padding-top: 20px;
    			}
    			
    			button {
    				margin-left: 10px;
    			}
    			
    			
    			.add {
    				float: right;
    				margin-right: 50px;
    			}
    			
        </style>
      </head>
      
      <body>
      <div class="contain pull-left">
      <h2>账号信息修改</h2>
      
      <div class="pull-left">
        
        <form action="UpdateServlet" method="post">
        <table class="table table-hover">
        <thead>
            <tr>
                <td>用户编号:</td>
                <td><input  type="text"  style="width: 40%" name="id" value="${admin.id}" required/></td>
            </tr>
            
            <tr>
                <td>用户帐号:</td>
                <td><input  type="text"  style="width: 40%" name="name" value="${admin.name}" required/></td>
            </tr>
            <tr>
                <td>用户密码:</td>
                <td><input  type="text"  style="width: 40%" name="password" value="${admin.password}" required/></td>
            </tr>
            <tr>
                <td>用户类别:</td>
                <td><input  type="text"  style="width: 40%" name="style" value="${admin.style}"/></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input  type="submit"  class='btn btn-primary'  value="提交"/>
                    <input  type="button"  class='btn btn-success'  value="返回" onclick="history.go(-1)"/>
                </td>
            </tr>
        </thead>
        </table>
       </form>
       </div>
       </div>
      </body>
    </html>
    

    六、框架集显示

    1. 由于当时没有用VUE的框架,所以用的HTML框架来实现点击后的右侧刷新效果!
      在这里插入图片描述
    frame.jsp
    
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>管理员页面</title>
    </head>
    <frameset rows="11%,*"  framespacing="10">
    		<frame src="admin/Top.jsp" noresize="noresize" scrolling="yes" />
    		<frameset cols="15%,*">
    			<frame src="admin/Left_nav.jsp" noresize="noresize" />
    			<frame src="admin/admin_user_index.jsp" name="contain" />
    		</frameset>
    	</frameset>
    </html>
    
    Top.jsp
    
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>管理员</title>
    <style type="text/css">
    	.block{
    		width: 1300px;
    		height: 50px;
    		background-color: #ccc;
    		border-radius: 10px;
    		margin: 0 auto;
    	}
    	h3{
    		text-align: center;
    		padding-top: 12px;
    		font-family: "微软雅黑";
    	}
    </style>
    </head>
    <body>
    	<div class="block">
    		<h3>您好!管理员,欢迎使用材料学院实验管理系统!</h3>
    	</div>
    </body>
    </html>
    
    Left_nav.jsp
    
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="UTF-8">
    		<title></title>
    		<link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
    		<style type="text/css">
    			ul{
    				width: 200px;
    				height:400px;
    				float: right;
    				margin-top: 30px;
    				font-family: "微软雅黑";
    			}
    		</style>
    	</head>
    	<body>
    		<ul class="nav nav-pills nav-stacked">
    			<li style="display: inline-block;background-color:black;font-size: 2em"><a href="admin_user_index.jsp" target="contain">用户管理</a></li>
    			<li style="display: inline-block;background-color:black;font-size: 2em"><a href="admin_experiment_index.jsp" target="contain">实验管理</a></li>
    			<li style="display: inline-block;background-color:black;font-size: 2em"><a href="admin_test_index.jsp" target="contain">题库管理</a></li>
    			<li style="display: inline-block;background-color:black;font-size: 2em"><a href="../index.jsp" target="_parent">退出系统</a></li>
    			
    		</ul>
    
    	</body>
    </html>
    

    七、Filter过滤器

    Filter代码

    package util;
    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;
    import javax.servlet.http.HttpSession;
    
    public class MyFilter implements Filter {
    
    	private static final String[] dir =
    		{    "/admin",
    			 "/student",
    			 "/teacher"	
    	};
    	
    	public  MyFilter() {
    		// TODO 自动生成的构造函数存根
    	}
        
        /**
    	 * @see Filter#destroy()
    	 */
    	public void destroy() {
    		// TODO Auto-generated method stub
    	}
    
    	/**
    	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
    	 */
    	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    		try {
    			request.setCharacterEncoding("UTF-8");
    			response.setCharacterEncoding("UTF-8");
    			
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    		}
    		
    		HttpServletRequest req = (HttpServletRequest) request;
    		HttpSession session = (req).getSession();
    		String user = (String) session.getAttribute("user");
    		String priv = (String) session.getAttribute("priv");
    		String url = req.getRequestURI().substring(
    				req.getContextPath().length());
    		for (int i = 0; i < dir.length; i++) {
    			if (url.startsWith(dir[i])) {
    				if (user == null) {
    					request.getRequestDispatcher("/index.jsp")
    							.forward(request, response);
    				} else if (Integer.parseInt(priv) != i) {
    					request.getRequestDispatcher("/error.jsp").forward(
    							request, response);
    				}
    			}
    		}
    		chain.doFilter(request, response);
    	}
    
    	/**
    	 * @see Filter#init(FilterConfig)
    	 */
    	public void init(FilterConfig fConfig) throws ServletException {
    		// TODO Auto-generated method stub
    	}
    }
    
    

    登录类

    package servlet;
    
    import entity.LoginMgr;
    
    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;
    
    @SuppressWarnings("serial")
    @WebServlet("/LoginServlet")
    public class LoginServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            processRequest(request, response);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            processRequest(request, response);
        }
    
        protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
        	HttpSession session = request.getSession();
            
            String name = request.getParameter("name");
            String password = request.getParameter("password");
            String style=request.getParameter("type");
            LoginMgr user = new LoginMgr();
            int userType  = user.verifyUser(name, password,style);
            switch (userType) {
                case -1:
                    request.getRequestDispatcher(
                            "error.jsp")
                            .forward(request, response);
                    break;
                case 0:
                    session.setAttribute("priv", "0");
                    session.setAttribute("user", name);
                    request.getRequestDispatcher("/admin/frame.jsp").forward(request,
                            response);
                    break;
                case 1:
                    session.setAttribute("priv", "1");
                    session.setAttribute("user", name);
                    request.getRequestDispatcher("/student/frame.jsp").forward(request,
                            response);
                    break;
                case 2:
                    session.setAttribute("priv", "2");
                    session.setAttribute("user", name);
                    request.getRequestDispatcher("/teacher/frame.jsp").forward(request,
                            response);
            }
        }
    
    }
    
    

    登录管理类

    package entity;
    
    import java.util.ArrayList;
    
    import dao.AdminDao;
    
    public class LoginMgr {
    	private static ArrayList<Admin> adminlist;
    	
    	public LoginMgr() {
    		AdminDao dao= new AdminDao();
    		adminlist=(ArrayList<Admin>) dao.getAllAdmin();
    		
    	}
    	
    	public int verifyUser(String name, String password,String type){
    		int userType = -1;
    		if("管理员".equals(type))
    		for(int i = 0; i<adminlist.size(); i++){
    			if(adminlist.get(i).getName().equals(name)&&
    					adminlist.get(i).getPassword().equals(password)&&
    					    adminlist.get(i).getStyle().equals("管理员")){
    				userType = 0;
    				return userType;
    			}
    		}
    		else if(type.equals("学生"))
    			for(int i = 0; i<adminlist.size(); i++){
    				if(adminlist.get(i).getName().equals(name)&&
    						adminlist.get(i).getPassword().equals(password)&&
    						   adminlist.get(i).getStyle().equals("学生")){
    					userType = 1;
    					return userType;
    				}
    			}
    		else if(type.equals("教师"))
    			for(int i=0;i<adminlist.size();i++) {
    				if(adminlist.get(i).getName().equals(name)&&
    						adminlist.get(i).getPassword().equals(password)&&
    						   adminlist.get(i).getStyle().equals("教师")) {
    					userType=2;
    					return userType;
    				}
    			}
    		
    		return userType;
    	}
    
    }
    
    

    第一次进行WEB项目,写的略显潦草,后期有待优化!需要源码的朋友留下邮箱,我会直接打包发给你们。之后有时间我会上传到GitHub上!期待大家的指教!

    • 2021/6/29 新增注册功能,有需要的朋友注明新版本还是旧版本!
    • 2022/5/19 上传到github仓库,需要的朋友自取,谢谢三连!
    展开全文
  • 经典的jsp+servlet项目

    2012-10-30 11:08:56
    jsp+servlet开发的一个电子商务网站
  • 自己学了一个学期的web写了一个很基础的项目大概四千行代码在eclipse环境下运行,适合于初学者.

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 80,442
精华内容 32,176
热门标签
关键字:

基于jsp和servlet的项目