This post is a result of frustration. I have been having hard time finding relevant or necessary code when i search for coding examples or actual codes about java or related technologies over the internet. This has been going on for a while, maybe 1 or 2 years. I will try to explain what happened to google searches in the last section of this post. I've had enough of this situation and actually ended up writing some up-to-date starting projects that are actually tested and working with the latest libraries and bare minimum configurations. The tech mix contains JavaFX, OpenCV, Jakarta, JDBC, JSP, JWT, Rest, Hibernate, Spring Framework, Spring Boot, Spring JDBC, Spring JPA, Spring Security and Thymeleaf. Believe me, this is harder than it sounds. Some technologies are hard to combine. Some codes are almost impossible to find. But i will keep my thoughts for the end.
This post is not meant to explain the codes. Instead, it is meant to give you the minimum starting point and i also mentioned some of the key points of them. You can just get them from GITHUB and try running them. Some of the projects will have prerequisites but it is up to you to dig them up inside the comments. Most of them are about database connections. All the necessary information is inside the projects. These are the most up-to-date examples over the internet as of January 2024 using JDK 21. Some of the technologies may seem unnecessary or old or unpopular to you. But if for some reason you end up working with these technologies, you will thank me :) If you don't already have knowledge about these technologies, this post may not help you. And one more note if you want to start with these examples: MAKE ONLY 1 CHANGE AT A TIME !!!. There are lots of connections and dependencies under these simple codes.
The list has no particular order. I tried to sort them from unpopular to popular. The github repository may be updated in the future. I will also update this post if that happens. All the projects that have DB connection, are using postgresql for database but it can be easily swapped with another database at repo classes.
If you are planning on starting a JavaFX desktop project or updating an old project with recent libraries, you can get help from this project. It has sample codes and the javafx-maven-plugin and the module-info.java file is important here. Run it from eclipse or intellij. Starting from command line may not work because you need to pack up the jar file with dependencies.
If you want to go into opencv and start image processing, you can get help from this sample project. It is using JavaFX since it is easier to implement a desktop app in JavaFX. I also know it can be done in a Java Swing app. The important part of this project on top of JavaFX above is OpenCV.loadLocally() in the app. This app can capture webcam or a video file if you want. You don't have to install opencv in your machine to run this example. Run it from eclipse or intellij. Command line may not work because you need to pack up the jar file with dependencies.
This is a mix of JakartaEE 10 and JDBC and Thymeleaf. If you want to avoid Spring Framework and you are used to develop JavaEE applications with EJB back in the day, you may use this project with latest Jakarta specs. You can also use the most popular Thymeleaf frontend here. This project has no security! The web.xml file and the InitializeSerletContext.java file are particularly important here. It runs on Payara but i didn't try it on Tomee. If it meets the JakartaEE 10 specs, it may work.
This is also a project for non-spring fans. You can find a basic configuration of JakartaEE 10, Hibernate and JSP here, which can be easily swapped with Thymeleaf with the help of the project above. Jakarta has no pre-built repositories for Hibernate like Spring Data JPA has CrudRepository interfaces. So i have configured and used Hibernate here with "org.hibernate.Session" and CriteriaApi. Not sure how to use entitymanager here, you may try @PersistanceContext but it will require an xml config too. The placement of the JSP frontend files are important here. Also notice the JSTL and Taglib libraries in the pom xml. This project has no security implemented. It too runs on Payara but i didn't try it on Tomee.
This is simple JakartaEE Restful service project. It has JDBC as repository, which is plain old java JDBC unlike Spring JDBCTemplate. You can easily develop JAX-RS apps with dependency injection alongside. You don't have to use Spring Framework or the old Jersey implementation. The most important part is Application.java since it acts as the starting point of the servlet path. I would also notice the beans.xml file here. This project also has no security and it too runs on Payara but i didn't try it on Tomee.
Boy this one was a challenge. I dare you to use JakartaEE 10, CDI and role based security with JWT together. I will even give you a clue, use HttpAuthenticationMechanism and @RolesAllowed. This project is meant to give a sample secure restful service with user roles. It has JWT mechanism since restful services are mostly secured with JWT. I hope i have done the right way. Using the Jakarta CDI annotations are a bit weird. Every single line of code is important in this project. This one doesn't have DB connection in order to keep it simple. You can inject a repository to mechanism if you want. It runs on Payara but i didn't try it on Tomee.
If you don't want to migrate to Spring Boot and stick to Spring Framework, this project is the latest configuration for Hibernate and JSP. In order to run this project on Tomcat 10, you need glassfish jakarta.servlet.jsp.jstl library. Otherwise, it just runs on Payara. Also you need JSTL library from jakarta servlet for JSP rendering. We are using Spring ORM here, not data jpa, since it is not spring boot and i think it won't be configured here. The defaultservlet-servlet.xml file and BeanFactory.java file is important. I didn't have separate config files for Hibernate, it is in the BeanFactory. The repository has example of both entitymanager and hibernate SessionFactory. Again, no security here either.
If you don't want to migrate to Spring Boot and stick to Spring Framework, this project is the latest configuration for Hibernate and Thymeleaf. It runs on Tomcat 10. We are using Spring ORM here, not data jpa, since it is not spring boot and i think it won't ve configured here. The defaultservlet-servlet.xml file and BeanFactory.java file is important. I didn't have separate config files for Hibernate, it is in the BeanFactory. The repository has example of both entitymanager and hibernate SessionFactory. Again, no security here either.
Restful service projects have security :) This one is another example of Spring Framework without boot. It is using JDBC and Restful services. It also have Spring Security with JWT. I would say the SecurityConfig.java class is the most important here. After that, there are JWTAuthenticationFilter.java and JWTAuthorizationFilter.java respectively. If it actually goes to database and fetches the user information and hands it over to spring security, it will be fully developed. This project runs on Tomcat 10.
This project is an example of Spring Framework with Thymeleaf and JDBC without boot. The BeanFactory.java class looks important. Other than that, this is a very simple project without security. It runs on Tomcat 10.
This project is an example of Spring Framework with Thymeleaf and Spring Security without boot. Almost every single line of code is crucial here. But "templateEngine.addDialect(new SpringSecurityDialect());" took me 3 days to figure out. It is using everything available from spring security - thymeleaf duo and you don't have to use spring boot. thymeleaf-extras-springsecurity6 dependency is required here. It doesn't have database connection but can easily be implemented and injected with the help of other projects. It runs on Tomcat 10.
Here we start with Spring boot, which is an autoconfiguration heaven. This one is using JDBCTemplates and Restful services. This also have Spring Security with a little bit easier configuration compared to non-boot version. The SecurityConfig.java class is the most important i guess. There is also SecurityConfigAlternative.java class if you want to use annotation based security. Also, don't forget to check out UserService.java class. Basically, all files under config package is important :) As usual, runs on Tomcat 10 which is also autoconfigured by spring boot.
I think this is the most popular tech stack these days. This one has Spring Security. Naturally MVC security, not JWT. JPA and Thymeleaf is automatically configured. So i would say the most important file here would be SecurityConfig.java here. Also i have an example of SecurityConfigAlternative for method based security. The Thymeleaf security is also present in the html files. thymeleaf-extras-springsecurity6 dependency is required here. Also application.properties is usually the root of configurations here. Runs on Tomcat 10, which is automatically configured.
This one is a surprise bonus. Because i think my example will be the best ever basic example of UseContext hook in ReactJS on all of the internet. I have been working with reactjs recently but all the usecontext examples i have found have weird business logic inside or some extra unnecessary library or unnecessary custom hook logic or they are just copy paste code or utterly wrong. So i have composed the most basic and usable sample code here. All you need is not more than 20 lines of code. If you don't know what UseContext is, it is basically a wrapper state for all of your application to transfer information from unrelated react components.
This is an example of login and save username in the context to show it in another component scenario. Start with writing your context and its provider in a single file called UsernameContext.tsx
import { createContext, useState } from "react";
// data type of context, not initial values
export const UserContext = createContext({
usernameVariable: "",
setterforusername: (somestring: string) => {},
});
// provider exposes context
export const UserContextProvider = ({ children }) => {
// state initializes from localstorage, it acts like cookie, not mandatory
const [username, setUsername] = useState<string>(localStorage.getItem("username") as string);
// so we are setting state from outside via provider
return (
<UserContext.Provider
value={{
usernameVariable: username,
setterforusername: setUsername,
}}
>
{/* render all components inside */}
{children}
</UserContext.Provider>
);
};
Then you probably have some index.tsx file. Wrap all your components inside the provider. So that you can transfer information among them.
import React from "react";
import { UserContextProvider } from "./components/context/UsernameContext";
const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement);
root.render(
<React.StrictMode>
<UserContextProvider>
{/* all components here */ }
</UserContextProvider>
</React.StrictMode>
);
Then you probably have some login operation somewhere. This file has unnecessary code but it has a button click and simulating login and navigating to main screen after login without refreshing the page.
import { Button } from "react-bootstrap";
import { useNavigate } from "react-router-dom";
import { UserContext } from "../context/UsernameContext";
import { useContext } from "react";
export default function LoginComponent() {
const mynavigate = useNavigate();
const ourUserContext = useContext(UserContext);
// you are probably using axios and react router
// you are setting the username value to context
function handleSubmitAdmin() {
axios.post("someurl/login", { username: "admin", password: "password" }).then((response) => {
// store it in the localstorage, just like a cookie, not mandatory though
localStorage.setItem("username", username);
// setter metod of our context
// which is the only 1 line of code necessary here !!!
ourUserContext.setterforusername(username);
// no need to refresh whole page
mynavigate("/");
});
}
// this is a bootstrap button, could be simple react button of course
return (
<Button variant="outline-success" onClick={handleSubmitAdmin}>
Admin Login
</Button>
);
}
The idea is to refresh another part of the screen, another component under the user provider which provides a context that has a state inside. So you probably have a menu on top or on the left. All you have to do in order to refresh the username information after login here is 2 lines of code.
import { useContext } from "react";
import { UserContext } from "../context/UsernameContext";
export default function MenuComponent() {
// menu on the left, this one reads username from context
const ourUserContext = useContext(UserContext);
return (
<h4>{ourUserContext.usernameVariable}</h4>
);
}
And that's it for the usecontext. Don't search google about it, you will get lost inside a rabbit hole. Even the official documentation is limited and not useful. This is where i start mentioning the awful situation we are facing while actually looking for something on google these days.
I have been programming for like 15 years straight. There has never been a time where i was having this much trouble finding useful information on the internet. This is not just Google 's fault, it is also because of copycats and thieves and opportunitists all together. Let me explain why i think this blog post is almost like a treasure and how i got frustrated this much.
Google used to be a keyword search engine. But for the last 2 years or so, probably with the AI evolution, it is trying to be a context search engine. A keyword search is mostly what us programmers need. Because you usually look for specific piece of code to try or copy paste. This is not ideal for self development but it is another subject. Now, google promotes itself as an AI search and expects you to define what is the problem or what you are looking for. So we used to search words before and now we are asking questions. Questions like "how can i do that without doing that" or "why is this happening this way". You think this is better?
No !! Because google or or any AI today does not have that much insight about programming. Our job is about algorithms and design. Not story telling or pre-defined rules. Google understands your question (somehow i guess) and looks for the best possible answer even if you try to force it towards a specific detail. For a hypothetical example "how can i write a filter with jakarta and create messagecontext and inject it inside a restful endpoint". This is literally as specific as i can get. But google takes this question part by part and brings you the most popular answer. I will explain that "most popular" in a minute.
Now google will dissect this statement and will give me usages of messagecontext or jakarta get request mapping examples. None will actually combine them properly. Which is the insight that we are missing. So your best bet is github or stackoverflow. There is no code search in github, which should really exist :D Stackoverflow has thousands of unanswered questions and even if you find a similar issue, it will contain a completely different reasoning or mentality or bussiness case. So you go back to google and search for words with quotation marks. So that it can match exactly what you need. But guess what. It ignores them :D I have literally seen a lots of example where google just returns search results and says "this doesn't contain that word". Why ???
Alongside this, let's talk about the most popular thing. Google also started thinking that the most popular code or idea on the internet is probably what you are looking for. This is a serious threat to humanity. I'm not kidding. If popularity is a criteria of truth, we are doomed with mindless and couragous fatal mistakes. Google will get you most up-voted results on stackoverflow or most followed reddits or most subscribed blogs. We used to say the best place to hide something is the 2nd page of google, because nobody looks there. Now i have lots of examples where i scroll through 100 results and find a clue. Something really weird happened to google but something even worse happened to us. Now it is time to talk about us. (Well, except myself :)
First the copycats. Disinformation is one thing, changing the nature of information, but it is another subject. We have people copying and pasting all sorts of information, not just about programming, on the internet. This can be false information or it is theft for the very least. I have seen blogs written as a direct copy paste of documentations or wikipedia. I have seen stackoverflow answers like this too. We also have crawlers these days, which is a tool to scan a website and copy all of its contents. The worst part is, if they are disseminating false information, it becomes popular and google thinks it is what you are looking for.
Even if you get rid of all these problems in an ideal world, people are drawn into popular subjects too. Or they can't explain complex concepts simply. Or they just disregard the details that are what really matter. You can't easily find Jakarta examples online, since spring framework is a lot more popular and has a bigger community. But spring framework does not always have to be a necessity. Even if you find related codes, people usually lack the documentation habit, even if it is official documentation. Let's assume you find some code to try and debug and understand, lots of people ignore the inner workings of the code. I have a saying "there is no lesser code, there is invisible code". If you are giving an example of something, please explain the unseen too. Or don't even bother, since even ChatGPT can do that, maybe even better than you. Don't waste my time.
And the last issue, lots of blog writers or tutors or instructors are failing to draw a big picture and make sense of the complex code by simplifying it. This is why i have the UseContext hook example here. Nobody have to understand your business logic or 3rd party library usage or your way of component or UI designing or proptypes or typescript array operations or ...etc. Believe me i have witnessed horrifying code examples with like a 100 lines of code for a 15 lines of necessary code. Oh also remember, we have the idiot copycats. And google thinks they are the right answers. So yeah, screw it, i can write it on my own. And i did :D
The internet is almost everywhere, information is almost everywhere. But it is becoming harder and harder to get useful or even correct information out there. This is due to several reasons. I have experience in my field but for the people who are starting to learn programming these days, the situation will affect you severely. That is why tutoring is becoming increasingly important these days. Don't worry i am not going to start a sponsor message like brilliant.org or something :D I will write about what is software tutoring later. It is not just showing code, it is not just citation. I wish all you developers bugfree days. See you at the next post :)
Leave a comment