changing URL but want to send data to controller - java

My web application has a new requirement that if parameter coming in url then land to email page. otherwise on index page like always.
Its a very old client product and not much scope to change lot in code so i put a check in controller that if encrypted email coming in then land to email page.
example url -
http://localhost:8080/R2/Controller?email=jAOtTv22BfkTkVrhTN/RHQ==
Everything works fine but i want to change URL.
How can i get rid of " /Controller " in URL but still it hits to controller.???
Controller code like -
public class Controller extends HttpServlet {
static Logger logger = Logger.getLogger(Controller.class);
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// get the action property from the request
String theAction = request.getParameter("action");
String theSource = request.getParameter("s");
String theSource1 = request.getParameter("email");
String em ="";
Action action=null;
em = EncryptEmail.decrypt(theSource1,GFWConstants.BLOWFISH_KEY);
if (em.equals(""))
rd = request.getRequestDispatcher("index.jsp?emailRtv=0");
else
rd = request.getRequestDispatcher("email-preferences.jsp?emailRtv=2&emailAddress="+em);
rd.forward(request,response);
return;
}
Thanks in advance.

adding two url-pattern to web.xml file worked.

Related

How to get CasToken from server?

I want to do a Cas Authentication from Standalone-Application but it fails on getting the Ticket from server. Can anyone provide me example code for a method that returns the ticket as String so i can use it for the Authentication. As you see the only Parameter should be the URL from the server. Thats waht i have yet(i know casToken is initialized on null an it doesnt work).
protected String getCasTicket(String serviceUrl) {
String casToken = null;
if (casToken == null){
logger.error("Failed to get CAS-Token!");
}else{
logger.info("Got CAS-Token successful!");
}
return casToken;
}
public class CasAuthenticationServlet extends HttpServlet {
...
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// NOTE: The CasAuthenticationToken can also be obtained using
// SecurityContextHolder.getContext().getAuthentication()
final CasAuthenticationToken token = (CasAuthenticationToken) request.getUserPrincipal();
// proxyTicket could be reused to make calls to the CAS service even if the
// target url differs
final String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(targetUrl);
// Make a remote call using the proxy ticket
final String serviceUrl = targetUrl+"?ticket="+URLEncoder.encode(proxyTicket, "UTF-8");
String proxyResponse = CommonUtils.getResponseFromServer(serviceUrl, "UTF-8");
...
}
CasAuthenticationProvider constructs a CasAuthenticationToken including the details contained in the TicketResponse and the GrantedAuthoritys.
Control then returns to CasAuthenticationFilter, which places the created CasAuthenticationToken in the security context.
Cas Example: https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/sample-apps.html#cas-sample
EDIT:
Please refer https://www.javaworld.com/article/3313114/what-is-a-java-servlet-request-handling-for-java-web-applications.html for creating a servlet

Servlet Dispatcher URL

I have problem when I submit my form to insert data
the URL can't change and when I refresh it, the data reinsert
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String _1 = request.getParameter("company_name").toString();
String _2 = request.getParameter("city").toString();
String _3 = request.getParameter("state").toString();
String _4 = request.getParameter("zipcode").toString();
String _5 = request.getParameter("branch").toString();
String _6 = request.getParameter("address").toString();
Database db = (Database) getServletContext().getAttribute("db");
try {
String sql = "insert into company(company_name,city,state,zipcode,branch,company_address) values('"+_1+"','"+_2+"','"+_3+"','"+_4+"','"+_5+"','"+_6+"')";
db.updateSql(sql);
} catch (Exception e2) {
System.out.println(e2);
}
getServletContext().getRequestDispatcher("/company.jsp").forward(request, response);
}
Your problem comes from the understanding of the forward method.
This method transfer the request and the response object to the new URL. It is invisible for the client's browser so the URL is unchanged. By reloading the page, you repeat your resquest so your sending again your data.
This behaviour is completely normal. If you want to redirect to another URL and have another request then you should use the sendRedirect method.
Refer to this post to have a complete description of both methods.

Forward(request,response) doesn't forward the URL

I'm doing a project using Java servlets. I have to include code in an already functioning site. I'm using Netbeans and the server is Tomcat. The code that I added is very similar to some parts of the code of the site. I had to create a new controller that reads from a database and display, add, update and delete information. The site was functioning with different servlets that we created but a requisite for the project is to create the controller servlet. This is part of the code of the controller:
public class MaintController extends HttpServlet {
#Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
String requestURI = request.getRequestURI();
String url = "/maint";
if (requestURI.endsWith("/displayProducts")) {
url = displayProducts(request, response);
} else if (requestURI.endsWith("/addProduct")) {
url = addProduct(request, response);
} else if (requestURI.endsWith("/editProduct")) {
url = editProduct(request, response);
} else if (requestURI.endsWith("/deleteProduct")){
deleteProduct(request, response);
}
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
}
private String displayProducts(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
List<Product> products = ProductDB.selectProducts();
session.setAttribute("products", products);
out.println(products);
String url= "/maint/products.jps";
return url;
}
The point is that debugging the site I can see that when entering an URL that finishes with /displayProducts the displayProducts function is accessed, the products are read and the URL is returned, but when the control goes to getServletContext().getRequestDispatcher(url).forward(request, response); the url is not forwarded and I get a 404 error when the url exists.
I can see in the displayProducts() method, you have defined the url as follows:
String url= "/maint/products.jps";
shouldn't that be a typo??
String url= "/maint/products.jsp";
file extension is wrong right?
404 error indicates the requested page not found.
your return url is
String url= "/maint/products.jps";
extension of the requested page is not correct. It should be products.jsp

transfer data to a servlet from a jsf page

I have an input in my jsf page like this
<html:inputText id="ResponseOK" value="#{bean.ResponseOK}" binding="#{bean.ResponseOKInput}" />
I want to get the value in a servlet (by request.getParameter ("ResponseOK")) when i click on a command button
<html:commandButton value="Valider" action="#{bean.callServlet}"/>
which call a function
public void callServlet()
{
String url = "http://localhost:8080/TestOne/Timers"; //servlet
FacesContext context = FacesContext.getCurrentInstance();
try {
context.getExternalContext().redirect(url);
}catch (Exception e) {
e.printStackTrace();
}
finally{
context.responseComplete();
}
}
Unfortunately, in my servlet the variable Ok , return only null
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String Ok = request.getParameter("ResponseOK");// return null
System.out.println(timerOk);
}
thank you very much
In order for you to be able to get a property from the request, the input must have the name attribute:
<html:inputText id="ResponseOK" value="#{bean.ResponseOK}" binding="#{bean.ResponseOKInput}" name="ResponseOK"/>
UPDATE:
I'm not too familiar with the JSF framework but i think your problem is the action button.
This button is not a submit button so the value of the input is not being sent to the request.
When calling a GET request, you need to pass the parameter in URL itself, so you need the url to look like:
http://localhost:8080/TestOne/Timers?ResponseOK=value
So you need to transfer the value of the ResponseOK input to the callServlet method.
Hope that helps.

GateIn: a filter for the login servlet

I need to implement some logic before and after the login servlet invoked by my login.jsp.
So I wrote a filter for the url /login to do that. I need to get the user profile for some operations, so I created this LoginFilter class:
public class LoginFilter implements Filter {
private static Logger logger = Logger.getLogger(LoginFilter.class);
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String username = httpRequest.getParameter("username");
String password = httpRequest.getParameter("password");
chain.doFilter(request, response);
PortalRequestContext context = PortalRequestContext.getCurrentInstance();
if (context == null)
logger.info("PortalRequestContext is NULL");
else {
String userId = context.getRemoteUser();
if (userId == null || userId.equals(""))
logger.info("Login failed, IP:" + httpRequest.getRemoteAddr());
else
logger.info("Login executed, username:" + userId);
}
}
The problem is that "context" (PortalRequestContext) is always null. What ma I doing wrong? Is this the right approach?
If you are using GateIn, you can try using
org.exoplatform.portal.webui.util.Util.getPortalRequestContext().getRequest()
ce
You can develop a Valve and add it into Context file of "portal" webapp (Tomcat/conf/Catalina/localhost/portal.xml).
That's what is done in GateIN for SSO extension for example:
See ServletAccessValve
ServletAccess.setRequestAndResponse(request, response);
Then, the Request is accessed in SSOLoginModule using this:
// Tomcat way (Assumed that ServletAccessValve has been configured in context.xml)
else
{
request = ServletAccess.getRequest();
}
For JBoss, it's more simple, you have just to use
javax.security.jacc.PolicyContext.getContext(HttpServletRequest.class.getName())
At login time, PortalRequestContext's not been created yet, but you can get remote user by calling HttpServletRequest#getRemoteUser()
You can add a GateIN Filter like detailed here.
And you can use statically in this Filter the ConversationState to get the current username:
ConversationState.getCurrent().getIdentity().getUserId();
Just use the conversation state object:
// Gets the current user id
ConversationState conversationState = ConversationState.getCurrent();
org.exoplatform.services.security.Identity identity = conversationState.getIdentity();
String userId = identity.getUserId();

Categories