I'm trying to develop a simple web app that takes the input and run a specific command, and return the result to the user. I'm struggling a little bit when I'm trying to pass the result/output to a textbox, it always shows null...
What am I missing here?
JAVA Code:
public boolean CheckSite(String site) throws Exception
{
try
{
Process p=Runtime.getRuntime().exec("cmd /c nslookup -debug "+site+".abc.internal.rpz | findstr 666");
p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
if (line == null)
{
System.out.println("This website is not blocked");
return false;
}
else if(line!=null && line.contains("666"))
{
System.out.println("Website is blocked");
return true;
}
}
catch(IOException e1) {}
return false;
}
Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
String site = request.getParameter("text1");
try {
b=ec.CheckSite(site);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("value", b);
}
JSP Page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Website Status</title>
</head>
<body>
<form align ="middle" action ="checkBlocked" method="post">
Please Enter The Website
<input type ="text" name ="inputText" >
<br>
<input type ="submit" value ="Submit">
</form>
<input type="text" name="done" value='<%=request.getAttribute("TextValue")%>'/>
</body>
</html>
Thank you in advance
You're setting attribute name:
request.setAttribute("value", b);
And trying to retrieve as:
getAttribute("TextValue")
Scriptlets are not recommended. JSP EL and JSTL are the way to go for this task (IMHO).
Make your servlet name is checkBlocked like it says below:
<form align ="middle" action ="checkBlocked" method="post">
Then forward or redirect the response from your servlet to your jsp:
request.getRequestDispatcher("confirmationPage.jsp").forward(request, response);
Related
I have a JPS page from which I want to execute a shell script placed on server:
Below code works fine and "/tmp/Sample.sh" script is getting executed on server.
Now I want to do 2 things:
1.The script is getting executed as soon as page is loaded, but i want to execute it only when button is clicked.
2.I understand that use of scriplets is discouraged, what I googled is that I should call a servlet, when button is clicked, in which i can move the java code.
I'm new to these terminologies as my primary skill is not java.
I have readed theory of servlet but , not getting how exactly i can achieve above two functionality.
Any help in achieving above two points would be greatly appreciated
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
</head>
<body>
<%
String unixCommand = "sh /tmp/Sample.sh";
Runtime rt = Runtime.getRuntime();
rt.exec(unixCommand);
%>
</body>
</html>
UPDATED CODE AS PER SUGGESTIONS:
http://10.111.24.21:7001/Project_1/Test_1.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
</head>
<body>
<button onclick="location.href = 'http://10.111.24.21:7001/Project_1/JavaServletClass.java';" id="RedirectButton" > Execute</button>
</body>
</html>
http://10.111.24.21:7001/Project_1/JavaServletClass.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class JavaServletClass extends HttpServlet
{
public void init() throws ServletException { }
private void ExampleMethod() throws IOException
{
String unixCommand = "sh /tmp/Sample.sh";
Runtime rt = Runtime.getRuntime();
rt.exec(unixCommand);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ExampleMethod();
out.println("<h1>" + "Method Executed" + "</h1>");
}
public void destroy() { }
}
Jsp page translates to servlet eventualy so ofc it is possible to do same thong that you did in servlet. If usage of JSP page is absolutely necessery you can do fallowing things:
Create servlet follow tutorial on Create Servlet
create method to execute command
private void ExampleMethod() {
String unixCommand = "sh /tmp/Sample.sh";
Runtime rt = Runtime.getRuntime();
rt.exec(unixCommand);
}
Call method from doGet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Call commands
PrintWriter out = response.getWriter();
ExampleMethod();
out.println("<h1>" + Method Executed + "</h1>");
}
Replace scriptlet in body of jsp with:
<button onclick="location.href = 'http://localhost:8080/SERVLETNAME';"
id="RedirectButton" > Execute</button>
Replace server name, location (localhost:8080) with youre values ...
FORGET ALL OF THAT AS SERVLETS AND SCRIPTING IN HTML IS SO OLD AND OBSOLETE IT SHOULD NOT BE USED ANY MORE
Im trying pass specific element from my Model to servlet to jsp.
This is working in my servlet: System.out.println(beanModel.getSortedDomainList().get(0).split(";")[1]) When I go to http://localhost:8080/Comparebet/Controller
But I dont know what Im doing wrong since I dont get it to my jsp. All tutorials ive been watching is mostly input parameters or they put code in the JSP.
UPDATE EDIT
Tried with this in my JSP and I get "null"
<%= request.getAttribute("rank1") %>
SERVLET
#WebServlet("/Controller")
public class Controller extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ArrayList<String> sortedDomainList = new BeanModel().getSortedDomainList();
BeanModel beanModel = new BeanModel();
request.setAttribute("rank1", beanModel.getSortedDomainList().get(0).split(";")[1]);
RequestDispatcher view = request.getRequestDispatcher("view.jsp");
view.forward(request, response);
//TESTING SERVLET
System.out.println(beanModel.getSortedDomainList().get(0).split(";")[1]);
System.out.println("CONTROLLER CALLED");
// System.out.println(${rank1});
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
}
}
JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>CompareBet</title>
</head>
<body>
<form action="/Controller/*" method="get">
<h1>${rank1.getSortedDomainList().get(0).split(";")[1] } </h1>
</form>
</body>
</html>
In your JSP try this, instead of rank1.getSortedDomainList().get(0).split(";")[1]
<h1>${request.rank1 } </h1>
You have already done beanModel.getSortedDomainList().get(0).split(";")[1] in your servlet and have added the result to the request scope object.
Try to replace this line in your jsp:
<h1>${rank1.getSortedDomainList().get(0).split(";")[1] } </h1>
To this:
<h1>${rank1} </h1>
In JSP you can access this data using the expression language like ${rank1}.
And take it out from the <form like this:
<form action="/Controller/*" method="get">
...
</form>
Try to use <h1><%= request.getParameter("rank1")%></h1>
I was wondering how I can print an error message to the user in the case he/she entered the wrong passowrd in JSP. Given that I have the form set up and validation works, I am trying to add this one check but the output is printed to the standard out ie console, however, I would like for it to be printed to the screen that the user is viewing. Here's my code for authentication:
public boolean verify (String username, String password) {
if (!password.equals("1234")) {
System.out.println("Wrong password!\n");
return false;
}
return true;
}
EDIT: LoginProcessing.java calls the method above and checks the boolean value (logedin), if it is not set I execute the code below, but it still doesn't print to the screen where user can see it.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// skipping initializations for brevity
if (logedin) {
// do stuff
}else {
System.out.println("Wrong password!\n");
response.sendRedirect("login.jsp");
return;
}
}
EDIT 2: Here's what my code looks like in login.html to which I redirect in the code above from the doPost() method, except I removed the println() method.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Using JSP</title>
</head>
<body>
<form action="login" method="post">
Please enter your username: <input type="text" name="username"><br>
Please enter your password:<input type="password" name="password"><br>
<input type="submit">
</form>
<c:if test="${!loggedin}">
Sorry. Wrong user name or password
</c:if>
</body>
</html>
In your servlet method:
// check the credentials
boolean loggedIn = verify(username, password);
// store the result in a request attribute, so that the JSP can retrieve it
request.setAttribute("loggedIn", loggedIn);
// let a JSP display the result
request.getRequestDispatcher("/loginResult.jsp").forward(request, response);
In the JSP (using the JSTL), test the value of the loggedIn request parameter:
<c:if test="${loggedIn}">
Congratulations: you're now logged in.
</c:if>
<c:if test="${!loggedIn}">
Sorry. Wrong user name or password
</c:if>
I am working with resteasy with war file deployed on jboss (6.0.2 EAP)
I have the following workflow :
URL hit calls a servlet(doGet() method)
this servlet is supposed to deliver a jsp page to the client
JSP page resides in WebContent/customFolder
I use the requestDispatcher().forward() method to invoke the JSP
The path given in forward("/customFolder/name_of_jsp")
the jsp has a form, whose action attribute points to another servlet
the problem is , once the forward() method is called, the browser returns a 404 resource not found error.
I have followed some questions already posted on this forum and was not able to solve this issue.
Can anyone please guide me.
Edit:
JSP page :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="javax.servlet.*,java.lang.String"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Password Reset Page</title>
</head>
<body>
<form method="GET" action="Resteasy">
<%!String userId;%>
<%userId = (String)getServletContext().getAttribute("userid"); %>
<p>User Id:<%= userId %></p>
Password: <input type="password" name="pwd" id="pass">
<br>
Confirm Password: <input type="password" name="rePwd" id ="c_pass" onblur="confirmPass()"><br>
<script type="text/javascript">
function confirmPass() {
var pass = document.getElementById("pass").value
var confPass = document.getElementById("c_pass").value
if(pass != confPass) {
alert('Wrong confirm password !');
document.getElementById("c_pass").focus();
}
}
</script>
<input type="submit" value="Submit">
</form>
</body>
</html>
The servlet which has to deliver the jsp :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.info("Received request for popup jsp page");
String userId = request.getParameter("userid");
String utc = request.getParameter("utc");
log.info("Recieved userid = "+ userId);
log.info("Received utc is = "+ utc);
ServletContext requestContext = request.getServletContext();
requestContext.setAttribute("userid", userId);
requestContext.setAttribute("UTC", utc);
String htmlfileName = null;
try {
htmlfileName = new DeltaPropertyHandler(
DeltaConstants.LINK_HTML_FILE).getPropertyValue(DeltaConstants
.USER_PASSWORD_RESET_HTML);
File file = new File(requestContext.getRealPath(htmlfileName));
if(file.exists()){log.debug("file exists!!");}
else{log.warn("file does mot exist");}
} catch (Exception e) {
log.error("failed to present the jsp page " + e.getMessage());
}
log.info("File name is "+htmlfileName);
RequestDispatcher rd = requestContext.getRequestDispatcher(htmlfileName);
rd.forward(request, response);
}
your code:
RequestDispatcher rd = requestContext.getRequestDispatcher(htmlfileName);
you should change:
RequestDispatcher rd = requestContext.getRequestDispatcher(programname.jsp);
if your using the get method as following as:
RequestDispatcher view=request.getRequestDispatcher(forward);
view.forward(request, response);
if your using the post method like as:
private static String LIST_USER="/listUser.jsp";
RequestDispatcher view=request.getRequestDispatcher(LIST_USER);
request.setAttribute("users", dao.getAllUsers());
view.forward(request, response);
User will be reference from this format. And just look at the simple format are following as:
A.jsp> conntroller.java > dao.java>dbUtil.java
you want the reference for that list as following link to click
I get following error after trying to launch my first servlet... what may be wrong? I am using proper method (get) and the same code works for my friend... is it possible to be tomcat's fault?
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet Ciastko threw exception
java.lang.NullPointerException
DOGET method:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
HttpSession sesja = request.getSession(true);
PrintWriter out = response.getWriter();
String login = request.getParameter("login");
String pass = request.getParameter("pass");
if(login.isEmpty() || pass.isEmpty()){
out.println("Brak sesji lub atrybutu.");
}
if(login.equals("admin") || pass.equals("admin")){
out.println("ADMIN");
}
else{
sesja.setAttribute("login", login);
sesja.setAttribute("pass", pass);
}
}
and here is index.html file:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Tytuł</title>
</head>
<body>
<form action="Ciastko" method="GET">
<p>Login: </p><input name="login" id="login" />
<p>Hasło: </p><input name="pass" id="pass" />
<input type="submit" value="Wyślij!" />
</form>
</body>
</html>
ServletRequest.getParameter
Returns the value of a request parameter as a String, or null if the parameter does not exist.
You're not checking your login/pass for null, which will make isEmpty crash if the parameters are not set.