i'm new to jsp , i have already a servlet that works , it sends parametres in the url (url/servletname?name=test&msg=test2), but i want to make a jsp file that transform that to be visual, i don't know how to start , here's is my servlet :
package mypackage;
import java.io.IOException;
import javax.servlet.http.*;
import java.util.*;
//import ma.cloud.ParticipantDao;
public class infoservlet extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
String p_name=req.getParameter("name");
String p_msg=req.getParameter("message");
String p_resp_text="";
if (p_id !=null && p_response !=null){
try {
Demand_aide_dao dao=new MemeCache_Demande_aide();
dao.respond_demande_aide_by_id(p_id, p_response);
p_resp_text="Hi Mr." + p_name + " }";
} catch (Exception e) {
// TODO: handle exception
p_resp_text="message : error" + e.getMessage()+ " }";
}
}
resp.getWriter().println(p_resp_text);
}
}
i just need an idea on how to start, and how to turn it from a parametres in url to values that i can type it . please i'm stuck for 5 days now
Params to type, ' transform that to be visual'
Do you mean a form ?
In a text file type :
<html>
<body>
<form action=/path/to/your/servlet/infoservlet method=post name=f1>
<input type=text name="name">
<input type=text name=" message">
<input type=submit value="Go">
</form>
Save this as start.html or start.jsp (at this point there is no difference as the jsp does not have any jsp specific code, but later can add other elements to it).
In folder where your web content goes (depends what app container you are using for Jboss 5 free version can put it in :
jbossMain\server\default\deploy\ROOT.war\
And start jboss with default :
jbossMain/bin/run.sh -c default
Open this jsp in browser, type values press Go, by default jboss would start with port 8080 make sure no other service us running on same port before.
http://localhost:8080/start.jsp
You need to go thru a tutorial on starting web apps and java jsps.
See
* https://www.google.com/search?q=java+jsp+tutorial
* http://www.jsptut.com/
* http://www.tutorialspoint.com/jsp/
Related
I'm facing an issue to try learn the full cycle of web following of data, i passed value from java jersay REST-API to angular 5, but i wanna pass text from angular to backend to execute some query and return the result again, i got confused between #FormParam and many things,
bellow my code,
File-list.service.ts
import { Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '#angular/common/http';
import { FileList } from './file-list';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map'
save(fileList: FileList): Observable<Response> {
console.log('Saving person ' + JSON.stringify(fileList));
return this.http.put('http://localhost:8080/SWBackend/jaxrs/Person/Save', JSON.stringify(fileList), { headers: this.getHeaders()});}
List.component.html
<form (click)="save()" method="POST" action="http://localhost:8080/SWBackend/jaxrs/Person/Save">
<p>
Path : <input type="text" name="pathUrl" />
</p>
Press to show the files
<input type="submit" value="Add User" />
<input type="hidden" name="_method" value="PUT">
</form>
Java file.java
#PUT
#Path("Save")
#Consumes({ "application/xml", "application/json" })
#Produces("application/json")
public Response saveEmp(FilesList pathUrl) {
System.out.println("Reach Save Emp");
return Response.ok().header("Access-Control-Allow-Origin", "*").build();
}
i'm getting this error:
line 0:-1 no viable alternative at input ''
i don't know if my way is right or no, but i was trying since week ago,
thank you all.
Try this instead,
in your form remove this:
<form (click)="save()" method="POST" action="http://localhost:8080/SWBackend/jaxrs/Person/Save">
Use ReactiveFormsModule for your forms, using FormGroup and FormControl.
Then in your component, when you submit the form, it will invoke the function to call your service which in return will communicate with your java controller.
The Component should have the function that is associated with your formGroup in your template(html).
The function should then call your service such as: this.service.save(fileList);
https://angular.io/guide/reactive-forms
ex:
<form [formGroup]="fileListForm" (ngSubmit)="save(fileListForm.value)">
<input type="text" formControlName="fileListNameControl">
</form>
Component:
private fileListForm: FormGroup;
private fileListNameControl: FormControl;
ngOninit(){
this.fileListForm = new FormGroup({
fileListNameControl: new FormControl("", Validators.required)
});
}
save(form: any){
// get your form values here and then call service
this.fileLIstService.save('your value');
}
** Make sure to import ReactiveFormsModule via #angular/forms in your module.
I have a trouble with servlet coding and I don't know how to solve it.
I was trying to track a session (using TomCat web server) using only hidden parameters.
In this example there are name, surname and email as parameters. My idea was to ask the client just one parameter per time and send it to him as hidden parameter (iteratively).
If I start just one session (since when the client sends the first parameter to when the client sends the last parameter) my servlet works fine.
The problem is when I start another session:
when i send to to server the surname (a different value from the revious session) the server gives me an url where there is two times the hidden parameter "surname" with the value of the current surname and the value of the previous one's session surname.
Here is my servlet class:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class HiddenParamServlet extends HttpServlet {
private final String[] PARAMS = { "name", "surname", "e-mail" };
private Map<String, String> hiddenParameters;
#Override
public void init() {
hiddenParameters = new HashMap<String, String>();
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// control the last parameter added by the client
List<String> clientParameters = Collections.list(request.getParameterNames());
// checks if the client already sent all the parameters
if(clientParameters.size() == 3) {
// start the html document
out.println("<html><head><title>Session finished</title></head>");
out.println("<body><h1>Session succesfully completed</h1></body>");
out.println("</html>");
// end the html
out.close();
hiddenParameters.clear();
}
else {
String lastParam = clientParameters.get(clientParameters.size() -1);
//memorizing the last param sent by the client
String value = request.getParameter(lastParam);
hiddenParameters.put(lastParam, value);
// starts the HTML document
out.println("<html>");
out.println("<head><title>Tracking session with hidden parameters</title></head>");
out.println("<body>");
out.println("<form method=\"get\" action=\"/DirectoryDiSaluto/HiddenParamServlet\">");
out.println("<p>");
//write the next parameter to ask to the client
out.println("<label>Insert "+PARAMS[clientParameters.size()]+":");
// write the hidden parameters of the server
for(String key : hiddenParameters.keySet()) {
out.println("<input type=\"hidden\" name=\""
+key+"\" value=\""+hiddenParameters.get(key)+"\" />");
}
out.println("<input type=\"text\" name=\""+PARAMS[clientParameters.size()]+"\" />");
out.println("<input type=\"submit\" value=\"Submit\" />");
out.println("</label>");
out.println("</p>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
// end the html
out.close();
}
}
}
Here is the html page where all starts:
<html>
<head>
<title>Tracking session with hidden parameters</title>
</head>
<body>
<form method="get" action="/DirectoryDiSaluto/HiddenParamServlet">
<p>
<label>Insert name:
<input type="text" name="name"/>
<input type="submit" value="Submit" />
</label>
</p>
</form>
</body>
</html>
I can't understand where the problem is. Can you help me? Thanks so much!
hiddenParameters is guilty of this behaviour, because of its bad scope. Have a look at this answer for more explanations.
Below is my View.jsp code
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:actionURL name="myAction" var="myAction">
</portlet:actionURL>
<form action="${myAction}" method="POST">
Name : <input type="text" name="name">
<input type="button" value="SUBMIT">
</form>
Below is my Portlet class code
package com.generic;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
/**
* Portlet implementation class FirstGenericDemo
*/
public class FirstGenericDemo extends GenericPortlet {
public void init() {
viewTemplate = getInitParameter("view-template");
}
public void doView(RenderRequest renderRequest, RenderResponse renderResponse)throws IOException, PortletException {
System.out.println("view");
include(viewTemplate, renderRequest, renderResponse);
}
protected void include(String path, RenderRequest renderRequest,RenderResponse renderResponse)throws IOException, PortletException {
PortletRequestDispatcher portletRequestDispatcher =
getPortletContext().getRequestDispatcher(path);
if (portletRequestDispatcher == null) {
_log.error(path + " is not a valid include");
}
else {
portletRequestDispatcher.include(renderRequest, renderResponse);
}
}
protected String viewTemplate;
private static Log _log = LogFactoryUtil.getLog(FirstGenericDemo.class);
#Override
public void processAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
System.out.println("ok");
String name=request.getParameter("name");
System.out.println("name is : "+name);
super.processAction(request, response);
}
}
When the portlet is rendered view method gets called but when i click on submit button neither processAction method gets called nor view method. Also these is no error in stacktrace. I did tried it by deploying several times but the issue is same. can anyone please help on this.
?
The code has several issues.
The renaming suggested by Ajay will not work as you are using the GenericPortlet as the parent.
To properly bind the jsp/html code with portlet class you need to rename the class and annotate it as suggested by Ajay.
#ProcessAction(name=myAction)
public void myAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
//your code
}
Another option is to witch to MVCPortlet as a base class. Then the renaming will be enough (name attribute needs to match method name).
The second thing that will not work are the parameters. If you are not using the aui tags you need to add the namespace to the input names. In JAVA code you refer to the parameters just by the name (without namespace)
Name : <input type="text" name="<portlet:namespace/>name">
I suggest using the AUI tags. It's easier.
As said by Miroslav Ligas there are several issues.To remove those issues you need to do changes in view.jsp as well as your Portlet class.
a) In your view.jsp you need to use the below code snippet
<portlet:actionURL name="myAction" var="myAction">
</portlet:actionURL>
<form action="${myAction}" method="POST">
Name : <input type="text" name="name">
<input type="submit" value="SUBMIT">
</form>
If you are using the input type="button" then it will not work till you use document.getElementById("myForm").submit(); in your javascript part.
b) In your Portlet Class
1) You need to remove the super.processAction(request, response); as it will generate exception.
2) You need to add below code snippet in your ProcessAction method
response.setRenderParameter("jspPage","/html/jsps/displayEmployees.jsp");
above code snippet is use so as to redirect to some view part(jsp page) where /html/jsps/displayEmployees.jsp represents the path to jsp which you want to use it as view part.
and changes suggested by me earlier like using annotation #ProcessAction(name=myAction) or changing name of action method will not be recommended as you are extending the GenericPortlet class rahter then MVCPortlet class.If you extend MVCPortlet Class then it's mandatory to use them.
Changes like adding
<portlet:namespace/> in html tags like Name : <input type="text" name="<portlet:namespace/>name"> are optional to use in your code snippet.
I was trying this small HttpSession program as a demo for my project.
This program just checks whether the user is new, if it is then displays a form, if the user is not new, then it displays the name of the user, the color he selected and the total no. of visits.
When i run my program, it works only for the first time. That means when i run another instance of my program, it displays a blank web page.
What is wrong in the code that is causing this problem???
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Integer hitCount;
HttpSession s = request.getSession(true);
if(s.isNew()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet SessionServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<form method=get action=SessionServlet>");
out.println("<h3>Please sleect a Color</h3>");
out.println("<input type=radio name=color />Red");
out.println("<br /><input type=radio name=color />Green");
out.println("<br /><input type=text name=txtName />");
out.println("<br /><input type=submit name=Submit value=Submit />");
out.println("</form>");
out.println("</body>");
out.println("</html>");
} else if(!s.isNew()){
String name = (String) request.getParameter("txtName");
String color = (String) request.getParameter("color");
hitCount = new Integer(1);
s.setAttribute("Name", name);
s.setAttribute("color", color);
s.setAttribute("HitCount", hitCount);
if((name != null) && (color != null)) {
out.println("Name: " + s.getAttribute("Name"));
hitCount = (Integer)s.getAttribute("HitCount");
hitCount = hitCount++;
s.setAttribute("HitCount", hitCount);
//out.println("<body bgcolor=" + s.getAttribute("color") + ">");
out.println("you selected" + s.getAttribute("color"));
out.println("Total visits=====>" + s.getAttribute("HitCount"));
}
}
}
}
}
The second time you run this code, the session already exists, so the program goes through else branch- but the "old" request object (from the first run of the application) and its parameters (color and name) are already gone at that time. Request is destroyed by container right after the response from the first application run was sent back to the client.
In your code
String name = (String) request.getParameter("txtName");
String color = (String) request.getParameter("color");
you are trying to get non existing parameters. Parameters txtName and color do not exist in request anymore. Therefore they are null and the next condition
if((name != null) && (color != null))
is always false. And nothing is written into out Writer.
What you should do in order to make this work is to read the parameters from the session object (this is what the sessions are made for anyway) where you should put them in the first application run. This code won't work. And your hitCount will always be 1 (please see HttpSessionListener interface). This code is wrong on so many levels- you should re-write everything after the else if branch which should be only else anyway.
TLDR:
Your question was why it is not working: the answer is - you are reading non existing parameters. You have to put the parameters into session object in the first application run and read them from it.
edit after your question from December 31st:
Here is what I would do. Assume following directory structure of this simple project named SessionServlet. This structure will be used in whole answer. To simplify things I won't list every directory, you surely get the idea from this. This is not the real-life example of directory structure, it is simplified for the purposes of this tutorial example.
<path-to-project>/SessionServlet/src/com/example/session
<path-to-project>/SessionServlet/WebContent/META-INF
<path-to-project>/SessionServlet/WebContent/WEB-INF
Create an html file, for example start.html. It should contain the input fields which values you need to store in the session. The file goes here
<path-to-project>/SessionServlet/WebContent/start.html
Its contents
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Start page</title>
</head>
<body>
<form method="get" action="MySessionServlet">
<h3>Please select a Color</h3>
<input type="radio" name="color" value="red" />Red<br>
<input type="radio" name="color" value="green" />Green<br>
<input type="text" name="txtName" /><br>
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
In your servlet example you forgot the value attribute in radiobutton input, therefore whichever radiobutton you would check, the value would be on, not the color name.
Next you have to create the servlet class SessionServlet.java, which will be slightly different from your original idea. It goes here:
<path-to-project>/SessionServlet/src/com/example/session/SessionServlet.java
Its contents
package com.example.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionServlet extends HttpServlet {
private static final long serialVersionUID = -3808675281434686897L;
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String requestColor = null;
String requestTxtName = null;
PrintWriter out = response.getWriter();
MySessionListener listener = new MySessionListener();
HttpSession session = request.getSession();
if (session.isNew()) {
//these are request parameters sent from html form
requestColor = request.getParameter("color");
requestTxtName = request.getParameter("txtName");
//save the attributes in session in order to use them later
session.setAttribute("sessionColor", requestColor);
session.setAttribute("sessionTxtName", requestTxtName);
}
else {
//get the previously stored attributes from session
String color = (String) session.getAttribute("sessionColor");
String name = (String) session.getAttribute("sessionTxtName");
//session info
out.println("session already existed");
if (color != null && name != null) {
out.println("Name: " + name);
out.println("Color: " + color);
out.println("Session count: " + listener.getSessionCount());
}
}
}
}
I think the servlet's code is pretty much self-explanatory. However, if you have any particular questions, please ask.
In order to count the active sessions, you need to create a SessionListener class and count the sessions. For the purposes of this example I put the class into the same directory as servlet class. Please do not do this in real project. You'd create a big mess. This is only simplified Java Enterprise Hello world example. The file is here
<path-to-project>/SessionServlet/src/com/example/session/MySessionListener.java
Its contents are
package com.example.session;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener {
private static int sessionCount;
#Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("Creating session with id: " + se.getSession().getId());
sessionCount++;
}
#Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Destroying session id: " + se.getSession().getId());
sessionCount--;
}
public int getSessionCount() {
return sessionCount;
}
}
The listener class for counting active sessions must implement HttpSessionListener interface. We call the method getSessionCount() in SessionServlet class as you already noticed.
The last thing to do is to create a deployment descriptor xml in order to tell the container what to do with those classes we created.
the file must be named web.xml and it must be placed in WEB-INF directory.
<path-to-project>/SessionServlet/WebContent/WEB-INF/web.xml
Its contents are
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID"
version="3.1">
<display-name>SessionServlet</display-name>
<welcome-file-list>
<welcome-file>start.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>my Session Servlet</servlet-name>
<servlet-class>com.example.session.SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>my Session Servlet</servlet-name>
<url-pattern>/MySessionServlet</url-pattern>
</servlet-mapping>
<!-- set session timeout to 30 minutes -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- register listener class -->
<listener>
<listener-class>com.example.session.MySessionListener</listener-class>
</listener>
</web-app>
And that's all. Lastly my two cents- you should first acquaint with Standard Edition Java. This is an example from Enterprise world which is way over your head yet. There are plenty of tutorials on the web. Give it some time, you won't regret it.
Regarding the servlets- you should (must) first understand the basic concepts of request, response, session, client and container (who is who, the lifecycle, managing, etc.) before you start making real projects. The best book I've seen about this is Head First - Servlets and JSP, which should be a starting point in understanding this topic.
You set response.setContentType("text/html;charset=UTF-8") ....
But in your section if(!s.isNew()){.... the output is not HTML, but is plain text. ("Name:", etc...)
My bet is that the content is there, but your browser is not displaying it.
I'm experimenting with sending data from a jsp form and calling a servlet and showing that data in the servlet.
I would like to use setAttribute and getAttribute.
In this jsp file I'm using setAttribute:
<HTML>
<HEAD>
<TITLE>
Multi Processor
</TITLE>
</HEAD>
<BODY>
<h4>This is a form submitted via POST:</h4>
<FORM action = "/MyWebArchive/MulitProcessorServlet" method = "POST">
Enter your name: <INPUT type="TEXT" name="name"/>
<BR/>
<INPUT type="submit"/>
</FORM>
<BR/>
<h4>This is a form submitted via GET:</h4>
<FORM action = "/Week05WebArchive/MulitProcessorServlet">
Enter your name: <INPUT type="TEXT" name="name"/>
<BR/>
<INPUT type="submit"/>
</FORM>
</BODY>
<%
String strMasjidLocation = "Selimiyie Masjid Methuen";
session.setAttribute("MasjidLocation", strMasjidLocation);
%>
</HTML>
This is the servlet I would like to use getAttribute but I don't know how to use GetAttribute. Can you show me what additional code I need to add to the servlet so I can capture the value from the setAttribute?
package temp22;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MulitProcessorServlet
*/
public class MulitProcessorServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
doPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
String name = req.getParameter("name");
StringBuffer page = new StringBuffer();
String methodWhoMadeTheCall = req.getMethod();
String localeUsed = req.getLocale().toString();
String strMasjidLocation = null;
//strMasjidLocation = this is where I would like to capture the value from the jsp that called this servlet.
page.append("<HTML><HEAD><TITLE>Multi Form</TITLE></HEAD>");
page.append("<BODY>");
page.append("Hello " + name + "!");
page.append("<BR>");
page.append("The method who called me is: " + methodWhoMadeTheCall);
page.append("<BR>");
page.append("The language used is: " + localeUsed);
page.append("<BR>");
page.append("I am at this location: " + strMasjidLocation);
page.append("</BODY></HTML>");
res.setContentType("text/html");
PrintWriter writer = res.getWriter();
writer.println(page.toString());
writer.close();
}
}
This should work:
String value = (String) req.getSession(false).getAttribute("MasjidLocation")
Don't use scriptlets; that's 1999 style. Learn JSTL and write your JSPs using that.
Your servlets should never, ever have embedded HTML in them. Just validate and bind parameters, pass them off to services for processing, and put the response objects in request or session scope for the JSP to display.
I agree with duffymo that you should learn on newer technology (if this is applicable, maybe your client cannot allow that...). Anyway, to get the value of the attribute you owuld do:
strMasjidLocation = (String)req.getSession().getAttribute("MasjidLocation");
Also, I notice you have two different paths for your servlets in your HTML < form> tags:
MyWebArchive/MulitProcessorServlet
and
Week05WebArchive/MulitProcessorServlet
Is it expected?
You used Session not Request.
you may need to get Session from request.
String strMasjidLocation = request.getSession().getAttribute("MasjidLocation");