1. 程式人生 > >WEB工程的創建、運行過程及可能出現的問題

WEB工程的創建、運行過程及可能出現的問題

javaee

1、創建工程,在WEBRoot下建.html文件,寫相應的代碼;

<html>

<head>

<title>登錄</title>

<meta charset=‘utf8‘ content="text/html">

</head>

<body>

<form method="post" action="login">

<p>用戶名:<input type="text" name="username"/>

</

p>

<p>密碼:<input type="password" name="password"/>

</p>

<input type="submit" value="登錄">

</form>

</body>

</html>

2、點擊Open perspective選擇myeclipse Database Explorer

3、鼠標右擊,選擇newdriver名可以隨便填,URL填寫要連接的地址(mysqloracle),

Username

password分別填寫開始時候設置的密碼;ADDJARS導對應的包,然後nextfinished

4、在工程的src下創建.sql文件,寫建表語句;

drop table if exists userlogin;

create table userlogin(

id int(6) primary key auto_increment,

username varchar(20),

password varchar(20)

);

insert into userlogin(username,password) values(‘www‘,‘1234‘);

insert into userlogin(username

,password) values(‘lll‘,‘1234‘);

insert into userlogin(username,password) values(‘yyy‘,‘1234‘);

insert into userlogin(username,password) values(‘wly‘,‘1234‘);

5、導入jar包到WEB-INF下的lib文件夾裏面(mysqljar包,commons-pool包,dom4j包,p6spy包),導入配置文件到src下面,導入寫好的DBUtil類到包裏面;

6、寫主類下的代碼,

public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException,IOException {

String username=request.getParameter("username");

String password=request.getParameter("password");

Connection conn=DBUtil.getConnection();

response.setContentType("text/html;charset=utf8");

PrintWriter pw=response.getWriter();

String sql="select * from userlogin 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()){

pw.println("<h1>登錄成功</h1>");

}else{

pw.println("<h1>用戶名或密碼錯誤,登錄失敗</h1>");

}

pw.close();

} catch (SQLException e) {

e.printStackTrace();

}

response.getWriter().write("hello Bonnie...");

}

public void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException,

IOException {

doGet(request, response);

}

}

7、配置web.xml文件,加入

<servlet>

<servlet-name>login</servlet-name>

<servlet-class>web814.LoginServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>login</servlet-name>

<url-pattern>/login</url-pattern>

</servlet-mapping>

8、html文件裏的form表單裏的action=login<url-pattern>標簽裏的內容”;

9、在地址欄輸入:http://localhost:8080/web814(工程名)/login.htmlWEBRoot下建的html文件)

10、進去後輸入相應的內容,點擊登錄,就會跳轉到所寫的輸出結果界面;

過程中可能出現的問題:

1、錯誤500,控制臺會出現空指針異常,一般發生在LoginServlet裏面的PreparedStatement ps=conn.prepareStatement(sql); --> 可能是因為:sql語句裏面有問題,沒有相應的表;還可能是DBUtil裏面有問題,配置文件沒有修改或者沒有導入相應的包;

2、錯誤404:一般是配置出現問題,.xml文件沒有修改,或者路徑出錯;

3、點擊登錄以後沒有變化,是因為.html文件中的formaction沒有添加。


本文出自 “Java學習” 博客,請務必保留此出處http://12181171.blog.51cto.com/12171171/1956081

WEB工程的創建、運行過程及可能出現的問題