Servlet接口实现类开发流程
1、什么是Servlet?
Servlet是java为浏览器开发动态资源文件的接口。
2、Servlet开发流程:
(1)首先要实现HttpServlet接口,为什么不直接实现Servlet接口?因为Servlet接口中有很多用不到的方法,比较繁琐,就继承了Servlet的子接口HttpServlet。
(2)然后重写HttpServlet接口中的doGet和doPost方法。
public class Test extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("浏览器以get请求方式进行请求数据");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("浏览器以post请求方式进行请求数据");
}
}
(3)最后将这个接口实现类注册到web.xml中。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>Test</servlet-name>//Servlet别名
<servlet-class>Test</servlet-class>//Servlet类路径
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>//Servlet别名
<url-pattern>/test</url-pattern>//Servlet资源名
</servlet-mapping>
</web-app>
3、Servlet对象生命周期:
在Http服务器接受到来自浏览器的请求对象为这个接口实现类资源的时候,自动生成Servlet实例对象。
如何手动创建(服务器启动就创建):
<load-on-startup>8</load-on-startp>//填写一个大于0的整数就可以
一个Servlet接口实现类只能创建一个Servlet对象。
在Http服务器关闭时,自动销毁所有Servlet对象。
Servlet中请求对象和响应对象
1、请求对象HttpServletRequest request
请求对象负责处理请求协议包中的信息。
请求对象的常用方法:
String url=request.getRequestURL().toString();//通过请求对象获得url(完整的地址栏的地址)
String method=request.getMethod();//通过请求对象获得getMethod(GET/POST)
String uri=request.getRequestURI();//通过请求对象获得uri(网站名/资源文件)
Enumeration<String> c=request.getParameterNames();//通过请求对象获得所有的参数名称存放到枚举中
while (c.hasMoreElements()){
String c2=c.nextElement();//获得枚举中下一个请求参数中的数据变量名
String c3=request.getParameter(c2);//获得请求参数中的变量对应的数据
}
2、响应对象HttpServletResponse response
响应对象负责返回给浏览器的资源信息。
响应对象的常用方法:
PrintWriter out=response.getWriter();//创建打印输出实例对象
out.write("hello");//打印到浏览器上(这种方式打印只识别字符串)
out.println();//打印到浏览器上
response.setContentType("text/html;charset=utf-8");//设置响应对象对响应体的解析样式
out.write("hello<br>world");
String url="http://www.1111.com";
response.sendRedirect(url);//响应体响应url,转到相应的地址
3、请求对象和响应对象的生命周期?
只要Http发送过来一个请求协议包,浏览器就会自动生成req对象和res对象
在doGet方法和doPost方法运行的时候,需要确保这两个对象正确传过来
在Http服务器准备推送Http响应协议包之前,负责将本次生成的req对象和res对象销毁
JDBC+Servlet+Html的基本用户信息管理网站
JDBC工具类:
public class JDBCG {
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection conn() throws SQLException {
ResourceBundle resourceBundle=ResourceBundle.getBundle("jdbc");
String url=resourceBundle.getString("url");
String user=resourceBundle.getString("user");
String password=resourceBundle.getString("password");
return DriverManager.getConnection(url, user, password);
}
public static void over(ResultSet set,Statement statement,Connection connection){
if(set!=null){
try {
set.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
用户工具类:
public class UserDML {
public static void Useradd(Users users){
Connection connection = null;
PreparedStatement statement=null;
ResultSet set=null;
try {
connection=JDBCG.conn();
String sql="insert into zhangjin(username,password,sex,email)values (?,?,?,?)";
statement=connection.prepareStatement(sql);
statement.setString(1,users.getUsername());
statement.setString(2,users.getPassword());
statement.setString(3,users.getSex());
statement.setString(4,users.getEmail());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCG.over(set,statement,connection);
}
}
public static List Userfind(){
Connection connection = null;
PreparedStatement statement=null;
ResultSet set=null;
List list=new ArrayList();
try {
connection=JDBCG.conn();
String sql="select * from zhangjin";
statement=connection.prepareStatement(sql);
set=statement.executeQuery();
while (set.next()){
Integer userId=set.getInt("userId");
String username=set.getString("username");
String password1=set.getString("password");
String sex=set.getString("sex");
String email=set.getString("email");
Users users=new Users(userId,password1,username,sex,email);
list.add(users);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCG.over(set,statement,connection);
}
return list;
}
public static void Userdelete(String id){
Connection connection=null;
PreparedStatement statement=null;
ResultSet set=null;
try {
connection=JDBCG.conn();
String sql="delete from zhangjin where userId=?";
statement=connection.prepareStatement(sql);
statement.setString(1,id);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
JDBCG.over(set,statement,connection);
}
}
public static boolean equal(String username,String password1) {
boolean a=false;
Connection connection = null;
PreparedStatement statement=null;
ResultSet resultSet=null;
try {
connection=JDBCG.conn();
connection.setAutoCommit(false);
String sql="select * from zhangjin where username=? and password=?";
PreparedStatement preparedStatement=connection.prepareStatement(sql);
preparedStatement.setString(1,username);
preparedStatement.setString(2,password1);
resultSet=preparedStatement.executeQuery();
if(resultSet.next()){
a=true;
}
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
if(connection!=null){
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}finally {
JDBCG.over(resultSet,statement,connection);
}
return a;
}
}
用户类:
public class Users {
private Integer userId;
private String password;
private String username;
private String sex;
private String email;
public Users(Integer userId, String password, String username, String sex, String email) {
this.userId = userId;
this.password = password;
this.username = username;
this.sex = sex;
this.email = email;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Users() {
}
}
添加用户信息:
public class Addusers extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Enumeration<String> c=request.getParameterNames();
Map<String,String> s=new HashMap<>();
while (c.hasMoreElements()) {
String c2 = c.nextElement();
String c3 = request.getParameter(c2);
s.put(c2,c3);
}
Users users=new Users(null,s.get("password"),s.get("username"),s.get("sex"),s.get("email"));
UserDML.Useradd(users);
String result="注册成功";
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.write(result);
}
}
用户登录:
public class Loginusers extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username=request.getParameter("username");
String password=request.getParameter("password");
Boolean a=UserDML.equal(username,password);
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
if(a){
response.sendRedirect("http://localhost:8080/_war_exploded/Find");
}else {
response.sendRedirect("http://localhost:8080/_war_exploded/shibai.html");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
用户删除
public class Loginusers extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username=request.getParameter("username");
String password=request.getParameter("password");
Boolean a=UserDML.equal(username,password);
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
if(a){
HttpSession httpSession=request.getSession();
response.sendRedirect("http://localhost/_war_exploded/Find");
}else {
response.sendRedirect("http://localhost/_war_exploded/shibai.html");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
数据库查看:
public class Findusers extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter printWriter=response.getWriter();
List<Users> list=UserDML.Userfind();
printWriter.print("<center>");
printWriter.print("<table border=\"2\" bgcolor=\"#7fffd4\">");
printWriter.print("<tr>");
printWriter.print("<td>id</td>");
printWriter.print("<td>用户名</td>");
printWriter.print("<td>密码</td>");
printWriter.print("<td>性别</td>");
printWriter.print("<td>邮箱</td>");
printWriter.print("<td>删除</td>");
printWriter.print("</tr>");
for(Users users:list){
printWriter.print("<tr>");
printWriter.print("<td>"+users.getUserId()+"</td>");
printWriter.print("<td>"+users.getUsername()+"</td>");
printWriter.print("<td>"+users.getPassword()+"</td>");
printWriter.print("<td>"+users.getSex()+"</td>");
printWriter.print("<td>"+users.getEmail()+"</td>");
printWriter.print("<td><a href=\"http://192.168.31.219:8080/_war_exploded/Find2?userid="+users.getUserId()+"\">删除</a></td>");
printWriter.print("</tr>");
}
printWriter.print("</table>");
printWriter.print("</center>");
}
}
注:html和mysql数据库没有添加,需自行添加。
状态码的分类
状态码存在于响应协议包中的状态行中,它代表浏览器如何处理响应的数据,状态码由3位数组成。
常见的状态码分类:
(1)以1开头的状态码:代表改资源是一个不完整的资源,资源中存在2次调用。
(2)以2开头的状态码:代表是一个完整的资源文件。
(3)以3开头的状态码:定位的不是资源,而是地址。
(4)以4开头的状态码:无法定位到资源或者定位到资源但是无法获取。
(5)以5开头的状态码:能够访问到资源,但是服务端代码有异常。
欢迎资源文件
默认欢迎资源文件:可以修改html文件为index.html或者修改web.xml欢迎界面规则
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>