学了一个学期的《面向对象程序设计》,还是没有对象,CSDN的第一篇笔记就献给它好了。
File - New - Web Project.
自动生成目录结构
新工程 servletTest1 上右键 - New - Servlet。
系统建议使用大写字母开头为新的servlet命名
那就叫 Servlet 叭!
路径很重要,最常见的报错就是 form 的 action 对象没写对。
点击Finish后得到的表结构↓
drop table if exists users
go
create table users(
username nvarchar(10),
password nvarchar(20)
)
go
insert into users
values('test1','11111'),('test2','22222'),('test3','33333')
select * from users
文件:index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
新增
启动Tomcat
由于Servlet文件未完成,Tomcat启动时控制台会报错,但对表单页面浏览不影响。
在浏览器地址栏输入:http://127.0.0.1:8080/servletTest/index.jsp
文件:Servlet.java
package servletTest1;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet extends HttpServlet {
public Servlet() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username=new String(request.getParameter("a"));
String password=new String(request.getParameter("b"));
System.out.println("1,username:"+username+"\t password:" +password);
Connection con = null;
Statement sql;
String dbname="你的数据库登录名称";
String url="jdbc:sqlserver://localhost:1433;DatabaseName="+dbname;
String userName="你的数据库登录用户名";
String userPwd="你的数据库登录密码";
String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
try{
Class.forName(driverName);
con=DriverManager.getConnection(url,userName,userPwd);
sql=con.createStatement();
sql.executeUpdate("insert into users values("+"'"+username+"'"+","+"'"+password+"'"+")");
con.close();
}
catch(Exception e){
System.out.print(e+"\n");
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("insert success!");
out.flush();
out.close();
}
public void init() throws ServletException {
// Put your code here
}
}
工程右键 - Build Path - Configure Build Path…
找到jdbc所在的位置并导入后,重新部署工程
This is the description of my J2EE component
This is the display name of my J2EE component
Servlet
servletTest1.Servlet
Servlet
/Servlet
CSDN笔记里怎么设置图片大小啊啊啊,这排版好丑啊