一 servlet概述和简单创建
servlet 是java server applet 的简称,称为小服务器程序,用于功能交互式浏览和修改数据,生成动态web内容;
创建的时候在包下new找创建servlet,就有一个直接写好的框架;
2.常见的错误
1.404 资源找不到:a.网站上面跟value不一样,
b.tomcat上没有更改文件夹
2.400 badRequest 客户端请求有语法错误,不能被服务器所理解
3.403服务器收到请求,但是拒绝提供服务
4.500 不可预知错误
5.503当前不能处理客户端请求,一段时间后可能会恢复正常。
两种创建方式 1实现servlet接口 2.继承httpservlet
1.实现servlet接口
@WebServlet(name = "MyServlet",value = "/myservlet")//value需要写上,斜杠写上,在Tomcat改好配置,在网站上直接写这个即可访问
public class Servlet implements javax.servlet.Servlet {
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("初始化servlet---init"+this.hashCode());
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("服务方法---------------service--------"+this.hashCode());
}
@Override
public String getServletInfo() {
System.out.println("获取Servlet配置------------getServletConfig----"+this.hashCode());
return null;
}
@Override
public void destroy() {
System.out.println("------销毁----------destroy---------"+this.hashCode());
}
}
2.继承 点击servlet即可里面创建一个
@WebServlet(name = "UseServlet")
public class UseServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
@webservlet注解里面 name可以随便写,value配置url路径 ,urlpatterns 和value作用一样不能同时使用,loadonstartup配置创建时机,0或者正数启动程序时建立,负数时访问时创建。数字越小优先级越高。
获取表单的信息:
html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>欢迎页面</title>
</head>
<body>
<h1>欢迎你</h1>
<div>
<form action="HelloServlet">
<label>姓名:</label><input name="name"><br/>
<label>年龄:</label><input name="age"><br/>
<input type="submit" value="提交">
</form>
</div>
</body>
</html>
servlet代码
@WebServlet(name = "FormServlet")
public class FormServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String age = request.getParameter("age");
//获取姓名可能会出现乱码
name=new String(name.getByte("ISO8859-1"),"utf-8");
System.out.println(request.getRemoteAddr()+"发过来的信息姓名和电话"+name+age);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
注册信息的提交代码
register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<h1>用户注册</h1>
<form action="/myxiaomi/registerservlet" method="post">
<table>
<tr>
<td>用户名:</td>
<td>
<input type="text" name="username">
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<input type="password" name="pwd">
</td>
</tr>
<tr>
<td>确认密码:</td>
<td>
<input type="password" name="repwd">
</td>
</tr>
<tr>
<td>邮箱:</td>
<td>
<input type="email" name="email">
</td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name="gender" value="男" checked="checked">男
<input type="radio" name="gender" value="女">女
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>
servlet代码
@WebServlet(name = "RegistServlet",value = "registservlet")
public class RegistServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//注册
//1.解决编码问题
request.setCharacterEncoding("utf-8");
response.setContentType("type/html;charset=utf-8");
//2.获取数据
String username = request.getParameter("username");
String password = request.getParameter("password");
//3.验证数据是否可以收到正常的数据
PrintWriter out = response.getWriter();
if (username==null||username.trim().equals("")){
out.write("用户不能为空");
return;
}
if (password==null||password.trim().equals("")){
out.write("密码不能为空");
return;
}
//4.把数据保存到数据库中,下面的这些用到了与数据库的连接
Connection connection=null;
PreparedStatement preparedStatement=null;
try {
//a.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//b.获取连接
connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/db_shopping", "root", "0810" );
//c.创建命令
preparedStatement=connection.prepareStatement("insert into tb_user(username,password) values(?,?)");
//d.设置参数
preparedStatement.setString(1,username );
preparedStatement.setString(2,password );
//e.执行sql命令
int result=preparedStatement.executeUpdate();
if (result>0){
out.write("注册成功");
}else {
out.write("注册失败");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if (connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement!=null){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
request和response
重定向 通过各种方法将网络重新定个方向转到其他位置
java web服务端控制页面跳转主要有两种:重定向和转发
html代码 index
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>网站首页</title>
</head>
<body>
欢迎进入xxx管理系统............
</body>
</html>
html首页代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<div>
<form action="/day12web1/login" method="post">
<label>账号:</label><input name="un"/><br/>
<label>密码:</label><input type="password" name="pw"/><br/>
<input type="submit" value="登录"/>
</form>
</div>
<h5><a href="register.html">还没账号请注册</a></h5>
</body>
</html>
重定向java代码
@WebServlet(name = "reServlet")
public class reServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String age = request.getParameter("age");
//服务器输出打印
System.out.println(name+age);
//重定向
response.sendRedirect("index.html");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
路径问题:
绝对路径:用于不同网站之间的跳转,写的很全问题不大
相对路径:用在同一个网站中,仅限静态资源,页面比较多的时候使用框架会出现混乱。
根路径:根指定就是主机名 表示http://localhost:8080/
servlet中可以使用的内置对象主要有:request response application session out(printwrite)
response练习:用户下载服务器图片代码,图片放到web文件夹下面
@WebServlet(name = "ImgServlet",value = "/imgservlet")
public class ImgServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.读取
ServletContext application = this.getServletContext();
String realPath = application.getRealPath("24.jpg");
response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode("叶承卓.jpg","utf-8" ));
FileInputStream fis=new FileInputStream(realPath);
ServletOutputStream os=response.getOutputStream();
byte[] buf=new byte[1024*4];
int len=-1;
while ((len=fis.read(buf))!=-1){
os.write(buf,0,len);
}
fis.close();
os.close();
System.out.println("执行完毕");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
2.页面中添加验证码:
@WebServlet(name = "CodeServlet",value = "/codeservlet")
public class CodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Validatecode code=new ValidateCode(200,50,6,200);
System.out.println(code.getCode);
code.write(response.getOutputStream());
}
}
封装请求参数:
将数据封装到实体类上,
a.使用getparameter获取string
b.使用反射解析
c.使用beanutils进行快速映射,导出beanutils对应的jar包,logging日志,commons-collection-3.2.1.jar,映射2
BeanUtils.populate(bean2,request.getParameterMap());
system.out.println(bean2);