JavaWeb注意事项
一、路径
在Application context处,表示打开的默认路径,不写就是localhost:8080,写了就是相对路径localhost:8080/......
二、Mapping问题
- 一个Servlet可以指定一个映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
- 一个Servlet可以指定多个映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello1</url-pattern>
</servlet-mapping>
- 一个Servlet可以指定通用映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
- 指定后缀访问 在那个页面都可访问到 *.kk前面不能加上/以及路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.kk</url-pattern>
</servlet-mapping>
- 指定一个error类
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>com.kk.servlet.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
- 定义有优先级 找的到就去 找不到才默认error
三、ServletContext
-
共享数据
public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); writer.println("hello servlet"); ServletContext context = this.getServletContext(); String username = "kk"; context.setAttribute("username",username);//将一个数据保存在ServletContext中, // 名称为username,此文件在Servlet中唯一 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } } -
获取初始化参数
<!-- 配置web初始化的参数 --> <context-param> <param-name>url</param-name> <param-value>jdbc://localhost:3306/mybatis</param-value> </context-param>protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); String url = context.getInitParameter("url"); resp.getWriter().println(url); } -
请求转发
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); //RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//请求转发的路径 //requestDispatcher.forward(req,resp);//使用forward进行转发 context.getRequestDispatcher("/gp").forward(req,resp); }转发和重定向的区别:
相同点
- 页面都会发生跳转
不同点
-
请求转发时,url不会发生变化 307
-
重定向url发生变化 302
重定向使用时最好加上项目路径和对应文件路径,跳转则不用
resp.sendRedirect(req.getContextPath()+"/login.jsp");//重定向要写ContextPath,转发不用 -
读取资源文件
Properties
- 在java目录下新建db.properties文件
- 在resources目录下新建db.properties文件
发现都在同一个目录下 :classes 俗称:classpath
因此创建一个文件流来读取信息
public class ServletDemo05 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //指向target目录下的db.properties InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); Properties prop = new Properties(); prop.load(is); String user = prop.getProperty("username"); String pwd = prop.getProperty("password"); resp.getWriter().println(user+": "+pwd); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }Cookie
四、Cookie和Session
4.1 Cookie
- 拿到cookie
- 传输到服务端
Cookie[] cookies = req.getCookies();//获取cookie
cookie.getName();//获得key
cookie.getValue();//获得value
Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");//新建cookie
cookie.setMaxAge(24*60*60);//设置保持时间
resp.addCookie(cookie);//传输到服务端
//防止乱码
URLEncoder.encode("中文","utf-8");//编码
URLDecoder.decode(cookie.getValue(),"utf-8");//解码
4.2 Session
Session和Cookie的区别:
- Cookie是把用户的数据写给用户的浏览器,浏览器保存(可保存多个)
- Session把用户的数据写到用户独占Session中,服务端保存(保存重要的信息,减少服务器资源的浪费)
- Session对象由服务创建
使用场景
- 整个网站都会经常使用的数据
- 购物车
设置自动过期
<!--设置Session失效时长-->
<session-config>
<!-- 时长为15分钟,单位为分钟-->
<session-timeout>15</session-timeout>
</session-config>
五、JSP
5.1 jsp基本语法
jsp表达式
<%= new java.util.Date()%>
jsp脚本片段
<%
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
out.print("<h1>Sum="+sum+"</h1>");
%>
jsp声明
<%!
static{
System.out.print("kk");
}
%>
jsp声明:会被编译到jsp所生成的相对应的java类中,其他的语句就会在jspService方法体中呈现
jsp的注释不会显示 html的注释会被显示
jsp指令
<%-- 融合三个为一个 变量等不能重复 --%>
<%@include file="common/header.jsp"%>
<h1>jsp3</h1>
<%@include file="common/footer.jsp"%>
<%-- 拼接三个 还是三个 变量等能重复 --%>
<jsp:include page="common/header.jsp"></jsp:include>
<h1>jsp3</h1>
<jsp:include page="common/footer.jsp"></jsp:include>
5.2 内置对象
<%
pageContext.setAttribute("name","kk");//保存的数据只在一个页面有效
request.setAttribute("name","kk");//保存的数据只在一次请求中有效,转发保留数据
session.setAttribute("name","kk");//保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
application.setAttribute("name","kk");//保存的数据只在服务器中有效,从打开浏览器到关闭浏览器
%>
request: 用户用完就扔
session:用完但没完全用完,先留着 如:购物车
application:我就要留着 如:聊天数据
5.3 JSP标签 JSTL标签 EL表达式
格式化标签
六、项目开发过程
6.1 资源管理
- 关于connection、prestatement、resultSet的关闭遵循谁创建,谁关闭。
//Dao
BaseDao.closeResource(null,pstm,rs);
//service
try {
//此处获取一个新的connection,最后关闭此对象中创建的所有资源
connection = BaseDao.getConnection();
//业务层调用对应的具体数据库操作
user = userDao.getLoginUser(connection, userCode);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
return user;
//servlet
public User login(String userCode, String password) {
Connection connection = null;
User user = null;
try {
//此处获取一个新的connection,最后关闭此对象中创建的所有资源
connection = BaseDao.getConnection();
//业务层调用对应的具体数据库操作
user = userDao.getLoginUser(connection, userCode);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
return user;
}
- 访问对象结束时,需要关闭
req.setAttribute("message","修改密码成功,请退出重新登陆");
//密码修改成功,移除Session
req.getSession().removeAttribute(Constants.USER_SESSION);
浙公网安备 33010602011771号