最近用servlet和jsp写一注册与登录模块:代码下载,猛戳这里
梗概如下:
将表单中的用户数据插入到数据库,插入之前,要查询用户名是否存在,如果存在,则跳转到注册页面,提示用户名已经存在,重新输入,注册成功,则跳转到登录页面。
涉及知识:mysql,jdbc,servlet和jsp,以及mvc分层思想。
步骤一:使用mysql数据库建表
create database jd; create table t_user( id bigint primary key auto_increment, username varchar(50) unique, name varchar(50), pwd varchar(20), gendar char(1) );
步骤二:创建一个web工程:
a,User实体类
b,dao类
c,regist.jsp,login.jsp
e.uti工具类
d.web类,包括AddUserServlet.java,ListUserServlet.java,LoadUserServlet,ModifyUserServlet,DelUserServlet,等servlet类。
步骤三:导入mysql驱动,配置web.xml等
该模块我还没有写我完,目前碰到一下主要异常,解决方式记录一下,以备后查:
1,
java.lang.IllegalArgumentException: Invalid <url-pattern> other in servlet mapping
原因web.xml配置错误,在错误的地方加了注释<!-- -->,导致错误
2,jsp向servlet中传值时出现异常。
jsp文件内容为:
<form action="login" method="post"> 用户名:<input type="text" name="username2"> <br/> 密 码:<input type="password" name="pwd2"> <br/> <input type="submit" value="登陆"> </form>
servlet中的内容为:
conn=DBUtil.getConnection(); //该语句获取jsp中传来的username2 String username=request.getParameter("username2"); //获取jsp中传来的pwd2 String pwd=request.getParameter("pwd2"); PreparedStatement prep = conn.prepareStatement("select username,pwd from " + "t_user where username=?"); prep.setString(1, username); //执行查询结果 ResultSet rs=prep.executeQuery(); //String str1=rs.getString("username"); if(rs.next()){ String str2=rs.getString("pwd");}
如果省略了if(rs.next())语句则会出现如下错误。
java.sql.SQLException: Before start of result set
3,请求的资源不被允许。
type: Status report message: HTTP method GET is not supported by this URL description: The specified HTTP method is not allowed for the requested resource (HTTP method GET is not supported by this URL).
原因如下:
1,继承自HttpServlet的Servlet没有重写对于请求和响应的处理方法:doGet或doPost等方法;默认调用父类的doGet或doPost等方法;
2,父类HttpServlet的doGet或doPost等方法覆盖了你重写的doGet或doPost等方法;
不管是1或2,父类HttpServlet的doGet或doPost等方法的默认实现是返回状态代码为405的HTTP错误表示,对于指定资源的请求方法不被允许。
解决方法:
1,子类重写doGet或doPost等方法;
2,在你扩展的Servlert中重写doGet或doPost等方法来处理请求和响应时不要调用父类HttpServlet的doGet或doPost等方法,
即去掉super.doGet(request, response)和super.doPost(request, response);