简单的javaweb项目(Servlet,JDBC)

一,数据库

   mysql

数据表:

简单的javaweb项目(Servlet,JDBC)_第1张图片

 

二、项目框架

简单的javaweb项目(Servlet,JDBC)_第2张图片

三、实现流程

1、编写连接数据库的工具类,放入hua.util 包中,命名为DBconn.java,用于实现对数据库的增删改查操作

package hua.util;

import java.sql.*;




public class DBconn {

        //数据库连接信息
	static String url = "jdbc:mysql://localhost:3306/diary?useUnicode=true&characterEncoding=utf8"; 
	static String user ="root";
	static String password ="123456";
	static Connection conn=null;
	static ResultSet rs=null;
	static PreparedStatement ps = null;
	
        //初始化,连接数据库
	public static void init(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn=DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("初始化失败");
			e.printStackTrace();
		}
	}
	
	/**
	 * 增加修改删除操作
	 * @param sql
	 * @return
	 */
	public static int addUpdDel(String sql){
		int i=0;
		try {
			PreparedStatement ps = conn.prepareStatement(sql);
			i=ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("sql数据库增删改异常");
			e.printStackTrace();
		}
		
		return i;
	}
	
        //数据库查询操作
	public static ResultSet selectSql(String sql){
		try {
			ps=conn.prepareStatement(sql);
			rs=ps.executeQuery(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("sql数据库查询异常");
			e.printStackTrace();
		}
		
		return rs;
	}
	

        //关闭连接
	public 	static void closeConn(){
		try {
			
			ps.close();
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("sql数据库关闭异常");
			e.printStackTrace();
		}
	}
}

2、编写字符编码过滤器EndodingFilter,放入hua.filter包下。

package hua.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class EncodingFilter implements Filter {
	public EncodingFilter(){
		System.out.println("过滤器构造");
	}

	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("过滤器 销毁");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
			
		request.setCharacterEncoding("utf-8");//将编码 改成utf-8
		response.setContentType("text/html;charset=utf-8");
		chain.doFilter(request, response);
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("过滤器初始化");

	}

}

3、编写JavaBean,放入hua.entity包下

Diary.java

package hua.entity;

import java.sql.Date;

public class Diary {
	private int jlxh;
	private Date createtime;
	private Date updatetime;
	private String place;
	private String text;
	private String info;
	private User user;
	public int getJlxh() {
		return jlxh;
	}
	public void setJlxh(int jlxh) {
		this.jlxh = jlxh;
	}
	public Date getCreatetime() {
		return createtime;
	}
	public void setCreatetime(Date createtime) {
		this.createtime = createtime;
	}
	public Date getUpdatetime() {
		return updatetime;
	}
	public void setUpdatetime(Date updatetime) {
		this.updatetime = updatetime;
	}
	public String getPlace() {
		return place;
	}
	public void setPlace(String place) {
		this.place = place;
	}
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
	public String getInfo() {
		return info;
	}
	public void setInfo(String info) {
		this.info = info;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	@Override
	public String toString() {
		return "Diary [jlxh=" + jlxh + ", createtime=" + createtime
				+ ", updatetime=" + updatetime + ", place=" + place + ", text="
				+ text + ", info=" + info + ", user=" + user + "]";
	}
	
	
}

 User.java

package hua.entity;

public class User {
	private int id;
	private String name;
	private String password;
	private String info;
	public int getId() {
		return id;
	}
	public void setId(int 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 String getInfo() {
		return info;
	}
	public void setInfo(String info) {
		this.info = info;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password
				+ ", info=" + info + "]";
	}
	
}

4、编写Dao接口,放入hua.dao包下。

UserDao.java

package hua.dao;



import hua.entity.User;

public interface UserDao {
	public User login (String name,String pwd);//登录
	public boolean register(User user);//注册
	
}

DiaryDao.java

package hua.dao;

import java.util.List;

import hua.entity.Diary;

public interface DiaryDao {
	public boolean add(Diary diary);//增加
	public List getDiaryAll();//返回用户信息集合
	public boolean delete(int id);//删除日志记录
	public boolean update(Diary diary);//修改日记
}

5、编写Dao实现类,放入hua.dao包下

UserDaoImpl.java

package hua.dao;

import hua.entity.User;
import hua.util.DBconn;

import java.sql.ResultSet;
import java.util.List;

public class UserDaoImpl implements UserDao {
	/**
	 * 登录
	 */
	public User login(String name, String pwd) {
		User user = null;
		String sql="select * from user where name='"+name+"' and password='"+pwd+"'";
		try{
			DBconn.init();
			ResultSet rs=DBconn.selectSql(sql);
			while(rs.next()){
				if(rs.getString("name").equals(name)&&rs.getString("password").equals(pwd)){
					user=new User();
					user.setId(rs.getInt("id"));
					user.setName(name);
					user.setInfo(rs.getString("info"));
				}
			}
		}catch (Exception e) {
			// TODO: handle exception
		}
	
		return user;
	}

	/**
	 * 注册
	 */
	public boolean register(User user) {
		boolean flag=false;
		String sql = "insert into user(name,password,info) values ('"+
						user.getName()+"','"+user.getPassword()+"','"+user.getInfo()+"')";
		DBconn.init();
		int i = DBconn.addUpdDel(sql);
		if(i>0){
			flag=true;
		}
		DBconn.closeConn();
		return flag;
	}


}

DiaryDaoImpl.java

package hua.dao;

import hua.entity.User;
import hua.util.DBconn;

import java.sql.ResultSet;
import java.util.List;

public class UserDaoImpl implements UserDao {
	/**
	 * 登录
	 */
	public User login(String name, String pwd) {
		User user = null;
		String sql="select * from user where name='"+name+"' and password='"+pwd+"'";
		try{
			DBconn.init();
			ResultSet rs=DBconn.selectSql(sql);
			while(rs.next()){
				if(rs.getString("name").equals(name)&&rs.getString("password").equals(pwd)){
					user=new User();
					user.setId(rs.getInt("id"));
					user.setName(name);
					user.setInfo(rs.getString("info"));
				}
			}
		}catch (Exception e) {
			// TODO: handle exception
		}
	
		return user;
	}

	/**
	 * 注册
	 */
	public boolean register(User user) {
		boolean flag=false;
		String sql = "insert into user(name,password,info) values ('"+
						user.getName()+"','"+user.getPassword()+"','"+user.getInfo()+"')";
		DBconn.init();
		int i = DBconn.addUpdDel(sql);
		if(i>0){
			flag=true;
		}
		DBconn.closeConn();
		return flag;
	}


}

6、编写测试类,放入hua.test包下。

Test.java

package hua.test;

import hua.dao.DiaryDao;
import hua.dao.DiaryDaoImpl;
import hua.entity.Diary;

import java.util.List;


public class Test {
	public static void main(String[] args) {
		System.out.println("dddddddddddddddd");
		List list;
		DiaryDao dd = new DiaryDaoImpl();
		list = dd.getDiaryAll();

		for(Diary diary:list){
			System.out.println(diary.toString());
		}
		
	}
	
	
}

7、Servlet处理器类的编写

UserServlet.java

package hua.servlet;

import hua.dao.UserDao;
import hua.dao.UserDaoImpl;
import hua.entity.User;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. 
* * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String todo = request.getParameter("todo"); System.out.println(todo); if(todo.equals("login")){ login(request, response); }else if(todo.equals("register")){ register(request, response); } } /** * 登录 * @param request * @param response * @throws ServletException * @throws IOException */ public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("调用user登录方法================================"); String name = request.getParameter("name"); String password = request.getParameter("password"); UserDao ud = new UserDaoImpl(); User user = ud.login(name, password); if(user!=null){ //登录成功 System.out.println("登录成功"); request.getRequestDispatcher("/caidan.jsp").forward(request, response);//转发页面 }else{ //登录失败 } } /** * 注册 * @param request * @param response * @throws ServletException * @throws IOException */ public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String password = request.getParameter("password"); String info = request.getParameter("info"); User user = new User(); user.setName(name); user.setPassword(password); user.setInfo(info); UserDao ud = new UserDaoImpl(); if(ud.register(user)){ //注册成功 }else{ //注册失败 } } }

DiaryServlet.java

package hua.servlet;

import hua.dao.DiaryDao;
import hua.dao.DiaryDaoImpl;
import hua.entity.Diary;
import hua.entity.User;

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;

public class DiaryServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public DiaryServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. 
*/ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet.
* * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String todo = request.getParameter("todo"); System.out.println(todo); if(todo.equals("showAllDiary")){ showAllDiary(request, response); }else if(todo.equals("addDiary")){ addDiary(request, response); }else if(todo.equals("updateDiary")){ updateDiary(request, response); }else if(todo.equals("deleteDiary")){ deleteDiary(request, response); } } /** * Initialization of the servlet.
* * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } public void showAllDiary(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("执行查询所有日志操作"); DiaryDao dd=new DiaryDaoImpl(); List diaryAll=dd.getDiaryAll(); request.setAttribute("diaryAll", diaryAll); request.getRequestDispatcher("/showAllDiary.jsp").forward(request, response); } public void addDiary(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("执行添加日志方法"); String place = request.getParameter("place");//获取jsp页面抓过来的参数 String text = request.getParameter("text"); String info = request.getParameter("info"); Diary diary = new Diary(); diary.setPlace(place); diary.setText(text); diary.setInfo(info); User user = new User(); user.setId(1); diary.setUser(user); DiaryDao dd = new DiaryDaoImpl(); boolean flag=dd.add(diary); if(flag){ request.getRequestDispatcher("/success.jsp").forward(request, response); }else{ request.getRequestDispatcher("/failed.jsp").forward(request, response); } } public void updateDiary(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("执行更新日志操作"); String id = request.getParameter("jlxh"); int jlxh=Integer.parseInt(id); String place = request.getParameter("place");//获取jsp页面抓过来的参数 String text = request.getParameter("text"); String info = request.getParameter("info"); Diary diary = new Diary(); diary.setJlxh(jlxh); diary.setPlace(place); diary.setText(text); diary.setInfo(info); User user = new User(); user.setId(1); diary.setUser(user); DiaryDao dd = new DiaryDaoImpl(); boolean flag=dd.update(diary); if(flag){ request.getRequestDispatcher("/success.jsp").forward(request, response); }else{ request.getRequestDispatcher("/failed.jsp").forward(request, response); } } public void deleteDiary(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("jlxh"); int jlxh = Integer.parseInt(id); DiaryDao dd = new DiaryDaoImpl(); if(dd.delete(jlxh)){ request.setAttribute("xiaoxi", "删除成功"); System.out.println("删除成功-------------"); request.getRequestDispatcher("/success.jsp").forward(request, response); }else{ request.setAttribute("xiaoxi", "删除失败"); System.out.println("删除失败"); request.getRequestDispatcher("/failed.jsp").forward(request, response); } } }

8、web.xml



  	
  
  	EncodingFilter
  	hua.filter.EncodingFilter
  
  
  	EncodingFilter
  	/*
  
  
    This is the description of my J2EE component
    This is the display name of my J2EE component
    UserServlet
    hua.servlet.UserServlet
  
  
    This is the description of my J2EE component
    This is the display name of my J2EE component
    DiaryServlet
    hua.servlet.DiaryServlet
  


  
    UserServlet
    /UserServlet
  
  
    DiaryServlet
    /DiaryServlet
  
  
  
    index.jsp
  

9、jsp文件

index.jsp 项目主页,显示用户登录界面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



 
       请登录
 
  
 
        


            用户名:


            密码:    


                    
                            
        

        
        新用户注册
        
 

caidan.jsp登录成功后,主菜单界面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



 
       菜单
 
  
 
        记一次
        查看所有记录
        
 

showAllDiary.jsp 展示所有日志界面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



 
   所有用户界面
 
  
 
  
     

${xiaoxi }


     
         
                 
                 
                 
                 
                 
                 
                 
                 
         
         
             

                     
                 

                     
                     
                     
                     
                     
                     
                     
                     
                 
             
         
         
     
序号地点创建时间修改时间内容备注用户id操作
删除

     
     返回主菜单
 

addDiary.jsp 添加日志界面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



 
    写日志
 
 
      


          地点


          内容


          备注


              
                  
      

      
 

success.jsp操作成功界面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



 
       菜单
 
  
 
              操作成功
        返回主菜单
        
 

failed.jsp操作失败界面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



 
       菜单
 
  
 
              操作失败
        返回主菜单
        
 

四、报错指引

在执行过程中发现数据库与浏览器之间的中文字符出现乱码,排查后发现navicat连接时未勾选mysql字符集,编码选择utf-8,勾选mysql字符集解决,如下图。

简单的javaweb项目(Servlet,JDBC)_第3张图片

 

 

 

 

 

 

你可能感兴趣的:(java)