I have inserted many records in table while displaying the record last inserted record is displaying for a particular ID.But all the records are inserted in database.Though it is not showing? Please see the code and tell where have I done wrong?
DAO CODE
package org.fproject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
public class StudyDAO {
private String driver="com.mysql.jdbc.Driver";
private String url="jdbc:mysql://localhost:3306/mydb";
private String dbuser="root";
private String dbpassword="root123";
private String commdetSQL="select cid,fname,lname,email,comment from comment where qid=?";
private Connection con;
private PreparedStatement pstmtcommdisplay;
public StudyDAO()throws ClassNotFoundException,SQLException{
Class.forName(driver);
con=DriverManager.getConnection(url,dbuser,dbpassword);
pstmtcommdisplay=con.prepareStatement(commdetSQL);
}
public Collection<Comment> getComment(int qid)throws SQLException{
pstmtcommdisplay.setInt(1, qid);
ResultSet rs=pstmtcommdisplay.executeQuery();
ArrayList<Comment>list4=null;
while(rs.next()){
list4=new ArrayList<Comment>();
Comment c=new Comment(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5));
list4.add(c);
}
return list4;
}
}
Servlet Code
package org.fproject;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class DisCommServlet
*/
#WebServlet("/DisCommServlet")
public class DisCommServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DisCommServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
String strqid=req.getParameter("qid");
int qid=Integer.parseInt(strqid);
try{
StudyDAO dao=new StudyDAO();
Collection<Comment> list4=dao.getComment(qid);
//req.setAttribute("LIST4", list4);
//req.setAttribute("QID", qid);
HttpSession s=req.getSession(true);
s.setAttribute("LIST4", list4);
s.setAttribute("QID", qid);
res.sendRedirect("DisComm.jsp");
}catch(ClassNotFoundException e){
e.printStackTrace();
res.sendError(9999,"Error in classloading");
}catch(SQLException e){
e.printStackTrace();
res.sendError(9998,"Error in sql:"+e.getMessage()+"Error code:"+e.getErrorCode()+e.getSQLState());
}catch(Exception e){
res.sendError(8000,"Unknown Error"+e.getMessage());
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*,org.fproject.*"%>
<!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>Answers</title>
</head>
<body>
<%
int qid=(Integer)session.getAttribute("QID");
Collection<Comment> list4=(Collection<Comment>)session.getAttribute("LIST4");
%>
<%if(list4!=null){ %>
<% for(Comment c:list4){ %>
<br><hr><%=c.getFname() %> <%=c.getLname() %><br><%=c.getEmail() %><br><p><b><%=c.getComment() %></b></p>
<% } %>
<%} else { %>
<h3>No answers are added</h3>
<% }%>
</body>
</html>
Only one record is displaying but all records are inserting in database.
in your studyDAO.java
while(rs.next()){
list4=new ArrayList<Comment>();
the above code should be
list4=new ArrayList<Comment>();
while(rs.next()){
now it will work.
Related
I try to write my website with spring framework in back- and thymeleaf in frontend on tomcat local server. I try add css to my html file. Css file seems to be linked on server, but devtools shows that it is empty. Do you know what could i miss?
EDIST: sorry for posting pictures, I will know better next time. I left minimum i wanted to show.
index.css
h1{
color: red;
}
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleag.org">
<head>
<meta charset="UTF-8">
<title>Index</title>
<link rel="stylesheet" href="../css/index.css" th:href="#{../css/index.css}"/>
</head>
<body>
<h1>Hello</h1>
Greeting
Registration
</body>
</html>
HomePageController.java
package com.krs.GreatBookOfDiet.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
#Controller
public class HomePageController {
#GetMapping("")
public String index(Map<String, Object> model){
return "index";
}
}
GreatBookOfDietConfiguration.java
package com.krs.GreatBookOfDiet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import java.util.Locale;
#Configuration
public class GreatBookOfDietConfiguration implements WebMvcConfigurer {
#Autowired
private ApplicationContext applicationContext;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**").addResourceLocations("/WEB-INF/pdf/");
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
#Bean
public LocaleResolver localeResolver(){
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.US);
return slr;
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor(){
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci;
}
#Bean
public ViewResolver thymeleafResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(0);
return viewResolver;
}
#Bean
public SpringResourceTemplateResolver templateResolver(){
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
}
file structure
devtools on server, index.css view
Your static resources in the /WEB-INF/css folder are not served by Spring, therefore a request for http://example.com/app/css/index.css returns a 404 error.
You need to modify your addResourceHandlers method:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**")
.addResourceLocations("/WEB-INF/pdf/");
registry.addResourceHandler("/css/**")
.addResourceLocations("/WEB-INF/css/");
}
Remark: Given the popularity of Spring Boot, you might consider using the same locations for static resources (cf. documentation), which sums up to the following configuration:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/");
}
Above is what I am trying to create
Hi,
Above is what I am trying to create using spring boot. My question is how do I properly iterate through a forEach loop and pull out the necessary data needed in JSP?
I thought I was doing it correctly but, I keep on getting an error saying
"Don't know how to iterate over supplied "items" in <forEach>"
Please see my code below for what I am currently doing.
Thanks for your help in advance!!!
Controller
#RequestMapping(value = "/showOrders.html")
public String listOrders(Model model) {
ArrayList<Order> orders = os.findAll();
model.addAttribute("allOrders", orders);
return "allOrders";
}
Service class for "Orders"
package com.sales.services;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sales.models.Order;
import com.sales.repositories.OrderRepository;
#Service
public class OrderService {
#Autowired
OrderRepository or;
public ArrayList<Order> findAll() {
return (ArrayList<Order>) or.findAll();
}
}
Repository class for orders
package com.sales.repositories;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.sales.models.Customer;
import com.sales.models.Order;
#Repository
public interface OrderRepository extends CrudRepository<Order, Long> {
}
Order class
package com.sales.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table(name="ORDERS")
public class Order {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="OID")
private Long oId;
#Min(1)
#Column(name="QTY")
private int qty;
#Column(name="ORDDATE")
private String orderDate;
#ManyToOne
#JoinColumn(name="cId")
private Customer cust;
#ManyToOne
#JoinColumn(name="pId")
private Product prod;
public Long getoId() {
return oId;
}
public void setoId(Long oId) {
this.oId = oId;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public Customer getCust() {
return cust;
}
public void setCust(Customer cust) {
this.cust = cust;
}
public Product getProd() {
return prod;
}
public void setProd(Product prod) {
this.prod = prod;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
}
Customer class
package com.sales.models;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotBlank;
#Entity
#Table(name="CUSTOMERS")
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="CID")
private Long cId;
#Column(name="CNAME")
#NotBlank
private String cName;
#OneToMany(mappedBy="cust")
private List<Order> orders = new ArrayList<Order>();
public Long getcId() {
return cId;
}
public void setcId(Long cId) {
this.cId = cId;
}
public String getcName() {
return cName;
}
public void setcName(String cName) {
this.cName = cName;
}
public List<Order> getOrders() {
return orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
}
````````````````````````````````````````````````````````````````````````````````
Product Class
````````````````````````````````````````````````````````````````````````````````
package com.sales.models;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import org.hibernate.validator.constraints.NotBlank;
#Entity
#Table(name="PRODUCTS")
public class Product {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="PID")
private Long pId;
#Column(name="PDESC")
#NotBlank
private String pDesc;
#Column(name="QTYINSTOCK")
#Min(value=0)
private int qtyInStock;
#OneToMany(mappedBy="prod")
private List<Order> ordersForProduct = new ArrayList<Order>();
public Long getpId() {
return pId;
}
public void setpId(Long pId) {
this.pId = pId;
}
public String getpDesc() {
return pDesc;
}
public void setpDesc(String pDesc) {
this.pDesc = pDesc;
}
public int getQtyInStock() {
return qtyInStock;
}
public void setQtyInStock(int qtyInStock) {
this.qtyInStock = qtyInStock;
}
public List<Order> getOrdersForProduct() {
return ordersForProduct;
}
public void setOrdersForProduct(List<Order> ordersForProduct) {
this.ordersForProduct = ordersForProduct;
}
}
````````````````````````````````````````````````````````````````````````````````
Jsp file where I am trying to pull all the data from
````````````````````````````````````````````````````````````````````````````````
```````````````````````````````````````````````````````````````````````````````
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<link href="/css/style.css" rel="stylesheet"></link>
<head>
<meta charset="ISO-8859-1">
<title>List of Orders</title>
</head>
<body>
<h1>List of Orders</h1>
<c:forEach items="${allOrders}" var="ords">
<b>${ords.oId} </b>
<table>
<tr>
<th>Quantity</th>
<th>Order Date</th>
<th>Customer ID</th>
<th>Customer Name</th>
<th>Product ID</th>
<th>Description</th>
</tr>
<tr>
<c:forEach items="${ords}" var="order">
<tr>
<td>${order.qty}</td>
<td>${order.orderDate}</td>
<c:forEach items="${ords.cust}" var="order">
<td>${order.cId}</td>
<td>${order.cName}</td>
<c:forEach items="${ords.prod}" var="order">
<td>${order.pId}</td>
<td>${order.pDesc}</td>
</c:forEach>
</c:forEach>
</tr>
</c:forEach>
</tr>
</table>
</c:forEach>
</body>
</html>
````````````````````````````````````````````````````````````````````````````````````
Below is the solve for this question
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<link href="/css/style.css" rel="stylesheet"></link>
<head>
<meta charset="ISO-8859-1">
<title>List of Customers</title>
</head>
<body>
<h1>List of Customers</h1>
<c:forEach items="${ordrs}" var="ords">
<c:forEach items="${ords.orders}" var="order">
<b>${order.oId} </b>
<table>
<tr>
<th>Quantity</th>
<th>Order Date</th>
<th>Customer ID</th>
<th>Customer Name</th>
<th>Product ID</th>
<th>Description</th>
</tr>
<tr>
<td>${order.qty}</td>
<td>${order.orderDate}</td>
<td>${ords.cId}</td>
<td>${ords.cName}</td>
<td>${order.prod.pId}</td>
<td>${order.prod.pDesc}</td>
</tr>
</table>
</c:forEach>
</c:forEach>
</body>
</html>
`````````````````````````````````````````````````````````````````````````````````````````
Hi there,
My task is displaying a list of object from database to JSP. But i don't know why it only show when i run servlet class,while not show anything when i run JSP. First I used setAttribute method to pass the list to JSP and at JSP i use JSTL tags for retriving data. I think everything is ok but don't why it happend like that. Here's my code
Asiakas.java
package Luokat;
public class Asiakas {
private int asiakas_id;
private String nimi;
private int puhelinnumero;
private String spostiosoite;
/**
*
*/
public Asiakas() {
asiakas_id = 0;
nimi= null;
puhelinnumero =0;
spostiosoite = null;
}
/**
* #param asiakas_id
* #param nimi
* #param puhelinnumero
* #param spostiosoite
*/
public Asiakas(int asiakas_id, String nimi, int puhelinnumero,
String spostiosoite) {
super();
this.asiakas_id = asiakas_id;
this.nimi = nimi;
this.puhelinnumero = puhelinnumero;
this.spostiosoite = spostiosoite;
}
public int getAsiakas_id() {
return asiakas_id;
}
public void setAsiakas_id(int asiakas_id) {
this.asiakas_id = asiakas_id;
}
public String getNimi() {
return nimi;
}
public void setNimi(String nimi) {
this.nimi = nimi;
}
public int getPuhelinnumero() {
return puhelinnumero;
}
public void setPuhelinnumero(int puhelinnumero) {
this.puhelinnumero = puhelinnumero;
}
public String getSpostiosoite() {
return spostiosoite;
}
public void setSpostiosoite(String spostiosoite) {
this.spostiosoite = spostiosoite;
}
#Override
public String toString() {
return "Asiakas [asiakas_id=" + asiakas_id + ", nimi=" + nimi
+ ", puhelinnumero=" + puhelinnumero + ", spostiosoite="
+ spostiosoite + "]";
}
}
NaytaAsiakasServlet
package Servletit;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import DBHoitaja.DBHoitaja;
import Luokat.Asiakas;
/**
* Servlet implementation class NaytaAsiakasServlet
*/
#WebServlet("/NaytaAsiakasServlet")
public class NaytaAsiakasServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public NaytaAsiakasServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
NaytaAsiakasServlet nayta = new NaytaAsiakasServlet();
request.setAttribute("asiakasLista", nayta.findAll());
request.getRequestDispatcher("admin_page.jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public List<Asiakas> findAll(){
List<Asiakas> list = new ArrayList<Asiakas>();
try {
list.add(new Asiakas(0, "Kaísa",0445206766,"kaisaa#haaga-helia.fi"));
list.add(new Asiakas(1, "Kaísa",0445206766,"kaisaa#haaga-helia.fi"));
list.add(new Asiakas(3, "Kaísa",0445206766,"kaisaa#haaga-helia.fi"));
} catch(Exception e){
list =null;
}
return list;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
admin_page.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Ylläpito Sivu</title>
</head>
<body>
<table border="1" cellpadding="2" cellspacing="2" width="500">
<tr>
<th>Id</th>
<th>Nimi</th>
<th>Puhelin</th>
<th>Sähköposti</th>
</tr>
<c:forEach var="asiakas" items="${asiakasLista}" >
<tr>
<td><c:out value="${asiakas.asiakas_id}" /></td>
<td><c:out value="${asiakas.nimi}" /></td>
<td><c:out value="${asiakas.puhelinnumero}" /></td>
<td><c:out value="${asiakas.spostiosoite}" /></td>
</tr>
</c:forEach>
</table>
</body>
</html>
From your question I can understand that you are totally new to J2EE!! And also you are trying to run the servlet class and JSP, which is not going to work anyway.
Please read the below specified tutorials and have some idea on how run a simple web application.
how to write hello world servlet Example
Sample Code for Hello World:
i have a HTML form(index.html) of three links which are login, logout and profile. After clicking on login link a HTML page is displayed with two fields named username and password. After entering correct username and password my servlet1 responses a message like "welcome user". my logout link is associated with a servlet2 which deletes cookies for current request and displays a message "successfully logout" when clicked. I would like to know all request and response objects associated with three links(login,logout,profile) in my index.html file
will be same for a user? i am also mentioning my code here:
login.java:
package loginandlogout;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Login extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out= response.getWriter();
request.getRequestDispatcher("link.html").include(request,response);
String name=request.getParameter("username");
String password=request.getParameter("password");
if(password.equals("admin"))
{
out.println("you are successfully login...");
out.println("welcome "+name);
Cookie ck= new Cookie("name",name);
response.addCookie(ck);
}
else
{
out.println("Not authorized");
request.getRequestDispatcher("login.html").include(request, response);
}
}
}
logout.java:
package loginandlogout;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Logout extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
int j=0;
response.setContentType("text/html");
PrintWriter out= response.getWriter();
Cookie ck[]=request.getCookies();
if(ck==null||ck[0].equals(""))
{
request.getRequestDispatcher("link.html").include(request, response);
out.println("without login how can logout you..");
}
else
{
int i;
int size1=ck.length;
for(i=0; i<size1; i++)
{
String ckname=ck[i].getValue();
if(ckname.equals(request.getParameter("username")))
{
out.println("successfully logout when i am in loop");
j=i;
break;
}
}
ck[j]=new Cookie("name","");
ck[j].setMaxAge(0);
response.addCookie(ck[j]);
request.getRequestDispatcher("link.html").include(request, response);
out.println("successfully logout " +ck[j].getValue());
}
}
}
profile.java
package loginandlogout;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Profile extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out= response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
Cookie ck[]=request.getCookies();
if(ck !=null)
{
String name= ck[0].getValue();
if(!name.equals("")|| name!=null)
{
out.println("welcome "+name);
}
else
out.println("please loing first");
}
else
{
out.println("please loing first");
}
}
}
index.html:
<!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>home page</title>
</head>
<body>
<h1>welcome to my home page...</h1>
<br />
login|
logout|
profile
</body>
</html>
I send a json from page to server with YUI and how to get data from json in servlet. I use jackson lib 2.4. Thanks!!!
var user = {
userName: username,
password: password,
customerId: customerId
};
new Y.IO().send("http://localhost:7778/MyController", {
method: 'POST',
data: user
});
actually, when you make a request like this
<html>
<body>
<script src="http://yui.yahooapis.com/3.14.1/build/yui/yui-min.js"></script>
<script>
var user = {
userName: 'x1',
password: 'y2',
customerId: 'z3'
};
YUI().use('io-form', function (Y) {
new Y.IO().send("http://localhost:8080/web/MyController", {
method: 'POST',
data: user
});
});
</script>
</body>
</html>
you're not sending a JSON object to the servlet. Instead, you're creating a http request where each property of your javascript object (which is represented in the JSON format) is sent as an http POST property, so you can retrieve these values like this
package mine;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MyController
*/
#WebServlet("/MyController")
public class MyController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public MyController() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String[]> map = request.getParameterMap();
for(Entry<String,String[]> entry:map.entrySet()){
System.out.println(entry.getKey());
System.out.println(entry.getValue()[0]);
}
}
}
which in turn prints this
userName
x1
password
y2
customerId
z3
so you don't need jackson to parse the data you retrieve from your page.