Jsp with java codejersey - java

I write simple Jax-Rs app (Restful), and try to return jsp file with java code. But, when I run app I get the error:
Could not find MessageBodyWriter for response object of type: com.sun.jersey.api.view.Viewable of media type: text/html;charset=UTF-8
My jsp file:
<%# page import="com.trofimovep.models.Book" %>
<%# page import="com.trofimovep.dao.BooksDao" %>
<%# page import="java.util.ArrayList" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>Bookshop</title>
</head>
<body>
This is a bookshop!
The books on our site:
<%
BooksDao booksDao = new BooksDao();
ArrayList<Book> books = booksDao.getBooks();
for (Book book : books) {
out.println("<tr>");
out.println("<th>" + book.getName() + "</th>");
out.println("<th>" + book.getAuthor() + "</th>");
}
%>
<button type="submit">Make order</button>
</body>
</html>
And function:
#Path("/bookshop")
public class Start {
#GET
#Path("/books")
#Produces({MediaType.TEXT_HTML})
public Response Books() {
return Response.ok(new Viewable("/views/mainPage", null)).build();
}
}
What I do wrong? And how it possible to fix?

Related

How to pass the values from Spring controller to JSP

I have Spring controller and I am setting a model value and want to display in my JSP:
public class TestController {
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(Model model){
model.addAttribute("message", "Programmer Gate");
return "/test";
}
}
My test.jsp code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Welcome</title>
</head>
<body>
<%
double num = Math.random();
if (num > 0.95) {
%>
<h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
<%
} else {
%>
<h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
<%
}
%>
<p>${message}</p>
</body>
</html>
I am not seeing the message value as the JSP rendering as follows:
Well, life goes on ...
(0.3343913194169942)
${message}
How to access the model message variable value in the JSP?

jsp and getting attributes data

I am trying to display the note attribute that I saved into my request.setAttribute("entries", entries), but I can't access this data in my jsp and I can't figure it out. I've tried {note} , but that doesn't work.
This is my controller class:
while( rs.next() )
{
int id = rs.getInt("id");
String name = rs.getString("name");
String note = rs.getString("note");
String title = rs.getString("title");
Notes entry = new Notes(id, name, note, title);
entries.add(entry);
}
request.setAttribute("entries", entries);
request.getRequestDispatcher( "/WEB-INF/homework2/MyNotes.jsp" ).forward(
request, response );
}
catch( SQLException e )
{
throw new ServletException( e );
}
finally
{
try
{
if( c != null ) c.close();
}
catch( SQLException e )
{
throw new ServletException( e );
}
}
}
}
This is my jsp view:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>MyNotes</title>
</head>
<body>
<p align="right">Hello, ${sessionScope.CurrentUser}! Logout</p>
<span>JOT My Notes | New</span>
<br>
<br>
<br>
<p>${note} </p>
<p>${applicationScope.entries.note},</p>
</body>
</html>
You already have your List in your request so:
Get the list with EL language
Iterate it to get all objects inside.
Then you can, (for example) put info a table:
<c:forEach items="${requestScope.entries}" var="entry">
<tr>
<td>ID: <c:out value="${entry.id}"/></td>
<td>Name: <c:out value="${entry.name}"/></td>
<td>Note: <c:out value="${entry.note}"/></td>
<td>Title: <c:out value="${entry.title}"/></td>
</tr>
</c:forEach>

Desktop Shortcut Creation: onClick of image link

I am using a JNI library (jshortcut-0.4-oberzalek https://github.com/jimmc/jshortcut/downloads ).
I wrote one jsp file and imported this jar and I am calling this jsp in ajax call.
i placed the library project folder, I am using WinSCP and putty.
Now I am getting the java.lang.unsatisfiedlinkerror: jshortcut not found in java.library.path
Code :DesktopCreation.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import ="net.jimmc.jshortcut.JShellLink" %>
<%# page import="javax.servlet.http.HttpServlet,javax.servlet.http.HttpServletRequest,
javax.servlet.http.HttpServletResponse" %>
<!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>Insert title here</title>
</head>
<body>
<jsp:useBean id="link" class="net.jimmc.jshortcut.JShellLink"></jsp:useBean>
<%!
JShellLink link;
String imgPath;
String iconPath="";
%>
<%
link = new JShellLink();
imgPath = JShellLink.getDirectory("") + "http://www.google.com";
iconPath="F:/WorkWorship/ShortCut/img/ico6.ico";
link.setFolder(JShellLink.getDirectory("desktop"));
link.setName("Manju");
link.setPath(imgPath);
link.setIconLocation(iconPath);
link.save();
%>
</body>
</html>
Code : Ajax
/*
* creates a new XMLHttpRequest object which is the backbone of AJAX,
* or returns false if the browser doesn't support it
*/
function getXMLHttpRequest() {
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
/*
* AJAX call starts with this function
*/
function createShortCut() {
var xmlHttpRequest = getXMLHttpRequest();
var con=confirm("Do you Wish to Crete?");
if(con){
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("GET", "DesktopCreation.jsp", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send(null);
alert("ShortCut Created....");
alert("Thanks for Downloading ShortCut");
}else{
alert("No thanks .....");
}
}
/*
* Returns a function that waits for the state change in XMLHttpRequest
*/
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned
// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
document.getElementById("hello").innerHTML = xmlHttpRequest.responseText;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
Code:Shortcut.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>SHORTCUT</title>
<script type="text/javascript" language="javascript" src="ajax.js"></script>
</head>
<body>
<h4 id="hello">Create ShortCut</h4>
<input type="image" src="F:\WorkWorship\DescktopShortCut\Dasara.jpg" width="100" height="100" onclick="createShortCut()" />
</body>
</html>
please any one can help.
Thanks in Advace

s:property not shown value Struts2

I have the following:
select name="nroPartido" style="color:#F5FFFA; background-color: #CC9900; font-weight: bold;">
<%
//se crean las listas
java.util.ArrayList<Partido> lista = Pronosticos.getInstance().getMiLista();
int nro = 0;
for (Partido p : lista) {
out.println("<option value=\"" + nro + "\">" + p.getLocal() +"-" +p.getVisitante() + "</option>");
nro++;
}
%>
</select>
So when I click the button the value of nro will be the value of the var nroPartido that is in the pronosticoAction class:
package acciones;
import com.opensymphony.xwork2.ActionSupport;
public class pronosticoAction extends ActionSupport {
private int nroPartido;
public String execute() {
System.out.println(nroPartido);
return SUCCESS;
}
public int getNroPartido() {
return nroPartido;
}
public void setNroPartido(int nroPartido) {
this.nroPartido = nroPartido;
}
}
Then what i want to do is print that number in a JSP page. So i do the following:
<%# 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>Detalles partido</title>
</head>
<body>
<h1>Chosen number</h1>
<h4>
You select number: <s:property value="nroPartido" />
</h4>
</body>
</html>
The problem is that it only shows this:
If someone could help me will be very useful
Thanks!
The following line is wrong, both syntactically and conceptually:
<s:property value="nroPartido"></<s:property>
there is an extra < , and the <s:property/> tag should self-closed, like a void element in XHTML:
<s:property value="nroPartido" />
That said, you should consider building your Select without using scritplets at all, by either iterating the options with <s:iterator>, or by using <s:select/> that is often the right way. You can find an example on how to do it in this answer.
EDIT
You also forgot to include the taglib directive for Struts2 tags:
<%# taglib prefix="s" uri="/struts-tags" %>
To use the Struts 2 tags on the view page, you must include a tag library directive. Typically, the taglib directive is <%# taglib prefix="s" uri="/struts-tags" %>. So the prefix for all the Struts 2 tags will be "s".
If you want to actually read the Struts 2 tag TLD file, you'll find it in the META-INF folder of the Struts 2 core jar.

PrintWriter output to jsp page inside body tag

This is the code to print to my jsp page. However I have other code in the page. When I call this function I want it to print the message right after where it is called. I can't check for sure because I am using xhtml negotiation, but I suspect it prints after the /html tag.
This is my function
public Print(HttpServletRequest request,HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>haha</p>");
}catch(IOException e){
e.printStackTrace();
}
}
};
This is where I call it
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
<%# page import="com.otrocol.app.*" %>
<%
Print(request, response);
%>
</body>
</html>
This is what I think the result is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
</body>
</html>
"haha"
This is what I want the response to be:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
"haha"
</body>
</html>
This is the error I get:
The JSP uses its own PrintWriter, the JspWriter out. So pass this to the (static) function.
Otherwise you are taking a second writer, and with buffering everything goes haywire.
Also as output already did happen do not set the content type in the function.
At the top of the JSP is a nice location, also for the imports.
<%#page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
When having one writer the function would print at the correct spot in the body.
Nice intuition about the cause. BTW begin a function name with a small letter.
It's not a direct answer to your question but I believe what you're doing will cause you nothing but pain even if you get it to work. You're not using the right tool for the job; creating custom JSP tags is a better option for writing to JSP from Java code.
Code example:
register.jsp
<%# taglib prefix="custom" uri="/WEB-INF/custom-tags.tld" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
<p>
<c:out value="${custom:printHaha()}" />
</p>
</body>
</html>
custom-tags.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0"
xmlns="http://java.sun.com/xml/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
<tlibversion>1.0</tlibversion>
<jspversion>2.0</jspversion>
<shortname>custom-taglib</shortname>
<uri>CustomTags</uri>
<function>
<name>printHaha</name>
<function-class>com.yourpackage.Tags</function-class>
<function-signature>
java.lang.String print()
</function-signature>
</function>
(...)
Tags.class
public class Tags {
public static String print() {
return "haha";
}
}
More info on Tags: official docs
I din't check your code ... you can't do a out.print again using get writer in a jsp page ... because the response for this request is already committed by rendering the jsp
now to print something on asp you can do this any number of ways
print by expression tag
use out (which is an object the server creates)
out.print("Blah...");
and more
to understand what happens to a jsp look into /work/catalina/blah.../
There are two pages. The first one is the Main Page. This one performs some
pseudo calcs.
Based on those calcs, either Success.jsp or Failure.jsp is returned.
This code will do what you wanted to have achieved.....
Even though as the others pointed out, there are more advanced techniques as of
late, still in order to dance, first you have to know the moves....
Primarily look at this
cObj.Print(request, response); in the 2nd jsp page.
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<%# page import="rustler.Beans.Beany" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP and JavaBean</title>
<%-- create an instance of Customer class --%>
<jsp:useBean id="cObj" scope="request" class="rustler.Beans.Beany">
<%-- Set the value of attribute such as CustID --%>
<jsp:setProperty name="cObj" property="*" />
</jsp:useBean>
</head>
<body>
<%
int x=cObj.setStoreCust();
if(x>=1)
{
%>
<jsp:forward page="Success.jsp" />
<%
}
else
{
%>
<jsp:forward page="Failure.jsp" />
<%
}
%>
</body>
</html>
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<%# page import="rustler.Beans.Beany" %>
<%# page import="javax.servlet.http.HttpServletRequest" %>
<%# page import="javax.servlet.http.HttpServletResponse" %>
<!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>Failure!</title>
<%-- create an instance of Customer class --%>
<jsp:useBean id="cObj" scope="request" class="rustler.Beans.Beany">
<%-- Set the value of attribute such as CustID --%>
<jsp:setProperty name="cObj" property="*" />
</jsp:useBean>
</head>
<body>
<%cObj.Print(request, response);%>
</body>
</html>
Java Bean
package rustler.Beans;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Beany implements Serializable
{
public Beany()
{
}
/**
*
*/
private static final long serialVersionUID = 1L;
private String custID;
private String custName;
private int qty;
private float price;
private float total;
private int storeCust;
public String getCustID() {
return custID;
}
public void setJunk(String sStr)
{
//System.out.println("What a punk!");
custName = sStr;//"What a punk!";
}
public void Print(HttpServletRequest request,HttpServletResponse response)
{
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>haha</p>");
}catch(IOException e){
e.printStackTrace();
}
}
public String prntJunk()
{
//System.out.println("What a punk!");
return custName;//"What a punk!";
}
public void setCustID(String custID) {
this.custID = custID;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public float getTotal() {
return total;
}
public void setTotal(float total) {
this.total = total;
}
public int setStoreCust()
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/usermaster","admin","password");
PreparedStatement pstmt=null;
String query=null;
query="insert into customer values(?,?,?,?,?)";
pstmt=con.prepareStatement(query);
pstmt.setString(1,custID);
pstmt.setString(2,custName);
pstmt.setInt(3,qty);
pstmt.setFloat(4,price);
pstmt.setFloat(5,total);
int i=pstmt.executeUpdate();
this.storeCust=i;
}
catch(Exception e)
{
}
return storeCust;
}
}

Categories