一、相关的软件下载和环境配置
1、下载并配置JDK。
2、下载eclipse。
3、下载并配置apache-tomcat(服务器)。
4、下载MySQL(数据库)。
5、下载Navicat for MySQL(数据库可视化工具),方便对数据库的操作。
6、下载jdbc用来实现eclipse中的项目与数据库实现连接。
---以上可在网上查询教程
二、新建web项目
1.
然后点击next,
继续点next
勾选Generate web.xml
然后finish
2.新建两个包
然后User就是我们封装的数据
packagecom.better.bean;public classUser {private intuserid;privateString username;privateString password;publicUser() {
}public intgetUserid() {returnuserid;
}public void setUserid(intuserid) {this.userid =userid;
}publicString getUsername() {returnusername;
}public voidsetUsername(String username) {this.username =username;
}publicString getPassword() {returnpassword;
}public voidsetPassword(String password) {this.password =password;
}
}
建立类文件时一样
而servlet建立时不一样,如下
然后servlet代码如下
addservlet.java
packagecom.better.servlet;importjava.io.IOException;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.SQLException;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;/*** Servlet implementation class addservlet*/@WebServlet("/addservlet")public class addservlet extendsHttpServlet {private static final long serialVersionUID = 1L;/***@seeHttpServlet#HttpServlet()*/
publicaddservlet() {super();//TODO Auto-generated constructor stub
}/***@seeHttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)*/
protected voiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {//TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String username= request.getParameter("username");
String psword= request.getParameter("password");
String url= "jdbc:mysql://localhost:3306/demodb?&useSSL=false&serverTimezone=UTC";
String user= "root";
String password= "9527";
Connection conn= null;
PreparedStatement ps= null;try{
Class.forName("com.mysql.cj.jdbc.Driver");
conn=DriverManager.getConnection(url, user, password);
}catch(ClassNotFoundException e) {
response.getWriter().print("加载驱动失败");
}catch(SQLException e) {
response.getWriter().print("连接数据库失败");
}try{
String sql= "INSERT INTO user(username