当前位置: 代码迷 >> Java Web开发 >> java中怎么创建Servlet
  详细解决方案

java中怎么创建Servlet

热度:6756   发布时间:2013-02-25 21:16:51.0
java中如何创建Servlet
如题 求高手指教

------解决方案--------------------------------------------------------
Java code
import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class TestServlet extends HttpServlet {    private static final long serialVersionUID = 8009071316884480626L;    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html");        PrintWriter out = response.getWriter();        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");        out.println("<HTML>");        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");        out.println("  <BODY>");        out.print("    This is ");        out.print(this.getClass());        out.println(", using the GET method");        out.println("  </BODY>");        out.println("</HTML>");        out.flush();        out.close();    }        public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        this.doGet(request, response);    }    }
------解决方案--------------------------------------------------------
创建一个class extends HttpServlet {
}

就是创建一个servlet了 

Java code
java jsp+servlet实现登录网页设计  这次涉及到四个文件:登录页面:login.jsp登录成功欢迎页面:success.jsp登录失败页面:fail.jspServlet处理文件:LoginServlet.java其实还涉及到一个文件:web.xml,这个后面再说:下面分别介绍这几个文件://--------------------------------------------------------------------------------------------------------------------LoginServlet.java   内容:package org.cai.servlet ;import java.sql.* ;import java.io.* ;import javax.servlet.http.* ;import javax.servlet.* ;public class LoginServlet extends HttpServlet implements Servlet{ public LoginServlet(){ }  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{  }// protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{//  System.out.println("-------------------------") ;//  doPost(request, response) ;// } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{  response.setContentType("text/html;charset=gb2312") ;  request.setCharacterEncoding("gb2312") ;  String result = "" ;  //获取用户名  String username = request.getParameter("username") ;  String psw = request.getParameter("password") ;  if ((username == "") || (username==null) || (username.length() > 20 )){   try{    result = "请输入用户名(不能超过20个字符)!" ;    request.setAttribute("message" ,result) ;    response.sendRedirect("login.jsp") ;   }catch(Exception e){    e.printStackTrace() ;   }  }  if ((psw == "") || (psw==null) || (psw.length() > 20 )){   try{    result = "请输入密码(不能超过20个字符)!" ;    request.setAttribute("message" ,result) ;    response.sendRedirect("login.jsp") ;   }catch(Exception e){    e.printStackTrace() ;   }  }    //登记JDBC驱动程序  try{   Class.forName("org.gjt.mm.mysql.Driver") ;  }catch(ClassNotFoundException e){   e.printStackTrace() ;   System.out.println("Class Not Found Exception . ") ;  }  //连接URL  String url ="jdbc:mysql://localhost:3306/learnJSP" ;  Connection conn = null ;  Statement stmt = null ;  ResultSet rs = null ;    try{   conn = DriverManager.getConnection(url, "root", "root") ;   stmt = conn.createStatement() ;   //SQL语句   String sql ="select * from userInfo where username='"+username+"' and userpsw= '"+psw+"'" ;   rs = stmt.executeQuery(sql) ;//返回查询结果  }catch(SQLException e){   e.printStackTrace() ;  }   HttpSession session =  request.getSession() ;   session.setAttribute("username", username) ;   //System.out.println("+++++++++++++++++++++++"+ username) ;  try{   if (rs.next()){ //如果记录集非空,表明有匹配的用户名和密码,登陆成功       // 登录成功后将username设置为session变量的username          // 这样在后面就可以通过 session.getAttribute("username") 来获取用户名,          // 同时这样还可以作为用户登录与否的判断依据    session.setAttribute("age",rs.getString("age")) ;    session.setAttribute("sex",rs.getString("sex")) ;    session.setAttribute("weight",rs.getString("weight")) ;    response.sendRedirect("success.jsp") ;   }else{    session.setAttribute("message", "用户名或密码不匹配。");    response.sendRedirect("fail.jsp") ;   }  }catch(SQLException e){   e.printStackTrace() ;  } }  private static final long serialVersionUID = 1L;}//--------------------------------------------------------------------------------------------------------------------login.jsp内容:<%@ page language="java" contentType="text/html;charset=gb2312"%><html> <head>  <title>登陆</title> </head> <body>  <form method="POST" name="frmLogin" action="LoginServlet">   <h1 align="center">用户登录</h1><br />   <center>    <table border=1>     <tr>      <td>用户名:</td>      <td>       <input type="text" name="username" value="Your name" size="20" maxlength="20" onfocus="if (this.value=='Your name')  this.value='';" />      </td>     </tr>     <tr>      <td>密&nbsp;&nbsp;码:</td>      <td>       <input type="password" name="password" value="Your password" size="20" maxlength="20" onfocus="if (this.value=='Your password')  this.value='';" />      </td>     </tr>     <tr>      <td>       <input type="submit" name="Submit" value="提交" onClick="return validateLogin()" />      </td>      <td>       <input type="reset" name="Reset" value="重置" />      </td>     </tr>    </table>   </center>  </form>  <script language="javascript">   function validateLogin(){    var sUserName = document.frmLogin.username.value ;    var sPassword = document.frmLogin.password.value ;    if ((sUserName =="") || (sUserName=="Your name")){     alert("请输入用户名!");     return false ;    }        if ((sPassword =="") || (sPassword=="Your password")){     alert("请输入密码!");     return false ;    }   }  </script> </body></html>//--------------------------------------------------------------------------------------------------------------------success.jsp 内容;<%@ page language="java" contentType="text/html;charset=gb2312" pageEncoding ="gb2312"%><html> <head>  <title>欢迎</title> </head> <body>  <%   String userName = (String)session.getAttribute("username") ;   String age = (String)session.getAttribute("age") ;   String weight = (String)session.getAttribute("weight") ;   String sex = (String)session.getAttribute("sex") ;   System.out.println("性别:A" + sex +"A")  ;   if (sex.trim().equals("M")) {    sex ="男" ;   }else{    sex = "女" ;   }  %>  <div align="center">   <%=userName %>   欢迎您,登陆成功!<br />   <font color="blue">登陆用户信息:</font>   <table border =1 >    <tr>     <td>&nbsp;姓名:&nbsp;</td>     <td>&nbsp;&nbsp;<%=userName %>&nbsp;&nbsp;</td>    </tr>    <tr>     <td>&nbsp;年龄:&nbsp;</td>     <td>&nbsp;&nbsp;<%=age %>&nbsp;&nbsp;</td>    </tr>    <tr>     <td>&nbsp;体重:&nbsp;</td>     <td>&nbsp;&nbsp;<%=weight %>&nbsp;kg&nbsp;</>    </tr>    <tr>     <td>&nbsp;性别:&nbsp;</td>     <td>&nbsp;&nbsp;<%=sex %>&nbsp;&nbsp;</>    </tr>   </table>   <a href="login.jsp">返回</a>  </div> </body></html>//--------------------------------------------------------------------------------------------------------------------fail.jsp 内容:<%@ page language="java" contentType="text/html;charset=gb2312" pageEncoding ="gb2312"%><html> <head>  <title>登陆失败</title> </head> <body>  <%   String userName = (String)session.getAttribute("username") ;   String msg  = (String)session.getAttribute("message") ;  %>  <div align="center">   <%=userName %>   对不起,登陆失败!<br />   <font color="red">原因: </font>   <%=msg %>   <br/>   <br/>   5秒后将返回登陆界面。  </div>      <%     response.setHeader("Refresh","5;URL=/learnJSP/login.jsp");       %> </body></html>//--------------------------------------------------------------------------------------------------------------------  mysql数据库中需要创建数据库learnJSP,其中创建表userInfo 创建表语句为:  create database learnJSP ;  use learnJSP   create table userInfo(id int not null primary key,username char(20) not null,userpsw char(20) ,age int ,weight int ,sex enum('M','F')) ;    需要把连接mysql的jar包放到项目的lib目录中//--------------------------------------------------------------------------------------------------------------------web.xml 内容:<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE web-app    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"    "http://java.sun.com/dtd/web-app_2_3.dtd"><web-app> <welcome-file-list>  <welcome-file>index.jsp</welcome-file> </welcome-file-list>  <servlet>        <servlet-name>            LoginServlet        </servlet-name>        <servlet-class>            org.cai.servlet.LoginServlet        </servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>LoginServlet</servlet-name>        <url-pattern>/LoginServlet</url-pattern>    </servlet-mapping> </web-app>//--------------------------------------------------------------------------------------------------------------------
  相关解决方案