pulling session attribute from url into webpage - java

From the URL of a page I want the "name" attribute to be displayed on the HTML page like let's say, Welcome ${name}
For example, localhost:8080/index?name=dave, then in the HTML page it should display as mentioned above.
Main question is what is the syntax to pull it onto an HTML page? As in JSP, it is ${name} but I don't know for HTML.
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
#Controller
public class IndexController {
#RequestMapping("index")
public String index(HttpServletRequest req) {
HttpSession session = req.getSession();
String name = req.getParameter("name");
if (name != null) {
System.out.println("Hi! " + name);
} else {
System.out.println("Hi");
}
session.setAttribute("name", name);
return "index";
}
}
The console displays the text name="Dave", but in the page with URL localhost:8080/index?name=Dave, I have typed Welcome ${name}, but the name doesn't show up.

Related

Fetch thymeleaf fragments from external URL

I have a spring-boot/thymeleaf website on server A, and I want to load some fragments from server B. The fragments are dynamic and some of them call java methods defined in server A, so what I need is to fetch those fragments (as plain text?) from server B and include them in my html pages in server A, where they will be processed etc. Server B will act like a repository, it won't do any processing at all, just serve the fragments to server A.
Is this possible?
Ok, I posted this question because all my attempts were failing, but after all it was just a typo that was holding me back... So here's what worked for me, in case anyone is interested:
I saved the fragments in src/main/resources/static/fragments on server B. Let's assume a file named frg with a fragment called "content" inside it.
I created a controller in server B to serve the files as plain text, like this:
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.File;
import java.nio.file.Files;
import javax.servlet.http.HttpServletResponse;
#Controller
public class FragmentsController {
#RequestMapping(value = "/fragments/{fragmentPage}")
#ResponseBody
public String GetFragment (#PathVariable String fragmentPage, HttpServletResponse response) throws Exception {
response.setHeader("Content-Type", "text/plain");
response.setHeader("success", "no");
if (fragmentPage == null)
{
System.err.println("Nothing to serve!");
return null;
}
System.out.println("Serving fragment: " + fragmentPage);
String fileName = "static/fragments/"+fragmentPage;
File resource = new ClassPathResource(fileName).getFile();
String frg = "";
try
{
frg= new String(Files.readAllBytes(resource.toPath()));
response.setHeader("success", "yes");
}
catch (Exception e)
{
frg = "Error loading fragment: " + e.getMessage();
}
return frg;
}
}
From server A, I can now fetch the fragment like this:
<div th:include="http://<server_b_url:port>/fragments/frg :: content"></div>

Unexpected mapping error for MVC project

I have a mapping error to my application. As you can see from the code I have the
#RequestMapping("/productList")
but when I am on my homepage and hover the link Products (for /productList) on the bottom left on my browser the url is the following
localhost:8080/eMusiscStore/productList;jsessionid=B16DF0DE6E0089AC5F7DBE356181BBB1
So sometimes, the page cannot be displayed and other times the requested page (/productList) loads normally.
What can I do to be sure that my mapping will be correct every time?
I post only my HomeController. Let me know if you need another file.
package com.controllers;
import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.entities.Product;
import com.servicesapi.ProductService;
#Controller
public class HomeController {
#Autowired
ProductService productService;
#RequestMapping("/")
public String home(){
System.out.println("HomeController home");
return "home";
}
#RequestMapping("/productList")
public String getProducts(Model model) {
System.out.println("HomeController productiList");
List<Product> products = productService.getAllProducts();
model.addAttribute("products", products);
return "productList";
}
#RequestMapping("/productList/viewProduct/{productId}")
public String viewProduct(#PathVariable String productId, Model model) throws IOException{
Product product = productService.getProductById(productId);
model.addAttribute(product);
return "viewProduct";
}
}
As you have mentioned in the description that some time you are able to render your productList page.This could a bad cache issue.You can either try running your page incognito mode or clear cache always.Also to be double sure that the your rest call is working fine install postman plugin in your chrome browser and try invoking localhost:8080/eMusiscStore/productList;jsessionid=B16DF0DE6E0089AC5F7DBE356181BBB1
If everything goes fine this should return you productList in the response body. Aren't you mentioning the type of CRUD operation?Looks like it is a #get method.

Authenticate GET request from html extensions in AEM

Good day,
When a user hit specific url with an extension on html, I want to validate if user has logged in. If the user is not logged in, I want to redirect them to my custom login page (this part is done). Else, I want to do nothing - meaning the current page that they are on, should continue being displayed.
I want this to meet client requirements (the default AEM login page should stay as is.
Scenario
The page is /content/mysite/page.html
If I am not logged in, I should be redirected to /content/mysite/login.html
If I am logged in, I should still see this page : /content/mysite/page.html
Now, my problem comes when I am logged in. Instead of seeing content of the page : /content/mysite/page.html, there page is simply blank. There are no contents to be displayed.
Maybe I do not get the concepts of servlets or I do not know how to handle this kind of problem.
Please help resolve this or suggest another route to handle this
Here is my the code I have so far:
package com.company.patientsportal.core.auth;
import java.io.IOException;
import java.util.Map;
import javax.jcr.Repository;
import javax.jcr.Session;
import javax.servlet.ServletException;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.engine.SlingRequestProcessor;
#Service
#SlingServlet(resourceTypes={"patientsportal/components/structure/page"}, selectors="html", methods = "GET", metatype=true, description="My Authentication Verifier")
#Properties
(
{
#Property(name="login.form", description="The form on which the user to enter authentication credentials.", value="")
}
)
public class CheckAuthentication extends SlingAllMethodsServlet
{
/**
*
*/
private static final long serialVersionUID = 8552708551560032677L;
private Map<String, Object> redirects;
#Reference
private Repository repository;
#Reference
private SlingRequestProcessor requestProcessor;
#Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException
{
ResourceResolver resolver = request.getResourceResolver();
Session session = resolver.adaptTo(Session.class);
String userId = session.getUserID();
String url = request.getRequestPathInfo().getResourcePath();
url = url.substring(0, url.lastIndexOf("/")) + ".html";
if (String.valueOf(userId) == null || (String.valueOf(userId) != null ? String.valueOf(userId).equals("anonymous") : false))
{
String loginForm = getLoginForm("login.form");
if (loginForm != null)
{
response.sendRedirect(loginForm + "?url=" + url);
}
else
{
response.sendRedirect("/content/patientsportal/login.html?url=" + url);
}
}
else
{
//Do nothing or something in the else
//So far, do nothing does not work. It returns blank page even if I do not include the else part
}
}
private String getLoginForm(String loginForm)
{
if (redirects != null)
{
loginForm = (String) redirects.get(loginForm);
return loginForm;
}
return null;
}
#Activate
protected void activate(Map<String, Object> properties)
{
redirects = properties;
}
}
The ideal way of implementing login functionality is to either use the OOTB AEM authentication handler or implement Sling AuthenticationHandler and extending DefaultAuthenticationFeedbackHandler. You can find the code references to implement in lot of blogs -
acs-aem-samples
How to Create Custom Authentication Handler in CQ
After you have implemented this and have created/configured your own login page /form, you need to setup CUG on the pages that are to be exposed only to a logged in user. The details around it are available in AEM documentation here

how to show online user using servlet mapping

i want to show online users using this servlet ......
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.chatapp.useroperation.Client;
#WebServlet(name = "onlineUsersServlet", urlPatterns = { "/getOnlineUsersList" })
public class ListOfOnlineUsers extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String commaSepeparatedStr ="";
ServletContext appScope = request.getServletContext();
String channel = request.getParameter("channel");
final Map<String, List<Client>> clients = (Map<String, List<Client>>) appScope.getAttribute(LoginServlet.CLIENTS);
System.out.println(clients);
if(clients.size()> 0){
final List<Client> onlineClients = clients.get(channel);
if(onlineClients !=null){
for (Client client : onlineClients) {
if(commaSepeparatedStr.equals("") ){
commaSepeparatedStr = client.getUserName();
}else{
commaSepeparatedStr =commaSepeparatedStr+","+ client.getUserName();
}
}
}
}
response.getWriter().write(commaSepeparatedStr);
response.flushBuffer();
}
}
how can i pass value to this servlet from a jsp so that it store the username in its list......is it possible to put value in that servlet from session.
in your jsp do something like this:
<form action="/YOURWEBAPPNAME/onlineUsersServlet/getOnlineUsersList" method="get">
<input type="text" name="test" value="Hello World">
<input type="submit" value="Send">
</form>
in you doGet method do this:
String userInput = request.getParameter("test");
and feel free using that stuff.
put that stuff in the session with:
request.getSession(false).setAttribute("input",userInput);
and read it with:
String lInput = (String) request.getSession(false).getAttribute("input");
If you want to Store a Value from a session to a servlet, just attach an attribute to the Session;
During Login, get the username and store the value into the Session;
HttpSession sess = request.getSession();//Create new Session
//Get the username from login input
String username = request.getParameter("name");
//Attach the name to the Session.
sess.setAttribute("username", username);
Get the value anytime as long as the session is active.
HttpSession sess = request.getSession(false);//Use the current Session
//Get the value fron the Session
String username = (String) sess.getAttribute("username");//get the Attribute Username
You need to have Attached the Attribute to the Session before you can get it this way.
There are variables with a different scope that you can, or not, access from different places in your code. In JavaEE there are variables with request, session and application scope.
The request scope means that you can set it and use it in all your classes for the current request and that's what you seem to need right now.
I'm sorry I can't help you more right now but with this info Google or the SO search box should be your friend. I'll add details later.
Edit -
Stefan beike's answer has these details I'm talking about.

No response back from REST WS called by jQuery/JSON

I know there is a lot of these posts but I couldn't really get this to work since I am new to both REST and JQuery:
I am using REST-WS with Java 5 and I am able to call it and get result back with "Poster" ,the firefox plugin to test it. When I call the URL below I should get the employee in order '0' in the map by calling the method "getCustomer" in the resource class shown below.
Although I am not able to get the result and getting an error "unknown "using jQuery and returning JSON when I call the REST from an html page with body as below:
<body>
jQuery to REST <br><br>
jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function (){
$.ajax({
type: "GET",
url: "http://localhost:8081/RestDemo/services/customers/0",
dataType: "json",
success: function (data) {
alert(data.name);
},
error: function(e){
alert("Error: " + e);
}
});
});
});
</script>
<br>
<br>
<button>Return Customer</button>
</body>
This is my Resource class:
package com.myeclipseide.ws;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.sun.jersey.spi.resource.Singleton;
#Produces("application/xml")
#Path("customers")
#Singleton
#XmlRootElement(name = "customers")
public class CustomerResource {
private TreeMap<Integer, Customer> customerMap = new TreeMap<Integer, Customer>();
public CustomerResource() {
// hardcode a single customer into the database for demonstration
// purposes
Customer customer = new Customer();
customer.setName("Harold Abernathy");
customer.setAddress("Sheffield, UK");
addCustomer(customer);
}
#GET
#XmlElement(name = "customer")
public List<Customer> getCustomers() {
List<Customer> customers = new ArrayList<Customer>();
customers.addAll(customerMap.values());
return customers;
}
#GET
#Path("/{id}")
#Produces("application/json")
public String getCustomer(#PathParam("id") int cId) {
return "{\"name\": \"unknown\", \"address\": -1}"; //customerMap.get(cId);
}
#POST
#Path("add")
#Produces("text/html")
#Consumes("application/xml")
public String addCustomer(Customer customer) {
int id = customerMap.size();
customer.setId(id);
customerMap.put(id, customer);
return "Customer " + customer.getName() + " added with Id " + id;
}
}
I appreciate anyone's help,
Thanks!
I got it!
Returning {"name": "unknown", "address": -1} is right because that's exactly what is hard coded in my method return,
so i replaced return "{\"name\": \"unknown\", \"address\": -1}";
simply with a correct form which is
return "{\"name\": \" " + customer.getName() + " \", \"address\": \"" + customer.getAddress() + "\"}";
and obviously it works!
Thanks everyone.
I appreciate anyone's help,
If you are stumped, take a look at what is in the web countainer's log files. If necessary, turn on debug logging.
The next thing would be to use your web browser's built-in "web developer" support to see what request is actually being sent.

Categories