首页 > 代码库 > servlet+jsp 实现一个简单的web项目

servlet+jsp 实现一个简单的web项目

开发环境:

  MyEclipse 10.7

  Tomcat   7

  MySql  5.5

开发过程

 1. 建立一个 Web Project,名字为 MyProject,如下图,点击finish,就创建好了。


2. 修改项目编码为Utf-8,在src下创建类,首先 看一下项目结构

 

2.1  创建实体类类 User 

   package entity;

public class User {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

2.2 创建jdbc 连接及数据库的表,在这里要记得把数据库的 jar 加上,我用的mySql,把mysql-connector-java.jar 加到lib下。

     package util;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


public class Jdbc {
//连接
public static Connection connect()throws SQLException, ClassNotFoundException{
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver");
//取得连接的url,能访问MySQL数据库的用户名,密码;user:数据库表名 
String url = "jdbc:mysql://localhost:3306/user"; 
String username = "root"; 
String password = "root"; 

   conn =(Connection) DriverManager.getConnection(url, username, password); 
return conn;
}

//关闭
public static void close(Statement stat, Connection conn) throws SQLException{
if(stat != null){
stat.close();
}
if(conn != null){
conn.close();
}
}


}


2.3 修改 url 、用户名和密码,在这里可以直接用main方法测试是否连接成功。写UserDao,这里只写了一个查询。

package dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import entity.User;
import util.Jdbc;

public class UserDao {
public ArrayList<User> search(String id) throws ClassNotFoundException, SQLException{
Connection con = Jdbc.connect();
Statement sta = null;
ResultSet rs = null;
sta = (Statement) con.createStatement();
 
ArrayList<User> users = new ArrayList<User>();
rs = (ResultSet) sta.executeQuery("select * from T_USER where Id = ‘"+id+"‘");
while(rs.next()){
User u = new User();
u.setId(rs.getString("idNumber"));
u.setName(rs.getString("name"));
users.add(u);
}

if(rs != null){
rs.close();
}
Jdbc.close(sta, con);
return users;
}


}

 2.4 写 ActionServlet。直接创建Servlet方便一些。

package web;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserDao;
import entity.User;

public class ActionServlet extends HttpServlet {


public void service(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
String uri = request.getRequestURI();
uri = uri.substring(uri.indexOf("MyProject/") + 10, uri.lastIndexOf("."));

if(uri.equals("show")){
try {
show(request,response);
} catch (Exception e) {
e.printStackTrace();

}
}

// 查看列表
public void show(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String id = request.getParameter("id");
//根据id查询
List<User> userList = new UserDao().search(id);
//返回页面
request.setAttribute("userList", userList);
request.getRequestDispatcher("record.jsp").forward(request, response);
}


}

2.5 修改web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ActionServlet</servlet-name>
    <servlet-class>web.ActionServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>ActionServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

3.这样后台就写完了,下面开始写jsp页面。

修改 index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://www.mamicode.com/">
    <title>My JSP ‘index.jsp‘ starting page</title>

  </head>
  
  <body>
   <div>
     <form action="show.do" method="post">
        ID:<input type="text" id="id" name="id" size="18"/>
        <input type="submit" value="http://www.mamicode.com/提交"/> 
    </form>
   </div>
  </body>
</html>

4. 添加 record.jsp

  <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<%@ page import ="entity.User" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://www.mamicode.com/">
    <title>My JSP ‘index.jsp‘ starting page</title>

<style type="text/css">
td{
border:1px solid #89c3eb;
width:200px;
height:30px;
text-align:center;
margin:0px;
padding:0px;
}
  tr{
margin:0px;
padding:0px;
   }
</style>
  </head>
  
  <body>
  <div>
   人员信息<br/>
       <%
    List<User> lists =(ArrayList)request.getAttribute("userList");
    if(lists.size() == 0){
        out.print("无查询记录");
    }else{
       out.print("<table  cellspacing=‘0px‘ cellpadding=‘0px‘>");
       out.print("<tr><td>姓名</td><td>ID</td></tr>");
       for(int i=0;i<lists.size();i++){
                User u = lists.get(i);
                out.print("<tr>");
                out.print("<td>"+u.getName()+"</td>");
                out.print("<td>"+u.getId()+"</td>");
                out.print("</tr>");
            }
       out.print("</table>");
    }
   
    %>
   </div>
  </body>
</html>

5. 部署程序到tomcat,在浏览器访问地址 http://localhost:8080/MyProject/ 可以看到index.jsp的内容,输入Id提交就能看到数据了。


servlet+jsp 实现一个简单的web项目