Login.jsp
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
用户登录 | |
username: | |
password: | |
在src目录下新建com.servlet Package然后再新建一个servlet 命名为LoginServlet,LoginServlet的代码如下:
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
/**
* Destruction of the servlet.
*/
Connection conn;
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 {
response.setContentType("text/html");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
if(conn!=null){
String sql = " select * from tb_user where username = ? and password = ?";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if(rs.next()){
// ServletRequest session = null;;
// session.getAttribute("username",username);
PrintWriter out = response.getWriter();
out.println(""-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("");
out.println("
A Servlet");out.println("
");out.print(" This is login JSP");
out.println(username+"登陆成功");
out.println(" ");
out.println("");
out.flush();
out.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
super.init();
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/tb_test";
conn = DriverManager.getConnection(url, "root", "admin");
}catch(Exception e){
e.printStackTrace();
System.out.println("数据库连接失败");
}
}
}
在写Servelet的时候,如果简单考虑的话,是写doPost()还是写doGet()是没有多大影响的。有两种方法:
1.在jsp页面的提交方法mehtod是等于post还是get,然后写相应的方法;
2.如果写了doPost()方法,可以在doGet()方法中加上doPost(request,response),反之亦然。
然后修改一下web.xml文件如下:
LoginServlet
com.servlet.LoginServlet
LoginServlet
/LoginServlet