Data show on servlet, not on jsp? - sql-server-2008

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:

Related

How do I select the text within this element in jsoup?

EDIT: The website is http://www.op.gg/statistics/champion/
I am trying to select the text withing the element highlighted in gray in this photo: https://i.gyazo.com/cc31794574692e2bc6709e193b27741c.png
I've tried the following plus some other variations but none seem to work.
Document doc = Jsoup.connect("http://www.op.gg/statistics/champion/").get();
String s = "";
s += doc.select("table.StatisticsChampionTable.sortable.tablesorter.tablesorter-default
.Content .Row.Top .Cell.ChampionName a").text();
Give this a try:
doc.select(".StatisticsChampionTable .ChampionName a").text()
Maybe this could help you next time.
Try this it may helps you.
You have to scrap the data with the combination of WebView and Jsoup.
First of all load the webpage in the webview and put the webview visibility invisible or gone. And than parse the HTML string into the JSoup.Than you can easily find that all tags which you needed and here is the example code as per your requirement.
public class MainActivity extends AppCompatActivity {
Handler handlerForJavascriptInterface = new Handler();
private WebView mWebView;
private String mURL = "http://www.op.gg/statistics/champion/";
private String html_source;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = findViewById(R.id.wv);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new MyJavaScriptInterface(MainActivity.this), "HtmlViewer");
mWebView.loadUrl(mURL);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Page loading started
}
#Override
public void onPageFinished(WebView view, String url) {
mWebView.loadUrl("javascript:window.HtmlViewer.showHTML" +
"('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
}
});
}
class MyJavaScriptInterface {
private Context ctx;
MyJavaScriptInterface(Context ctx) {
this.ctx = ctx;
}
#JavascriptInterface
public void showHTML(final String html) {
//code to use html content here
handlerForJavascriptInterface.post(new Runnable() {
#Override
public void run() {
html_source = html;
new Description().execute();
}
});
}
}
private class Description extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// Connect to the web site
Document mBlogDocument = Jsoup.parse(html_source);
int mPaginationSize = mBlogDocument.select("td[class=Cell ChampionName]").size();
for (int page = 0; page < mPaginationSize; page++) {
String mChampionName = mBlogDocument.select("td[class=Cell ChampionName]").eq(page).text();
Log.i("Champion Name " + page, mChampionName + "\n");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Set description into TextView
}
}
}
import java.io.IOException;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class Snippet {
public static void main(String args[]) throws IOException, InterruptedException {
Document doc = Jsoup.connect("http://www.op.gg/statistics/ajax2/champion/").get();
List<Element> links = doc.select("table > tbody > tr > .Cell.ChampionName > a");
for (Element link : links) {
System.out.println(link.absUrl("href"));
}
}
}
Sample Output:
http://www.op.gg/champion/Taric/
http://www.op.gg/champion/Quinn/
http://www.op.gg/champion/Kled/
http://www.op.gg/champion/Draven/
http://www.op.gg/champion/MonkeyKing/
http://www.op.gg/champion/Yorick/
http://www.op.gg/champion/Zilean/
http://www.op.gg/champion/Zyra/
http://www.op.gg/champion/Morgana/
http://www.op.gg/champion/Singed/
http://www.op.gg/champion/Nocturne/
http://www.op.gg/champion/Nami/
http://www.op.gg/champion/Udyr/

Unable to print many results in a loop in jsp page

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.

Data not inserted in mySQL database from jsp form

New to the world of struts2 and hibernate. I designed a form to perform CRUD operations. Projects runs without any errors... But when I submit the form values are not inserted in mySQL database. Another issue - existing values from mySQL table are not populated in datatable on jsp form. Following is code from jsp and other class files. I need to understand if I've missed something here
<%--
Document : ctsFrmCaseCategory
Created on : Nov 17, 2015, 9:30:00 PM
Author : nishad
--%>
<%# 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">
<%#taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
<s:head />
<style type="text/css">
#import url(style.css);
</style>
</head>
<body>
<s:form action="saveOrUpdateCategory">
<s:push value="category">
<s:hidden name="ccg_ID" />
<s:textfield name="ccg_CategoryName" label="Category Name" />
<s:textfield name="ccg_Description" label="Description" />
<s:checkbox name="ccg_DeleteFlag" label="Delete User?" />
<s:checkbox name="ccg_ActiveFlag" label="Active User?" />
<s:hidden name="ccg_CreateDate" />
<s:hidden name="ccg_CreateUser" />
<s:hidden name="ccg_ModifyDate" />
<s:hidden name="ccg_ModifyUser" />
<s:submit />
</s:push>
</s:form>
<s:if test="categoryList.size() > 0">
<div class="content">
<table class="userTable" cellpadding="5px">
<tr class="even">
<th>Category Name</th>
<th>Description</th>
<th>Delete Flag</th>
<th>Active Flag</th>
<th>Create Date</th>
<th>Create User</th>
<th>Modify Date</th>
<th>Modify User</th>
</tr>
<s:iterator value="categoryList" status="categoryStatus">
<tr
class="<s:if test="#categoryStatus.odd == true ">odd</s:if><s:else>even</s:else>">
<td><s:property value="ccg_CategoryName" /></td>
<td><s:property value="ccg_Description" /></td>
<td><s:property value="ccg_DeleteFlag" /></td>
<td><s:property value="ccg_ActiveFlag" /></td>
<td><s:property value="ccg_CreateDate" /></td>
<td><s:property value="ccg_CreateUser" /></td>
<td><s:property value="ccg_ModifyDate" /></td>
<td><s:property value="ccg_ModifyUser" /></td>
<td><s:url id="editURL" action="editCategory">
<s:param name="ccg_ID" value="%{ccg_ID}"></s:param>
</s:url> <s:a href="%{editURL}">Edit</s:a></td>
<td><s:url id="deleteURL" action="deleteCategory">
<s:param name="ccg_ID" value="%{ccg_ID}"></s:param>
</s:url> <s:a href="%{deleteURL}">Delete</s:a></td>
</tr>
</s:iterator>
</table>
</div>
</s:if>
</body>
</html>
CategotyDAO.java code ---
package com.cts.dao;
import java.util.List;
import com.cts.domain.Category;
public interface CategoryDAO {
public void saveOrUpdateCategory(Category category);
public List<Category> listCategory();
public Category listCategoryById(Long categoryId);
public void deleteCategory(Long categoryId);
}
CategoryDAOImpl.java code ---
package com.cts.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.cts.domain.Category;
public class CategoryDAOImpl implements CategoryDAO {
#SessionTarget
Session session;
#TransactionTarget
Transaction transaction;
/**
* Used to save or update a category.
*/
public void saveOrUpdateCategory(Category category) {
try {
session.saveOrUpdate(category);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to delete a category.
*/
public void deleteCategory(Long categoryId) {
try {
Category category = (Category) session.get(Category.class, categoryId);
session.delete(category);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to list all the categorys.
*/
#SuppressWarnings("unchecked")
public List<Category> listCategory() {
List<Category> courses = null;
try {
courses = session.createQuery("from Category").list();
} catch (Exception e) {
e.printStackTrace();
}
return courses;
}
/**
* Used to list a single category by Id.
*/
public Category listCategoryById(Long categoryId) {
Category category = null;
try {
category = (Category) session.get(Category.class, categoryId);
} catch (Exception e) {
e.printStackTrace();
}
return category;
}
}
CategoryAction.java code ---
package com.cts.web;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.cts.dao.CategoryDAO;
import com.cts.dao.CategoryDAOImpl;
import com.cts.domain.Category;
public class CategoryAction extends ActionSupport implements ModelDriven<Category> {
private static final long serialVersionUID = -6659925652584240539L;
private Category category = new Category();
private List<Category> categoryList = new ArrayList<Category>();
private CategoryDAO categoryDAO = new CategoryDAOImpl();
public Category getModel() {
return category;
}
/**
* To save or update category.
* #return String
*/
public String saveOrUpdate()
{
categoryDAO.saveOrUpdateCategory(category);
return SUCCESS;
}
/**
* To list all categories.
* #return String
*/
public String list()
{
categoryList = categoryDAO.listCategory();
return SUCCESS;
}
/**
* To delete a category.
* #return String
*/
public String delete()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
categoryDAO.deleteCategory(Long.parseLong(request.getParameter("ccg_ID")));
return SUCCESS;
}
/**
* To list a single category by Id.
* #return String
*/
public String edit()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
category = categoryDAO.listCategoryById(Long.parseLong(request.getParameter("ccg_ID")));
return SUCCESS;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public List<Category> getCategoryList() {
return categoryList;
}
public void setCategoryList(List<Category> categoryList) {
this.categoryList = categoryList;
}
}
Category.java code ---
package com.cts.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
#Entity
#Table(name = "cts_mcasecategory")
public class Category {
private Long ccg_ID;
private String ccg_CategoryName;
private String ccg_Description;
private boolean ccg_DeleteFlag;
private boolean ccg_ActiveFlag;
private Date ccg_CreateDate;
private int ccg_CreateUser;
private Date ccg_ModifyDate;
private int ccg_ModifyUser;
#Id
#GeneratedValue
#Column(name = "ccg_ID")
public Long getCcg_ID() {
return ccg_ID;
}
public void setCcg_ID(Long ccg_ID) {
this.ccg_ID = ccg_ID;
}
#Column(name = "ccg_CategoryName")
public String getCcg_CategoryName() {
return ccg_CategoryName;
}
public void setCcg_CategoryName(String ccg_CategoryName) {
this.ccg_CategoryName = ccg_CategoryName;
}
#Column(name = "ccg_Description")
public String getCcg_Description() {
return ccg_Description;
}
public void setCcg_Description(String ccg_Description) {
this.ccg_Description = ccg_Description;
}
#Column(name = "ccg_DeleteFlag")
public boolean isCcg_DeleteFlag() {
return ccg_DeleteFlag;
}
public void setCcg_DeleteFlag(boolean ccg_DeleteFlag) {
this.ccg_DeleteFlag = ccg_DeleteFlag;
}
#Column(name = "ccg_ActiveFlag")
public boolean isCcg_ActiveFlag() {
return ccg_ActiveFlag;
}
public void setCcg_ActiveFlag(boolean ccg_ActiveFlag) {
this.ccg_ActiveFlag = ccg_ActiveFlag;
}
#Column(name = "ccg_CreateDate")
public Date getCcg_CreateDate() {
return ccg_CreateDate;
}
public void setCcg_CreateDate(Date ccg_CreateDate) {
this.ccg_CreateDate = ccg_CreateDate;
}
#Column(name = "ccg_CreateUser")
public int getCcg_CreateUser() {
return ccg_CreateUser;
}
public void setCcg_CreateUser(int ccg_CreateUser) {
this.ccg_CreateUser = ccg_CreateUser;
}
#Column(name = "ccg_ModifyDate")
public Date getCcg_ModifyDate() {
return ccg_ModifyDate;
}
public void setCcg_ModifyDate(Date ccg_ModifyDate) {
this.ccg_ModifyDate = ccg_ModifyDate;
}
#Column(name = "ccg_ModifyUser")
public int getCcg_ModifyUser() {
return ccg_ModifyUser;
}
public void setCcg_ModifyUser(int ccg_ModifyUser) {
this.ccg_ModifyUser = ccg_ModifyUser;
}
}
Struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="example.xml"/>
<!-- Configuration for the default package. -->
<package name="default" extends="struts-default">
<action name="saveOrUpdateCategory" method="saveOrUpdate" class="com.cts.web.CategoryAction">
<result name="success" type="redirect">listCategory</result>
</action>
<action name="listCategory" method="list" class="com.cts.web.CategoryAction">
<result name="success">/ctsFrmCaseCategory.jsp</result>
</action>
<action name="editCategory" method="edit" class="com.cts.web.CategoryAction">
<result name="success">/ctsFrmCaseCategory.jsp</result>
</action>
<action name="deleteCategory" method="delete" class="com.cts.web.CategoryAction">
<result name="success" type="redirect">listCategory</result>
</action>
</package>

passing the object from one servlet to another

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>

Getting value from dropdownlist in jsp to spring mvc controller using hibernate annottations

Hi I am writing a program using spring mvc hibernate and mysql as database.I have two tables employee and team in mysql db.I am using jsp as my view.In my jsp i am loading team names from team table to a dropdownlist.I want to display all employees in specefic team when i select the specefic team from the dropdown list and click the submitt buttton
Here is my jsp
<%#page import="java.sql.ResultSet"%>
<%#page import="com.mysql.jdbc.PreparedStatement"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
<form:form method="POST" action="Search.html" modelAttribute="command">
<table>
<tr>
<form:label path="teams.teamId">Team Name</form:label>
<td>
<form:select path="teams.teamId" cssStyle="width: 150px;">
<option value="-1">Select a type</option>
<c:forEach items="${teamKey}" var="teams">
<option value="${teams.teamId}">${teams.teamName}</option>
</c:forEach>
</form:select>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="submit"> </td>
</tr>
</table>
</form:form>
<h1>Home</h1>
</body>
</html>
my jsp view
controller code
#RequestMapping(value="/Search",method = RequestMethod.POST)
public ModelAndView fromSearch(#ModelAttribute("command") Resource resource,BindingResult result){
return new ModelAndView("redirect:/searchResult.html");
}
#RequestMapping(value="/searchResult",method = RequestMethod.GET)
public String getValue(#ModelAttribute("command") Resource resource ,Model m){
m.addAttribute("command", "Got value here"+resource.toString());
return "Search";
}
Resource class
#Entity
#Table(name="Employee")
public class Resource implements Serializable {
private static final long serialVersionUID = -723583058586873479L;
#Id
#Column(name="empid")
private Integer empId;
#Column(name="empname")
private String empName;
#Column(name="empexp")
private Integer empExp;
#Column(name="empskills")
private String empSkills;
#ManyToOne
#JoinColumn(name="teamId",referencedColumnName="teamId")
private AddTeam teams;
public Integer getEmpId(){
return empId;
}
public void setEmpId(Integer empId){
this.empId=empId;
}
public String getEmpName(){
return empName;
}
public void setEmpName(String empName){
this.empName=empName;
}
public Integer getEmpExp(){
return empExp;
}
public void setEmpExp(Integer empExp){
this.empExp=empExp;
}
public String getEmpSkills(){
return empSkills;
}
public void setEmpSkills(String empSkills){
this.empSkills=empSkills;
}
public AddTeam getTeams() {
return teams;
}
public void setTeams(AddTeam teams) {
this.teams = teams;
}
}
AddTeam.class
#Entity
#Table(name="Team")
public class AddTeam {
#Id
#Column(name="teamId")
private Integer teamId;
#Column(name="teamName")
private String teamName;
public Integer getTeamId() {
return teamId;
}
public void setTeamId(Integer teamId) {
this.teamId = teamId;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
}
ResourceDao Impl class
#Override
public void serchResources(int teamid) {
// TODO Auto-generated method stub
sessionfactory.getCurrentSession().createQuery(" FROM Resource WHERE teamId=" +teamid);
}
Error
org.springframework.beans.NotReadablePropertyException: Invalid property 'teams' of bean class [java.lang.String]: Bean property 'teams' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:665)
org.springframework.beans.BeanWrapperImpl.getNestedBeanWrapper(BeanWrapperImpl.java:518)
org.springframework.beans.BeanWrapperImpl.getBeanWrapperForPropertyPath(BeanWrapperImpl.java:495)
org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:655)
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:147)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
org.apache.jsp.WEB_002dINF.views.Search_jsp._jspx_meth_form_005flabel_005f0(Search_jsp.java:306)
org.apache.jsp.WEB_002dINF.views.Search_jsp._jspService(Search_jsp.java:117)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I am new to spring hibernate application , i am stuck here.Is there any method to display the selected teams employee...
Thanks for any advice...
Your code would be hard to maintain :
you call Resource what could be called Employee class (table name is Employee)
you call AddTeam what could be called Team class (table name is Team)
you call teams (plural) a single AddTeam element
you use a full Resource object to simply get a team
all that without a comment
I suppose you just want to get a team in that jsp, and the form sends correctly a teamId. It can work that way, thanks to spring magic, but you need to declare a Converter<String, AddTeam> to convert the String sent by browser (representation of the teamId) to the AddTeam having that id.
To have it integrating prorperly in spring you must :
declare a FormattingConversionServiceFactoryBean bean (if you don't, you will loose all default conversions)
declare a Converter<String, AddTeam> bean for the conversion String -> Integer -> AddTeam and register it into the above ConversionService
And in your form, the path for the select should only be teams :
<form:select path="teams" ...
It is a rather advanced config, but it can work.
If you prefere something less magic, use a true form (not a model object) :
class TeamCommand {
private int teamId;
// getter and setter ommitted for bievety
}
In your controller :
#RequestMapping(value="/Search",method = RequestMethod.POST)
public ModelAndView fromSearch(#ModelAttribute("command") TeamCommand command,BindingResult result){
AddTeam team = service.method(command.getTeamId);
...
return new ModelAndView("redirect:/searchResult.html");
}
In your JSP :
<form:select path="teamId" ...>
Here are some changes that may solve your problem,
in jsp file
Current
<form:select path="teams.teamId" cssStyle="width: 150px;">
Have to change
<form:select path="teams" cssStyle="width: 150px;">
In your controller class
Current
public String getValue(#ModelAttribute("command") Resource resource ,Model m)
Have to change
public String getValue(#ModelAttribute("command") Resource resource ,Model m,
#RequestParam("teams") String teamId)
and add below code in your controller class
#InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(AddTeam.class, new PropertyEditorSupport() {
#Override
public void setAsText(String text) {
AddTeam teams = new AddTeam();
teams.setTeamId(Integer.valueOf(text));
this.setValue(teams);
}
});
}
Hope this will solve your problem. :)