Những vấn đề jsp servlet
Java Web 2016
//Hiển thị giá trị Object với JSTL
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>//Thư viện c
<%
String id = request.getParameter("id");
ShopJpaController SJC = new ShopJpaController();
Shop shop = SJC.findShop(id);
request.setAttribute("shop", shop);
%>
<c:out value="${shop.getName() }"></c:out> //Out: Object
//SENT OBJECT WITH Session
HttpSession session = request.getSession(true);
session.setAttribute("item", list);
//SENT OBJECT WITH Request
if (true) {
ArrayList<Person> list = my.showPerson();
request.setAttribute("item", list);
//Sent with request
RequestDispatcher rd = request.getRequestDispatcher("Search.jsp");
rd.forward(request, response);
} else {
response.sendRedirect("Help.jsp"); //Sent no requet
}
//GET Object on page jsp
<%
List<Person> list = (ArrayList) request.getAttribute("item");
for (Person p : list) {
%>
//Hiển thị giá trị List với JSTL
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> //Thư viện c
<%
List<Product> list = new productDAO().getAllProduct();
request.setAttribute("list", list);
%>
<c:forEach var="L" items="${list}">
<c:out value="${L.description}" /> //Out List
</c:forEach>
//Định dạng tiền tệ
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>//Thư viện c
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> // Thư viện fmt
<c:forEach var="item" items="${shop}">
<fmt:formatNumber type="number" value="${item.getPrice() }" /> //Out: 125,000,000 VND
</c:forEach>
//Get path URL project
<%=request.getContextPath() %>
${pageContext.request.contextPath}
//Tạo Session
HttpSession session = request.getSession(true);
session.setAttribute("user", "Welcome " + user);
//Lấy Session
HttpSession session = request.getSession()
session.getAttribute("user")
//Logout Session
request.getSession().invalidate();
//Hello Session and Link login logout
<span>Welcome: ${sessionScope.user } </span><br/>
<c:choose>
<c:when test="${not empty sessionScope.user}">
<a href="logoutServlet">Logout</a>
</c:when>
<c:otherwise>
<a href="login.jsp">Login</a>
</c:otherwise>
</c:choose>
<c:if test="${not empty sessionScope.user}">
<li><a href="/register.jsp">Register</a></li>
</c:if>
NOTE:
<c:choose>
<c:when test="${..}">...</c:when> <!-- if condition -->
<c:when test="${..}">...</c:when> <!-- else if condition -->
<c:otherwise>...</c:otherwise> <!-- else condition -->
</c:choose>
view
//Visit đến url định sẵn không Send cùng request
response.sendRedirect("url");
response.sendRedirect(request.getContextPath()+"/admin.jsp");
//Visit và Send cùng request và giữ nguyên url servlet
request.getRequestDispatcher("url").forward(request, response);
request.getRequestDispatcher(request.getContextPath()+"/admin.jsp").forward(request, response);
//Upload file or images
<form id="form1" action="url" method="post" enctype="multipart/form-data">
//Thêm vào phần đầu servlet để fix lỗi không lấy được giá trị getParameter("");
@MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 10,
maxFileSize = 1024 * 1024 * 50,
maxRequestSize = 1024 * 1024 * 100
)
//Upload file image với jsp servlet dến folder và lấy tên của image save vào Entity
VD: Shop shop = new Shop();
=>> shop.setImage(UploadFile(request));
private String uploadFile(HttpServletRequest request) throws IOException, ServletException {
String fileName = "";
String UPLOAD_DIR = "images";
try {
Part filePart = request.getPart("photo"); //photo là tên đặt trong <input type="file" name="photo"/>
fileName = (String) getFileName(filePart);
String applicationPath = request.getServletContext().getRealPath("");
String basePath = applicationPath + File.separator + UPLOAD_DIR + File.separator;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
File outputFilePath = new File(basePath + fileName);
inputStream = filePart.getInputStream();
outputStream = new FileOutputStream(outputFilePath);
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (Exception e) {
e.printStackTrace();
fileName = "";
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (Exception e) {
fileName = "";
}
return fileName;
}
private String getFileName(Part part) {
final String partHeader = part.getHeader("content-disposition");
System.out.println("*****partHeader :" + partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Đếm số lượt truy cập trang</title>
</head>
<body>
<%
Integer hitsCount =
(Integer)application.getAttribute("hitCounter");
if( hitsCount ==null || hitsCount == 0 ){
/* First visit */
out.println("Welcome to my website!");
hitsCount = 1;
}else{
/* return visit */
out.println("Welcome back to my website!");
hitsCount += 1;
}
application.setAttribute("hitCounter", hitsCount);
%>
<center>
<p>Total number of visits: <%= hitsCount%></p>
</center>
</body>
</html>
----Lỗi XSS trên web JSP---Viết như này sẽ bị lỗi xss <%=name %> <%=<b>name</b> %> Nếu người dùng trèn code html vào theo name => lỗi xss Thì khi hiển thị sẽ thành chữ đậm name JSTL: fix lỗi xss <c:out value="${nameJSTL }"></c:out> Strust2: fix lỗi xss <s:property value="#L.id" />
----Lỗi SQLI gọi là SQL Injection----https://giai-ma.blogspot.com/2016/10/nhung-van-e-ve-struts2-framework.htmlLỗi này Hacker có thể lấy được Username và Password nguy hiểm cao hơn XSS.Lỗi SQLi: VD: SELECT * FROM users WHERE name = '" + userName + "'; FIX Lỗi: VD: Select * From user Where name=?; stmt.setString(1, name);
0 nhận xét:
Post a Comment