JSP最令我痴迷的地方在于其神奇的Servlet映射,映射一直是现在网站开发,MVC ,SSH框架都必备的最重要的基础技能。
我们今天就用用户注册的实例来讲解Servlet的用法
下面是我提前建好的数据库:
首先我们新建一个Dynamic Web Project(动态网页)
我们在src文件下新建一个包,并创建一个servlet:RegServlet
一个新的servlet具有以下的基础代码:
首先我们在RegServlrt类中重写init()方法和doPost()方法。在基础代码中是没有给出init()方法的,需要我们自己去写。
首先看看我们引用的jar包
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
首先在init()方法中获取数据库连接。
//数据库连接Connection
private Connection conn;
public void init()throws ServletException{
super.init();
try{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//设置url
String url="jdbc:mysql://localhost:3306/MyBlog";
//获取连接
conn =DriverManager.getConnection(url, "root", "");
}catch(Exception e)
{
e.printStackTrace();
}
}
其中驱动的jar包是需要自己下载的,我这里引用的是mysql.jar:
运行时可能提示一些小问题,tomcat找不到该驱动,解决办法就是将jar包复制粘贴到tomcat的lib中,就没事了。
接下来就是填充doPost代码:
//设置编码格式
response.setContentType("text/html");
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
//获取表单中的属性值
String username=request.getParameter("username");
String password=request.getParameter("password");
String sex=request.getParameter("sex");
String question=request.getParameter("question");
String answer=request.getParameter("answer");
String email=request.getParameter("email");
if(conn!=null){
try{
//插入注册信息的SQL语句(使用?占位符)
String sql="insert into tb_user(username,password,sex,question,answer,email)"+"values(?,?,?,?,?,?)";
//这里会有两类,一类是com.mysql.jdbc,一类是java.sql,没有本质区别,java.sql兼容性会更强。
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ps.setString(3, sex);
ps.setString(4, question);
ps.setString(5, answer);
ps.setString(6, email);
ps.executeUpdate();
//获取PrintWriter对象。
PrintWriter out=response.getWriter();
out.print("<h1 aling='center'>");
out.print(username+"注册成功!");
out.print("</h1>");
out.flush();
out.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
else
{
response.sendError(500,"数据库连接错误!");
}
}
接下里就是我们index.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>Insert title here</title>
</head>
<body>
<form action ="RegServlet" method="Post" onsubmit="return reg(this);">
<table align="center" border="0", width="500">
<tr>
<td align ="right" width ="30%">用户名:</td>
<td><input type ="text" name ="username" class="box"></td>
</tr>
<tr>
<td align ="right" width ="30%">密码:</td>
<td><input type ="text" name ="password" class="box"></td>
</tr>
<tr>
<td align ="right" width ="30%">性别:</td>
<td><input type ="radio" name ="sex" value="男" checked="checked">男
<input type ="radio" name ="sex" value="女" >女</td>
</tr>
<tr>
<td align ="right" width ="30%">密码找回问题:</td>
<td><input type ="text" name ="question" class="box"></td>
</tr>
<tr>
<td align ="right" width ="30%">密码找回答案:</td>
<td><input type ="text" name ="answer" class="box"></td>
</tr>
<tr>
<td align ="right" width ="30%">邮箱:</td>
<td><input type ="text" name ="email" class="box"></td>
</tr>
<tr>
<td colspan="2" align="center" height="40">
<input type ="submit" value="注册">
<input type ="reset" value="重置">
</td>
</tr>
</body>
</html>
最重要的步骤,也是今天的重点:配置servlet
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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>MyBlog</display-name>
<servlet>
<servlet-name>RegServlet</servlet-name>
<servlet-class>servlet.RegServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegServlet</servlet-name>
<url-pattern>/RegServlet</url-pattern>
</servlet-mapping>
</web-app>
我们运行index.jsp
这里出现了乱码问题,是为什么呢,明明设置的字符集都是统一的。因为通过servlet处理form表单就会出现这样的情况。解决办法是加个过滤器。我后面会讲到。