In my conclusion, simply put all JAR files to WEB-INF/lib/, without any other adjustments, your NoClassDefFoundError will be gone.
See https://tomcat.apache.org/tomcat-7.0-doc/appdev/deployment.html
| Standard Directory Layout |
|
I'm a software engineer, interested learning the best technologies, and contribute to the industry.
| Standard Directory Layout |
|
public static ResultSet executeQuery(String sql, String[] parameters){
DataSource ds = DBConnector.setupDataSource();
try (
Connection conn = ds.getConnection();
PreparedStatement ps = createPreparedStatement(conn,sql,parameters);
ResultSet rs = ps.executeQuery();
) {
CachedRowSet rowset = new CachedRowSetImpl();
rowset.populate(rs);
return rowset;
} catch (SQLException e) {
Logger lgr = Logger.getLogger(SqlHelper.class);
lgr.log(Level.WARNING,e.getMessage(),e);
}
return null;
}
filter-mapping element contains a url-pattern that matches the request are added to the chain in the order they appear in the web.xml deployment descriptor.<filter-mapping> <filter-name>LogFilter</filter-name> <servlet-name>*</servlet-name> </filter-mapping> <filter-mapping> <filter-name>ALogFilter</filter-name> <servlet-name>*</servlet-name> </filter-mapping> <filter-mapping> <filter-name>BLogFilter</filter-name> <servlet-name>*</servlet-name> </filter-mapping>
@WebFilter(filterName="LogFilter", urlPatterns="/*")
public class LogFilter implements Filter {
private FilterConfig filterConfig;
/**
* Default constructor.
*/
public LogFilter() {
}
public void destroy() {
filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
String uri = httpRequest.getRequestURI();
String sequence = (String)request.getAttribute("sequence");
request.setAttribute("sequence", sequence+" LogFilter ");
if(uri.startsWith(httpRequest.getContextPath()+"/ValidateCode") || uri.startsWith(httpRequest.getContextPath()+"/imgs") || uri.startsWith(httpRequest.getContextPath()+"/LoginView")){
chain.doFilter(request, response);
}
else{
HttpSession session = httpRequest.getSession();
User user = (User)session.getAttribute("user");
if(user!=null) chain.doFilter(request, response);
else ((HttpServletResponse)response).sendRedirect(httpRequest.getContextPath()+"/LoginView?L");
}
}
public void init(FilterConfig fConfig) throws ServletException {
this.filterConfig = fConfig;
}
}
@Target(value=ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLTable {
String value(); //table name
}
@Target(value=ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLField {
String column();
String type();
int length();
}
@SQLTable("student")
public class Student {
@SQLField(column="id",type="int",length=10)
private int id;
@SQLField(column="name",type="varchar",length=10)
private String studentName;
@SQLField(column="age",type="int",length=3)
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Demo2 {
@Test
public void test(){
try{
Class clazz = Class.forName("model.Student");
//(1)get all annotations for the class
Annotation[] annotations = clazz.getAnnotations();
for(Annotation a: annotations){
System.out.println(a);
}
//(1) get the specified annotation for the class
SQLTable table = (SQLTable) clazz.getAnnotation(SQLTable.class);
System.out.println(table);
//(2) get annotation for the field
Field f = clazz.getDeclaredField("studentName"); //get the target field from class
SQLField myField = f.getAnnotation(SQLField.class); //get the annotation for this field
//use function declared in annotation
System.out.println(myField.column()+","+myField.type()+","+myField.length());
//based on (1) and (2), we can build up all info for the related sql table
}catch(Exception e){
}
}
}
//@Target(value=ElementType.METHOD)
@Target(value={ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation01 {
String studentName() default "";
int age() default 0;
int id() default -1;
String[] schools() default {};
}
@CustomAnnotation01(schools = { "" })
public class Demo1 {
@CustomAnnotation01(studentName="AAA",age=0,id=1001,schools={"aaa","bbb"})
public void test(){
}
}
@Override //mark as override function from super classes
public String toString(){
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
/**
* The set of warnings that are to be suppressed by the compiler in the
* annotated element. Duplicate names are permitted. The second and
* successive occurrences of a name are ignored. The presence of
* unrecognized warning names is not an error: Compilers must
* ignore any warning names they do not recognize. They are, however,
* free to emit a warning if an annotation contains an unrecognized
* warning name.
*
* Compiler vendors should document the warning names they support in
* conjunction with this annotation type. They are encouraged to cooperate
* to ensure that the same names work across multiple compilers.
*/
String[] value();
}
ServletContext servletContext = this.getServletContext();
//ServletContext servletContext servletContext = this.getServletConfig().getServletContext();
servletContext.setAttribute("ABC", new Object()); //(String, Object)
<context-param>
<param-name>Country</param-name>
<param-value>China</param-value>
</context-param>
request.getServletContext().getInitParameter("Country");
Properties pp = new Properties();
InputStream fis = getServletContext().getResourceAsStream("WEB-INF/settings.properties");
pp.load(fis);
getServletContext().getRealPath("WEB-INF/settings.properties");
public class ValidateCodeService {
static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static Random rnd = new Random();
public static String createRandomString(int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++)
sb.append(AB.charAt(rnd.nextInt(AB.length())));
return sb.toString();
}
public static Image getImage(String code) {
BufferedImage image = new BufferedImage(80, 30,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 80, 30);
g.setColor(Color.BLACK);
g.setFont(new Font(null, Font.BOLD, 20));
g.drawString(code, 0, 20);
return image;
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setDateHeader("Expires", -1);
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setHeader("Content-Type", "image/jped");
String code = ValidateCodeService.createRandomString(4);
request.getSession().setAttribute("ValidateCode", code);
Image image = ValidateCodeService.getImage(code);
ImageIO.write((RenderedImage) image, "jpg", response.getOutputStream());
}
out.println(
"Validation Code: <input type='text' name='ValidateCode'/>"
+"<img id='ValidateCodeImg' src='"+request.getContextPath()+"/ValidateCode'>"
+"<a href='#' rel='nofollow' title='Refresh Image' onclick=\"document.getElementById('ValidateCodeImg').src = '"+request.getContextPath()+"/ValidateCode?'+Date.now();return false;\">"
+"Refresh"
+"</a>"
+"<br>");
public String MD5(String md5) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
Logger lgr = Logger.getLogger(UserService.class);
lgr.log(Level.WARNING, e.getMessage(), e);
}
return null;
}
HttpSession session = request.getSession();
session.setAttribute("data", data);
Cookie cookie = new Cookie("JSESSIONID",session.getId());
cookie.setMaxAge(60*30); //session timeout in 30 minutes
response.addCookie(cookie);
HttpSession session = request.getSession();//get session, if no session, create a new one //HttpSession session = request.getSession(true); //same as no parameter //HttpSession session = request.getSession(false); //if no session, return null session.setAttribute(String, Object); session.setMaxInactiveInterval(30); // precise in secondsGet Session
request.getSession(); session.getAttribute(String); //return null if not existsDelete object from Session
session.removeAttribute(String);Unbind Session
request.getSession();
session.invalidate(); //destroy the session, unbind all objects in session
//Normally used when safe sign out
<session-config>
<session-timeout>30</session-timeout>
</session-config>
void | destroy()Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. |
ServletConfig | getServletConfig()Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. |
java.lang.String | getServletInfo()Returns information about the servlet, such as author, version, and copyright. |
void | init(ServletConfig config)Called by the servlet container to indicate to a servlet that the servlet is being placed into service. |
void | service(ServletRequest req, ServletResponse res)Called by the servlet container to allow the servlet to respond to a request. |
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nowTime = format.format(new java.util.Date());
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2016-4-24");
| Date and Time Pattern | Result |
|---|---|
"yyyy.MM.dd G 'at' HH:mm:ss z" | 2001.07.04 AD at 12:08:56 PDT |
"EEE, MMM d, ''yy" | Wed, Jul 4, '01 |
"h:mm a" | 12:08 PM |
"hh 'o''clock' a, zzzz" | 12 o'clock PM, Pacific Daylight Time |
"K:mm a, z" | 0:08 PM, PDT |
"yyyyy.MMMMM.dd GGG hh:mm aaa" | 02001.July.04 AD 12:08 PM |
"EEE, d MMM yyyy HH:mm:ss Z" | Wed, 4 Jul 2001 12:08:56 -0700 |
"yyMMddHHmmssZ" | 010704120856-0700 |
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" | 2001-07-04T12:08:56.235-0700 |
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" | 2001-07-04T12:08:56.235-07:00 |
"YYYY-'W'ww-u" | 2001-W27-3 |
Cookie cookie = new Cookie("name","abc"); //new Cookie(String,String)
cookie.setMaxAge(1000);
//in seconds, default if not set: cleaned when browser closed
response.addCookie(cookie); //remember to call addCookie
Cookie cookies[] = request.getCookies(); //return null if none cookies
for(int i=0;i<cookies.length;i++){
Cookie cookie = cookies[i];
cookie.getName();
cookie.getValue();
cookie.getMaxAge();
}
String val = java.net.URLEncoder.encode("中国字","utf-8");
Cookie cookie = new Cookie("name",val);
Getting
String val = java.net.URLDecoder.decode(cookie.getValue(),"utf-8");
String filePath = this.getServletContext().getRealPath("abc.text");
FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = bufferedReader.readLine();
//do with line
bufferedReader.close();
fileReader.close();
@WebFilter("/CharacterEncoding")
public class CharacterEncoding implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8"); //set request character encoding
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
<filter> <filter-name>CharacterEncoding</filter-name> <filter-class>com.gvace.notebook.web.filter.CharacterEncoding</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<!-- Encoding with spring filter --> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
String val = java.net.URLEncoder.encode("中国字","utf-8");
Cookie cookie = new Cookie("name",val);
GettingString val = java.net.URLDecoder.decode(cookie.getValue(),"utf-8");
Properties file
For character encoding in properties file
Use native2ascii from jdk/bin/, copy the String into native2ascii, it will translate to ascii
GET /test/hello.html HTTP/1.1
Accept: */*
Referer: http://localhost:8080/test/abc.html
Accept-Language: zh-cn
User-Agent: Mozilla/4.0
Accept-Encoding: gzip, deflate
Host: localhost:8080
Connection: Keep-Alive
[empty line]
dataname1=data1
dataname2=data2
Request Methods:
State Code